# Downcity — Full Documentation
> Complete text of the Downcity documentation, SDK references, and articles.
> Generated from the same MDX sources that render the website.
## Docs
### Downcity Docs
Source: https://downcity.ai/en/docs/
Downcity is agent infrastructure for AI builders. These docs help you run local agents, connect City, connect models and powers, and turn agent workflows into real product surfaces.
The shortest product model:
- products own the user experience
- agents execute work inside explicit runtime boundaries
- Downcity provides the reusable runtime layer for models, tools, tasks, memory, services, permissions, usage, billing, and control surfaces
## Start Here
## Run and Control
- [Agent](/en/docs/agent/overview/): execution capabilities and runtime boundaries.
- [Power](/en/docs/power/overview/): tools and integrations.
- [City](/en/docs/city/overview/): hosts, resources, and workspaces.
- [Federation & Service](/en/docs/federation/overview/): shared models and product services.
- [Security](/en/docs/security/overview/): permissions, approvals, and isolation.
- [CLI](/en/docs/cli/overview/): manage your local runtime from the terminal.
## Documentation Spaces
- [Products](/en/docs/): product-level docs: Agent, Power, City, Federation, security, and reference.
- [Agent SDK](/en/agent-sdk-docs/): programmable agents, sessions, local/remote agent, model binding, and power APIs.
- [City SDK](/en/city-sdk-docs/): `City`, `Federation`, downcity identity, tokens, service/action infrastructure, and deployment.
- [Payments](/en/payments/): accounts, balance, usage, and Stripe payment services.
- [Agent Powers Docs](/en/powers-docs/): built-in power manuals and power examples.
- [UI SDK](/en/ui-sdk-docs/): reusable UI components and Workboard surfaces.
### Getting Started
Source: https://downcity.ai/en/docs/quickstart/
Downcity has several user surfaces. This page is a map, not a command tutorial.
Use it to decide where to start:
- Use [Downcity CLI](/en/docs/reference/cli) when you want to run local agents, manage project agents, or use built-in power commands.
- Use [CLI](/en/city-sdk-docs/packages/cli) and its `fed/downfed` commands when you want to create, manage, or deploy a Federation project.
- Use [Agent SDK](/en/agent-sdk-docs) when you want to embed agent behavior in your own Node.js application.
- Use [City SDK](/en/city-sdk-docs) when you want to build services, model providers, billing, usage, or admin surfaces.
- Use [Agent Powers Docs](/en/powers-docs) when you want to understand built-in power behavior or author power integrations.
- Use [Products Docs](/en/docs) when you want product-facing usage for Downcity CLI, Downcity Console, or Chrome Extension.
## Recommended Order
First understand the model:
1. [How Downcity Fits Together](/en/docs/concepts/project-logic-overview)
2. [Agent Overview](/en/docs/agent/overview/what-is-agent)
3. [Configuration Model](/en/docs/configuration/overview)
Then choose the practical surface:
- Local CLI usage: [Downcity CLI](/en/docs/reference/cli)
- Project agent workflows: [Agent CLI product docs](/en/docs/reference/cli)
- Power workflows: [Power CLI product docs](/en/docs/reference/cli)
- Federation / local Agent commands: [CLI](/en/city-sdk-docs/packages/cli)
- SDK integration: [Agent SDK](/en/agent-sdk-docs)
## What This Space Explains
Downcity docs explain why the system is split into Downcity, City, Agent, powers, services, permissions, and configuration layers.
Concrete command flags, examples, and step-by-step operation guides live in product or SDK documentation.
### Desktop messages
Source: https://downcity.ai/en/docs/desktop/
{/* User-facing guide to file previews and Desktop Agent messages. */}
## System requirements
The macOS app requires **macOS 13 Ventura or later**.
## Inputs and focus
Search fields, settings forms, and multiline editors share a consistent input style. Hover subtly changes the background; clicking or entering with the keyboard keeps a clearer focus background visible. Inputs do not draw an outer focus ring that extends beyond panel or scrolling boundaries. Search headers and chat editors show focus on one input container, without a second background on inner fields. Read-only content remains selectable and copyable, disabled fields appear subdued, and validation messages appear beside the field.
Chat drafts are saved automatically on this device after you pause typing. Leaving the input area or switching sessions immediately saves any pending changes. Each session restores its own draft when you return.
## Test System One decision models
Open **Settings → Models**, select JEV or another model in the decision model section, and use **Test decision model** in its details. A ready-to-run example is prefilled. Edit the content and decision instructions, choose Boolean, Choice, or Score, then select **Run test**. Choice accepts one distinct option per line (2–255 options); Score requires a minimum and maximum with a range width of 1–9. Update the instructions to match the selected answer type.
The result shows structured answers, any returned probability or option distribution, usage when provided, and elapsed time. Failures appear in the same form so you can correct the input and retry. Tests use the current account and the model's normal billing. Closing the details does not cancel a request already submitted.
## City Remote
Open **Settings → General → City Remote** to enable HTTP access, initially bound to `127.0.0.1:5314`. The switch applies immediately; save changes after editing the address or port. The page shows the actual running status, connection URL or startup failure. Copy the running URL into Chrome settings; there is no need to run `city on` separately.
Create a City Token on the same page, choosing its name, allowed Agents (or explicitly all existing and future Agents), and expiry. The creation dialog offers 30 days, 90 days, no expiry or a custom date. Plaintext is shown once in a separate dialog: copy it into Chrome's access credential and select Done. Existing Tokens can be edited or revoked. CLI `city token` manages the same records.
HTTP is disabled by default. Enabled settings are restored on Desktop startup. Disabling access, changing listen settings or exiting Desktop disconnects clients. Desktop and CLI retain the single-host model. Loopback is local-only; when binding another address, clients must use the corresponding machine address and network configuration.
## Send follow-ups and take over
When you send a Chat message, it is submitted immediately only while the session is idle and the pending list is empty. While a Turn is still running, or while the pending list already holds messages, new input is appended to the end of that list and submitted one at a time as each Turn finishes, without overtaking what is already queued.
Items in the list are local records until they are submitted: you can edit, delete, reorder, or pause them individually. `Option/Alt + Command/Ctrl + Enter` appends a paused item that never sends automatically; `Command/Ctrl + Shift + Enter` bypasses the whole list and submits the current input immediately without disturbing other queued messages. A rejected submission stays in the list as paused so you can fix and retry it.
Each Turn is owned by its initiating actor. The same user can send follow-ups. When another actor owns the work, a queued submission is rejected and stays in the pending list as paused rather than being discarded. To take over, stop the current work, wait for it to finish stopping, then send your message. Stop targets the Turn shown in the interface; refresh and retry if it has changed. A rejected submission does not mark existing work as failed.
Previously registered callbacks still deliver the stopped work's original result, never the answer from your new Turn.
## Retry a failed Agent response
When the latest visible conversation message is a finished Agent response with a recoverable error, use **Retry** on the right side of its error card. The button is disabled while the session is busy, waiting, or submitting, while messages are queued, while history is loading, or while a retry submission is pending. Resolve pending questions or approvals before retrying; the session also checks these when accepting the request.
Retry keeps previous outputs and tool results available, the failed card stays in history, and a new Agent attempt is appended without a duplicate visible user message. It continues from the existing context rather than replaying the entire request. Actions already performed may run again; retry does not guarantee that side effects happen only once.
While the retry is being submitted, the button shows a spinner and prevents duplicate clicks. If submission fails, an error appears and you can retry once the button is available again.
## Answer questions and approve operations
Pending Agent questions and approvals appear above the chat input in both one-to-one and group chats. The card has a subtle background and rounded corners. Use the left and right arrows to switch between pending items; group items identify the requesting member. Switching pending items or collapsing tool details in a message preserves your input. For multiple questions, use the left and right arrows to revise an answer. Expand the optional note when needed.
Long content scrolls inside the pending area while the chat input stays visible. Successful submissions leave the pending area; failures display an error and preserve your input for retry. Tool details show execution information without repeating approval cards or approval results. Pending interactions are handled above the input, without a separate right-side response panel.
## Compact context manually
In an existing one-to-one Session, type `/` in the composer and select `/compact` to fold older stable conversation content into a context summary. The original chat history stays available. You can submit this while the session is running. Compaction joins the Session queue and runs in queue order at a maintenance checkpoint. Compaction and prompts share the Session queue's busy state. The session loading indicator remains active until the queue drains, including across consecutive commands. The chat timeline shows progress and the result, including when there is nothing to compact. New conversation drafts do not show this command.
Summary history uses plain text: user and Agent bodies plus tool results, without call arguments, call IDs, protocol states, or JSON wrappers. Structured results use indented key-value text to preserve field meanings. Compaction shares model-visible message conversion with regular conversations, excluding UI data, activity records, and reasoning. Attachments retain references and metadata without reloading binary contents. Nested image data URLs and explicitly named base64 fields in tool results are replaced with media type and size metadata. Sibling page text, paths, and URLs stay available, and the original tool records remain unchanged. It targets roughly the older 65% of stable projected content at the nearest complete-content boundary, while retaining at least 10,000 tokens of original history. Retention takes priority over the ratio. History at or below this amount, or without an eligible complete unit, is not compacted. Retention excludes system instructions, the previous summary, and tool definitions. Each compaction sends the previous summary, each selected history record, and the final summary instructions as separate plain-text messages in one request. Records keep their original order instead of forming one oversized user message; the summary is not repeatedly rewritten in batches. There is no fixed 16k or 64k input cap. Known model windows reserve 4,000 output tokens and 2,048 safety tokens; only the selected history range is reduced if needed. Unknown windows do not introduce an arbitrary input cap. The current model interface has no tokenizer: ASCII text, code, and JSON are estimated at roughly three characters per token, with other characters estimated by code point. Long encoded strings use a higher token-density estimate rather than the ordinary ASCII rate. These are estimates rather than exact token counts. Each summary has a 4,000-token output limit.
The new summary and boundary are saved once after successful generation. Failure leaves the previous summary and boundary unchanged. Transport interruption retries the same request at most once, discarding any unsaved partial summary. HTTP 400 and other request rejections are reported directly rather than assumed to be context-limit errors. Updated Federation services include the upstream status, an available request ID, and a redacted, length-limited response body to help identify the rejection reason.
## Window and panels
The Sidebar, main view, and right-hand BayBar share the window. Resizing the window preserves your Sidebar width where space allows, while the main view grows or shrinks first. When space runs short, BayBar narrows and then hides automatically. If the main view still lacks reading space, the Sidebar hides automatically too. At default width and 100% UI scale, it hides below a window width of 860px and returns at 908px. Your Sidebar width and UI scale adjust these thresholds. Closed panels release their full layout width.
Drag the boundary between a panel and the main view to adjust its width; releasing the boundary saves your choice. Temporarily shrinking the window does not overwrite saved widths. Automatically hidden panels return once there is enough space; manually closed panels stay closed. Explicitly opening BayBar or following a file link in a narrow window displays it over the right-hand content area. Resizing the window returns it to the available-space layout.
When the Sidebar is automatically hidden or manually closed, hover over the left window edge or its top toggle for about 150ms to reveal floating navigation. It overlays the main view without changing the main view's position or width. Moving away hides it after about 250ms; related menus, resizing, and keyboard interaction within navigation keep it open. Click the top toggle to pin it open. If space is insufficient, it stays floating until you click outside or press `Escape`.
Use the top window controls or `⌘/Ctrl+B` to toggle the Sidebar and `⌘/Ctrl+L` to toggle BayBar. Window resizing and panel dragging follow your movement directly. Panel toggles use a short animation, omitted when reduced motion is enabled.
## Session hierarchy
Within each Workspace in the Works sidebar, child Sessions appear directly below their parent and are indented by depth. Root Sessions and siblings are ordered by live status first, then by most recent update. If a parent is outside the current Workspace section, its children remain visible as root Sessions. Pinning moves the entire subtree together, preserving hierarchy and expansion state. Archiving a parent also archives all descendant Sessions. Finish or stop any running or queued work in the subtree before archiving.
Each parent shows up to 3 direct child Sessions by default. A fourth “Show more (N left)” row expands the remaining children; “Collapse child sessions” at the end returns to 3. Each nested parent expands independently. Workspace pagination counts root Sessions, and range selection includes only Sessions currently displayed. If the current or a selected Session falls beyond the third child, the necessary parent lists expand automatically and cannot be collapsed while needed. Switching Sessions or clearing selection restores the previous manual expansion state.
## Pin conversations
In the Works sidebar, open a conversation's more menu and choose **Pin to top**. The root conversation and all its descendants move into a **Pinned** section above every Workspace, and stays visible when Workspaces are collapsed. Pinned conversations keep their pin order, newest first, and each row shows the Workspace it belongs to. The chat header menu offers the same action as **Unpin**. Child menus show “Pin parent conversation” or “Unpin parent conversation”; both actions apply to the whole tree. Unpinning returns each Session to its Workspace, and new children automatically follow the root. Pinned trees also show up to 3 direct children per parent by default, with expand and collapse controls. Pinning applies to Works sidebar conversations, including Group conversations.
## Share messages and conversations
Shared images and PDFs include the Downcity logo and name at the start of the document, in both preview and saved files.
Open the more menu below a completed Agent reply and choose **Share**, then **Save as image**, **Save as PDF**, or **Save as Markdown** in the preview to save its full content, including the Agent name and timestamp.
Choose **Share** from the Chat Session's top-right menu, then **Save as image**, **Save as PDF**, or **Save as Markdown**. Exports read the complete history and preserve the original order of user messages and Agent replies. Reasoning, tool activity, and internal context are excluded. Markdown keeps editable text and attachment links. Images and PDFs preserve code blocks, tables, math, images, and static views of built-in visualizations. Third-party or unavailable visualizations use their published text summary.
Sharing opens a preview with format tabs at the top, a centered preview canvas, and a fixed bottom bar for the content option, copying, and saving. Images scale proportionally to the available width. Long images keep all sections in one continuous scroll.
When sharing a single Agent reply, enable **Include previous user message** to place the nearest preceding user message above it, including sender, timestamp, text, and attachments. This option is off by default and appears only when a previous user message exists. Changing it updates the preview and content saved in every format. Messages from earlier history are supported without manually loading the chat first. PNG shows the generated image sections, with a **Copy image** button in the bottom bar that copies the section most visible in the preview to the clipboard without saving a file first. PDF shows the paginated file, and Markdown shows the source to be saved. Click the selected format's **Save as…** button to open the system save dialog. Cancelling that dialog keeps the preview open; closing the preview releases its prepared content. Resource failures appear in the preview.
Short images use a file save dialog. Long content asks for a directory and creates a new folder containing numbered PNG sections. PDFs paginate automatically and keep selectable text. After saving, you can open the file or image folder directly. Cancelling does not create an export. Image resource failures show an error so you can fix the resource and retry.
## Messages and files
Click a workspace file link in a conversation to preview it in the right-hand file panel while keeping the conversation visible. Files in other registered workspaces also open in this panel. Links with a line number jump to that line. Web links open in your default browser.
The file panel and Workspace view select a preview by file type. Markdown renders as a document; local `.html` and `.htm` files render as static web pages with relative stylesheets, fonts, and images. Scripts and in-page navigation are disabled. CSV and TSV files display as tables with row and column numbers, preserving quoted separators and line breaks. Tables display up to 1,000 rows and 100 columns. Use **Source mode** in the file menu to read the complete original text for Markdown, HTML, CSV, or TSV; text links with line numbers open in source mode.
Relative image paths in Markdown files, such as `images/chart.svg` or `../images/chart.png`, resolve from the current document's directory in both BayBar and Workspace previews.
Fenced Markdown code blocks labeled `mermaid` render as diagrams and adapt their layout to the available width. Diagrams follow the current theme. Copy their source or open the fullscreen view to zoom, pan, fit to the window, and download a PNG with the current theme. Incomplete streaming syntax keeps the last successful diagram visible; if parsing still fails after generation finishes, the source and a retry button appear.
Fenced Markdown code blocks labeled `svg` render as images that fit the available width, in both BayBar file previews and chat messages. Incomplete streaming content, invalid SVG, or image load failures display the source instead. SVG loads in an isolated image context without executing scripts.
PNG, JPEG, GIF, WebP, SVG, AVIF, APNG, BMP, and ICO files display as images. Switch between fitting the panel and viewing the original size. Images load separately from the text reader. Other binary files show an **Open with default app** button that opens the file in its associated system application. If opening fails, the reason appears and you can retry. Text previews remain limited to 2 MB; code and configuration files display as source.
Select text in the right-hand BayBar file panel to show a floating **Quote** button near the selection. Clicking it adds a reference to the current chat input with the workspace, file path, and selected text; source mode also includes the selected line range. The reference preserves the content at the time of quoting and can be saved with the draft or removed before sending. Clearing the selection, scrolling, switching files, or updating the file hides the button. Markdown, table previews, and source mode support text quoting. Switch HTML previews to source mode to quote text; images do not support text selection references.
Agent messages use two columns. The left column stacks the avatar and optional collapse button. The right column shows an info bar with the Agent name and timestamp, followed by the message body and file changes, with spacing between the info bar and body. Message actions such as copy, quote, and fork appear below all content, including the file changes card when present.
Messages with execution history have an arrow button below the avatar in the left column. The button stays visible and gains a subtle background on hover. Its arrow points right when collapsed and down when expanded. Click it to toggle the history, or use the keyboard.
History starts expanded while the Agent is working and collapses when the message finishes. Collapsing hides the history and keeps the final answer fully visible, without a tool summary row. If a message only contains execution history, the arrow remains available to reopen it.
Both actions use the button as a scroll anchor. Once you toggle it manually, that message keeps your choice. Messages without execution history display the answer directly without a collapse button.
### Chrome Extension
Source: https://downcity.ai/en/docs/products/chrome-extension/
The Downcity Chrome extension lets you chat with your Agent in a side panel and reference the current page or selected text. It requires Chrome 116 or later and a running, reachable Downcity City.
[Download Chrome Extension ZIP](/download/chrome-extension)
The extension is currently distributed as a ZIP for manual installation. It is not yet listed in the Chrome Web Store. The package works with Chrome on macOS, Windows and Linux.
## Install manually
1. Download and unzip the package into a permanent folder, such as `Documents/Downcity/chrome-extension`.
2. Open `chrome://extensions` in Chrome.
3. Enable **Developer mode**.
4. Click **Load unpacked**.
5. Select the extracted folder that directly contains `manifest.json`.
6. Pin Downcity in the toolbar and click its icon to open the side panel.
Select the extracted folder, not the ZIP. Keep that folder after installing.
## Connect Downcity
Start your City, open the extension's **Settings**, and enter:
| Field | Value |
| --- | --- |
| City URL | City HTTP URL, default `http://127.0.0.1:5314`; reverse proxy path prefixes are supported |
| Access credential | Bearer token accepted by your City, as required by the server |
| Default Agent | Select an accessible Agent after connecting to City; no manual ID entry |
| Default Ask | Default request used by the page sharing entry point |
Run `city token` on the machine hosting City to create a credential interactively, selecting the allowed Agents and expiry policy. For scripts, use `city token create --name chrome --agents --never-expires`. Enter the plaintext shown at creation directly in extension settings. Old Agent Tokens are no longer accepted.
Click **Connect City / refresh Agent list** (连接 City / 刷新 Agent 列表), select a default Agent, then click **Save and check** (保存并检查). An empty list means the credentials have no visible Agents or City has none. Once connected, reopen the side panel or click **Reconnect** (重新连接). The extension interface currently uses Chinese labels.
Port `15314` is for RPC, not HTTP. Do not include `/agents/...` in City URL: the extension adds the Agent scope. Chrome conversations use the `chrome` origin partition without a Workspace.
## Use the extension
- Click the toolbar icon or press `Command+I` on macOS / `Ctrl+I` on Windows and Linux. Change conflicting shortcuts at `chrome://extensions/shortcuts`.
- Enter your request. The composer references the current page by default; remove that reference to omit the initial page body. The Agent can still read the bound page on demand during this Turn.
- Select text on a regular webpage and click **Reference** (引用) to add it to the composer.
- Replies support Markdown, reasoning text and tool status.
- Reopening the panel restores the browser session for the same City and Agent.
- **New conversation** (新对话) creates another session without deleting server history.
- If the event stream disconnects, click **Reconnect** to load saved messages and reconnect.
Side-panel submissions provide a `chrome_page` Power for the current Turn. The Agent can call `read_page` or `find_text` on the tab and URL captured at submission. Navigation invalidates access. Clicking, filling and cross-tab operations are not exposed. Keep the panel open until the Turn completes; closing it or losing the execution connection interrupts caller-owned capabilities. Chrome internal pages, the Chrome Web Store and some protected pages cannot be read. Handle tool approval requests in Downcity when the extension shows a waiting status.
## Update or uninstall
Manually installed extensions do not update automatically. Download the new ZIP, replace the contents of the original folder, click **Reload** at `chrome://extensions`, then refresh webpages where you use references.
The current source build uses City, Agent and Token settings. Existing Workspace sessions are not migrated into Chrome sessions or deleted. Downloaded packages only include these features once released.
Click **Remove** at `chrome://extensions` to uninstall. Browser settings are removed; server sessions remain in Downcity.
## Verify a download
[Latest release metadata](/download/chrome-extension/latest.json) includes the version, size and SHA-256. The download redirects to a versioned ZIP; append `.sha256` to that final path to download its checksum file.
[Extension data and privacy](/en/docs/products/chrome-extension-privacy)
### Chrome Extension Data and Privacy
Source: https://downcity.ai/en/docs/products/chrome-extension-privacy/
This notice describes the current source build with request-level page Powers. Updated October 20, 2026.
## Data read and sent
The extension reads the active tab's title and URL to display page references. A local selection script detects selected text; clicking Reference passes that selection to the side panel.
When you submit a request, the extension sends your input and referenced page content, title, URL or selections to the Agent at your configured City URL. Side-panel submissions also provide page reading and text search capabilities for that Turn, bound to the tab and URL at submission. When the Agent calls an Action, its results are sent to your City. Removing a page reference omits the initial body but does not revoke on-demand reading for that Turn. Pages may contain private information visible after login; submit only on pages you intend to authorize the Agent to read. Navigation invalidates access, and closing the panel interrupts the execution channel.
Your City executes Agent requests according to its configuration. Content may be provided to the model services or tools you configure. Server retention, model providers and tool behavior depend on that City.
## Local storage
Chrome `storage.local` stores the City URL, Agent ID, Agent Token, default request, server session IDs, recent page-sharing records and temporary selection references. Tokens are not written to `storage.sync`.
Page-sharing records contain the page URL, request text and timestamp, not the captured page body. Uninstalling removes browser settings. Manage server sessions separately in Downcity.
## Permissions
| Permission | Purpose |
| --- | --- |
| `tabs` | Read active tab title and URL and respond to tab changes |
| `activeTab`, `scripting` | Read the bound page when you submit a reference or the Agent invokes a read/search Action during that Turn |
| `sidePanel` | Display persistent chat |
| `storage` | Save local settings, session identities and temporary references |
| HTTP/HTTPS host permissions | Connect to your chosen local or remote City and provide selection references on regular webpages |
The extension itself includes no advertising, analytics or separate telemetry uploads and does not sell user data. Website package downloads are handled by Downcity's website and Cloudflare as website requests.
For privacy questions, contact the maintainers through [Downcity GitHub Issues](https://github.com/genesiscosmos/downcity/issues). Do not include tokens or private page content in public reports.
### Website account
Source: https://downcity.ai/en/docs/website-account/
{/* User guide for the website account flow. */}
Select **Log in** in the website navigation and choose an available GitHub or Google login option. The original login dialog displays an authorization code and opens an authorization window. After provider authentication, enter the code from the original dialog on the confirmation page. Once confirmed, the original page continues automatically and returns you to the page you were browsing.
If the authorization window does not open, allow pop-ups for the Downcity website and try again. You can cancel while waiting. If login expires or fails, choose a login option again to retry.
Once logged in, select your account name in the navigation and choose **Account** to view your name, email, and user ID. If your provider does not supply an email address, the page shows “Not provided”.
## Balance and activity
The account center has a sidebar with **Overview**, **Usage & activity**, **Transactions**, **API Keys**, **Request history**, **Models & setup**, and **Profile**. On mobile, use the section menu at the top. The `view` URL parameter supports direct links; sections share loaded data, and refreshing preserves the current view.
The account center shows:
- Available Credits, permanent Credits, and temporary Credits with expiration dates.
- Month-to-date spend, AI request count, and metered Tokens.
- A daily trend chart with separate Spend (USD), Tokens and Requests views for the last 7, 30 or 90 days. Hover for daily details; dates before coverage remain unknown.
- An activity heatmap for the past 365 days, colored by AI requests. Hover or focus with the keyboard for details, click to pin a day, then close the details or press Escape to unpin.
- The latest three transactions in Overview, and up to twenty in Transactions. Select a record to expand its description and status.
Daily statistics use your browser timezone. AI requests include failed or cancelled executions; Tokens include only measured usage. Spend comes from independent billing records and is not estimated from Tokens. Dates before data coverage are not treated as zero activity.
Credits added may come from purchases or grants. The website currently links to Credits information and does not provide a direct top-up flow. If a service is unavailable, the affected section shows an error. Select **Refresh** to try again.
## API key management
Select **API Keys** in your account center, or open [key management](/account?view=keys). View your own keys, create new ones, edit names, model / route permissions, expiration and spending soft limits, or disable, reactivate and permanently revoke keys.
Permission choices come from the service’s published language model and route catalog. Selecting all current and future entries also grants access to entries published later; selecting none blocks all inference. Access to a route does not grant direct access to its model. Previously granted entries that are no longer available remain in the editor and can be removed. If the catalog is unavailable, existing permissions are preserved; refresh it before changing permissions or creating a key.
Enter spending limits in whole Credits. Blank means no limit; zero blocks new calls. The limit checks successfully settled lifetime spending for that key. Editing the limit does not reset spending. **No funds are reserved**: concurrent in-flight requests can exceed the limit, and all keys share your account balance. Enter expiration in your browser’s local time, or leave it blank for no automatic expiration.
The complete key is **shown only once** after creation. Copy and store it securely. Closing the dialog, leaving the Keys section or signing out removes it from the page; it cannot be retrieved again. If clipboard access is unavailable, select the text and copy manually. If creation is interrupted, refresh the list to check the result first. Revoke any newly created key whose secret you did not receive before creating another.
Disabled keys can be reactivated. Revocation is permanent; check the name and prefix before confirming. Disabling, revoking or expiration blocks new calls, while in-flight calls still settle. A key grants only permitted inference access and cannot sign you in or manage your account. See the [model relay guide](/en/city-sdk-docs/service/ai/relay) for OpenAI client configuration.
## Request history
Open [Request history](/account?view=requests) to view your own relay requests, with up to 20 records per page, filtering by key, previous/older pages, and refresh-latest controls. Key names and prefixes come from your own key list. If unavailable, records show key IDs; signed-in calls are identified separately.
Each record shows the requested public model / route, execution state, input/output tokens, settled Credits, duration and settlement state. **Unknown / not provided does not mean zero.** Input tokens are summed only when both cached and uncached input are known; reasoning tokens are part of output and are not added again. Pending, failed or missing charges are not presented as free. Select **Details & attempts** for request ID, resolved public model, metering breakdown and safe upstream attempt metadata: channel ID, actual upstream model, HTTP status and first-content latency. No prompts, answers or provider credentials are displayed.
Only key filtering is available; backend date, state and model filters are not provided. Requests rejected before execution may have no record. Interrupted requests may remain running, so consult metering and settlement separately.
## Models and setup
[Models & setup](/account?view=models) reads the live public language model and route catalog, with search by name or ID. It preserves backend context windows, reasoning efforts and structured pricing, including currency, units, scale and conditions. Missing fields are marked as unavailable. Tools or vision support is not inferred from tags, and prices are not converted into Credits.
The OpenAI Base URL comes from the website server’s Federation connection configuration. Choose an entry and protocol to copy a curl example for **OpenAI Chat Completions** or the **native Downcity model stream**. Examples use only `YOUR_DOWNCITY_API_KEY`; the page never reads or saves a real key. Replace the placeholder in your secure client. Native streaming uses its own Downcity SSE events. Responses and Anthropic Messages are not supported.
Catalog visibility does not grant a calling key permission: authorize the entry in key management. Catalog failures provide retry controls, and any retained older catalog is explicitly identified.
Select **Log out** to revoke the current website login and end the session in this browser. If logout fails, retry when the service is available. Log in again when your session expires. Logging out of the website does not log you out of the desktop app or other devices.
### Agent
Source: https://downcity.ai/en/docs/agent/overview/
The **Agent SDK** (`@downcity/agent`) is the core runtime for executing agent work. An Agent owns
identity, model, instructions, Tools, and one `AgentSessions` collection. Each Session may receive a
Workspace. `City` owns Workspaces, unique Power instances, Agent/Group collections, and transports.
## What an Agent does
- Reads project config (constructor options or a project directory)
- Maintains sessions and conversation history
- Calls tools during execution
- Uses Power capabilities projected by City into the current scope
- Binds to a model for inference
## Creating an Agent
Selecting “Create Agent” opens a dedicated creation page. Describe the role in natural language to let the system default model draft its name, description, instructions, and recommended powers, or choose manual configuration to start with an empty draft. AI output remains editable and nothing is persisted until you confirm creation.
The editor preselects the system default text model and only falls back when it is unavailable. Desktop surfaces display Agent names throughout the UI; stable IDs remain internal routing and storage references.
The name and description identify the Agent in contacts and conversations. The generated ID remains the stable reference used by local directories, APIs, and runtime ownership. If the generated ID already exists, Desktop asks for another name instead of silently adding a random suffix.
You can edit the name and description later without changing the stable Agent ID. Desktop also supports permanent deletion of the Agent definition, avatar, sessions, logs, schedules, and Agent-scoped power data. An Agent cannot be deleted while it is running or still belongs to a Group.
## Desktop completion notifications
When an Agent Session finishes a Turn in the background, Desktop shows a blue unread dot on the Agent and on the corresponding Session in the lower conversation list of the Chat Sidebar. The system app icon also shows the number of unread Sessions. No unread item is created while you are actively viewing that Session; opening it clears both the dots and the system badge. Multiple completed Turns in the same Session are grouped into one unread item.
## Setting a Desktop Agent avatar
When creating an Agent, Desktop randomly selects an image from its built-in pixel avatar pool and saves it as that Agent's independent avatar. Click the avatar on the Agent details page to select another built-in avatar at random or upload a custom PNG, JPEG, or WebP image up to 2 MiB.
## Creating a Group
Selecting “Create Group” opens a dedicated creation page. Describe the collaboration goal to let the selected model draft a Group name, collaboration instructions, and recommended members from the existing Agents, or start with manual configuration. AI output remains an editable draft until you confirm it.
You only provide the visible Group name. Desktop derives the stable internal `group_id` from that name. The name, instructions, model, and members remain editable later without changing the stable ID. The Group avatar is composed from its member Agent avatars.
```ts
import { Agent } from "@downcity/agent";
import { City } from "@downcity/city";
import { create_builtin_power_registrations } from "@downcity/powers";
import { Workspace } from "@downcity/city";
import { Shell } from "@downcity/city";
import { MicrosandboxProvider } from "@downcity/sandbox-microsandbox";
const agent = new Agent({
id: "repo-helper",
model: myModel,
tools: { my_tool: myTool },
});
const workspace = new Workspace({
id: "project",
path: "/path/to/project",
shell: new Shell({
sandbox_provider: new MicrosandboxProvider(),
}),
});
const city = new City({
workspaces: [workspace],
powers: create_builtin_power_registrations(),
});
city.agents.add(agent);
```
## Key concepts
- **City** — owns Workspaces, unique Power instances, Agent/Group collections, and unified transports.
- **Session** — one execution thread. The Agent creates sessions on demand and routes messages through them.
- **Tool** — a function the Agent can call during execution. Passed directly to the constructor.
- **Power** — an extension capability provided and owned by City, then projected to every Agent.
- **Model** — the inference backend. The Agent holds the default instance, and a Session can override it with its own instance.
## What an Agent is not responsible for
- Managing multiple projects (that is the CLI / Console layer).
- Owning the model catalog (that is City / Federation).
- Persisting global credentials (that is City).
Keeping these boundaries clear makes it easy to answer: where should I configure a model? Where should a bot credential live? Is this a control-plane failure or a project-runtime failure?
## Execution model
The Agent execution model is simple:
1. Receive a message or task
2. Load the session context (history, tools, powers, prompts)
3. Call the model
4. If the model asks for a tool, execute it and continue
5. Return the result
Continue with:
- [Agent SDK](/en/docs/agent/sdk)
- [SDK architecture](/en/docs/agent/sdk-architecture)
- [Runtime architecture](/en/docs/agent/runtime-architecture)
- [Agent Lifecycle](/en/docs/agent/lifecycle)
### Agent SDK
Source: https://downcity.ai/en/docs/agent/sdk/
Use `@downcity/agent` to create an Agent, manage Sessions, and execute model calls in the same process. See the [Agent SDK docs](/en/agent-sdk-docs) for the complete API.
```ts
import { Agent } from "@downcity/agent";
import { City } from "@downcity/city";
import { create_builtin_power_registrations } from "@downcity/powers";
import { Workspace } from "@downcity/city";
import { Shell } from "@downcity/city";
import { MicrosandboxProvider } from "@downcity/sandbox-microsandbox";
const workspace = new Workspace({
id: "project",
path: process.cwd(),
shell: new Shell({
sandbox_provider: new MicrosandboxProvider(),
}),
env: { API_KEY: process.env.API_KEY ?? "" },
});
const agent = new Agent({
id: "repo-helper",
model,
tools: { search: search_tool },
});
const city = new City({
workspaces: [workspace],
powers: create_builtin_power_registrations(),
});
city.agents.add(agent);
// Session 在创建时选择 Workspace。
const session = await agent.sessions.create({ workspace });
const turn = await session.prompt({ query: "Inspect this project" });
const result = await turn.finished;
await agent.dispose();
```
`Workspace` comes from `@downcity/city` and owns project files, search tools, Env, and an optional Shell. It does not own Agent identity, storage, Powers, or Session semantics. `agent.sessions.create({ workspace })` creates the SessionStore inside the Agent scope supplied by City Storage.
An Agent is not configured with a Workspace. Each Session may use a Workspace, and multiple Agents may operate on the same physical directory by creating separate Workspace instances. `agent.dispose()` releases Agent resources and the Sessions' Workspace resources.
Local runtime state is centralized outside the project directory:
```text
~/.downcity/agents//
├── sessions///
└── archived-sessions///
```
`chat` and `work` are the only two categories, and the category is the only field that decides the
directory. `type` is the role inside that category. Omitting `origin` defaults to
`{ category: "work", type: "work" }`. Custom roles must declare a category, and restoring a Session
uses `get(session_id, category)`. See
[Session Origin and Types](../agent-sdk-docs/sessions/origin-and-types) for details.
City starts shared Power instances and background work when it binds them. Session execution waits for initialization automatically. Use `await city.close()` to close the host or `city.agents.remove()` to remove one Agent. City also supplies HTTP and RPC.
## Streaming messages
`subscribe()` returns the unified live Session Mutation stream:
```ts
const unsubscribe = session.subscribe((mutation) => {
if (mutation.variant === "delta" && mutation.type === "text") {
process.stdout.write(mutation.delta);
}
});
```
Tool lifecycle updates use `type: "tool"`; a pending Interaction lives on its Tool Part's `interactions` while that Tool is `waiting-user`. Submit responses through the Session command API:
Part order within an Assistant step always follows the model stream. If Tool execution becomes ready before its Tool Part reaches the stream, execution waits at that boundary instead of overtaking preceding text. Waits are isolated by `tool_call_id`, so multiple Tools can still execute concurrently. Clients should render Mutations and history snapshots in their recorded order without reordering them.
```ts
const unsubscribe = session.subscribe((mutation) => {
if (mutation.variant !== "part" || mutation.part.type !== "tool") return;
const interaction = (mutation.part.interactions ?? []).find(
(item) => item.status === "pending",
);
if (interaction) render_interaction(interaction);
});
async function decide_approval(interaction_id: string, decision: "approved" | "denied") {
await session.respond({
interaction_id,
response: { type: "approval", outcome: decision === "approved" ? "resolved" : "denied", payload: { decision } },
});
}
```
Use `session.messages()` for a canonical history snapshot. It paginates on Message boundaries and returns a `next_before_sequence` cursor when older history exists. After a disconnect, reload the snapshot and establish a new subscription.
Hosts that render a flat activity feed can use the SDK projection instead of depending on `.downcity` file names:
```ts
import { to_session_message_timeline_events } from "@downcity/agent";
const page = await session.messages();
const timeline = page.items.flatMap(to_session_message_timeline_events);
```
Session JSONL, logs, and scheduled actions use the StorageProvider scope injected by City. If no City storage is injected, the Agent uses an in-memory provider. Project File/Search tools cannot access this private state. Applications should use Agent.sessions and Session APIs rather than depend on the physical layout.
Continue with:
- [SDK architecture](/en/docs/agent/sdk-architecture)
- [Runtime architecture](/en/docs/agent/runtime-architecture)
- [Complete Agent SDK API docs](/en/agent-sdk-docs)
### Agent SDK Architecture
Source: https://downcity.ai/en/docs/agent/sdk-architecture/
Downcity separates the execution subject, project resources, and Power runtime. `Agent` owns identity,
instruction, model, custom Tools, and Sessions. `Workspace` owns project resources and Shell. `City`
owns unique Power instances, lifecycle, and Agent/Group collections.
```ts
import { Agent } from "@downcity/agent";
import { City } from "@downcity/city";
import { create_builtin_power_registrations } from "@downcity/powers";
import { Shell, Workspace } from "@downcity/city";
const agent = new Agent({ id, model, instruction });
const workspace = new Workspace({ id: "project", path, shell });
const city = new City({
workspaces: [workspace],
powers: create_builtin_power_registrations(),
});
city.agents.add(agent);
// Session 在创建时选择 Workspace。
const session = await agent.sessions.create({ workspace });
```
## Responsibility model
```mermaid
flowchart TD
Host["Host application"] --> City["City
resource and lifecycle container"]
City --> Agent["Agent
identity, model, instruction, Sessions"]
City --> Workspace["Workspace
project resources and Shell"]
City --> Powers["Powers
unique instances, configuration projection, lifecycle"]
Agent --> Enter["agent.sessions.create({ workspace })"]
Workspace --> Enter
Enter --> Sessions["AgentSessions
Session collection"]
Sessions --> Session["Session
continuous execution"]
Session --> Tools["Workspace + Agent + Power tools"]
Session --> Context["City-projected PowerContext"]
Powers --> Context
City --> Storage["StorageProvider
Memory by default"]
Session --> Storage
Workspace --> Files["Project File/Search"]
Workspace --> Env["Workspace Env"]
Workspace --> Shell["Shell"]
Shell --> Sandbox["Sandbox Provider + Workspace Sandbox"]
```
The dependency direction stays explicit:
- `@downcity/agent` depends only on neutral resource protocols from `@downcity/type`.
- `@downcity/city` depends on Agent and injects Workspace, Tools, and `SessionHooks` through its internal binding; Agent does not depend back on City.
- Hosts choose a Sandbox Provider when constructing each Shell; City does not understand the backend.
- Edge adapters use `@downcity/type/workspace` without loading Node.js local implementations.
## Agent is the subject
An Agent is reusable across projects. It is never configured with one permanent Workspace.
```ts
const agent = new Agent({
id: "repo-helper",
model,
instruction: "Maintain the current project.",
tools: { company_search: company_search_tool },
});
city.agents.add(agent);
const frontend = await agent.sessions.create({ workspace: frontend_workspace });
const backend = await agent.sessions.create({ workspace: backend_workspace });
```
Agent does not own Powers. City owns one instance per Power ID and projects every Power into an
Agent/Workspace execution entry. Every Power Action receives the current `PowerContext` with
directly callable restricted Agent, Workspace, Session, and Turn handles. Powers use one City-level
`initialize/dispose` lifecycle; Agent/Workspace only defines the current call scope.
## Workspace is the resource boundary
`Workspace` owns:
- A stable Workspace ID and normalized project path.
- Rooted project file access and File/Search tools.
- Workspace environment variables.
- An optional Shell and its Sandbox adapter.
- It never owns Agent or Session runtime storage. City provides the domain-neutral `StorageProvider`.
Workspace does not create SessionStore, understand Agent IDs, register Powers, call models, or
create Storage. The constructor has no runtime data-root option.
Shell belongs to Workspace because command execution operates on Workspace resources. The public
entry is:
```ts
import { Shell, Workspace } from "@downcity/city";
```
There is no separate `@downcity/shell` package. Platform Sandbox packages remain independently
installable and are injected into Shell.
## Session is the execution boundary
`agent.sessions.create({ workspace })` combines Agent and Workspace for one Session without merging ownership. Agent, Session, and the City execution projection provide:
- The final Tool set from Workspace tools, Agent custom tools, and Power bridge tools.
- `AgentSessions` and the Agent domain `LocalSessionStore`.
- Agent/Workspace/Session/Turn-aware PowerContext and an execution lease.
- Logs, scheduled Power Actions, and Shell binding.
Tool name conflicts fail during composition; no source silently overwrites another. The same Agent
can hold multiple Sessions with different Workspace resources. Workspace resources may be registered
in City or managed by the host outside City.
## Private storage
When City receives a local persistent Storage Provider, runtime state is centralized outside the project:
```text
~/.downcity/
└── agents/
└── /
├── sessions/
├── powers/
├── logs/
└── schedule.jsonl
```
City Storage is a bottom-level file/database capability. Agent code interprets the
`agents//` business scope and creates Session and Power stores inside it. Project
File/Search tools use a different rooted FileSystem, so they cannot inspect or change Session
history, Power state, or runtime data.
## Environment and checkpoints
Environment variables describe the project execution environment and therefore belong to
Workspace:
```text
/.env < WorkspaceOptions.env
```
`set_env()` and `patch_env()` update the Workspace snapshot and synchronize Shell. Existing
Sessions commit the new environment at the next Step checkpoint, avoiding context changes halfway
through a model call.
Power registry changes, Session model changes, and compaction follow the same checkpoint rule.
## Lifecycle
```mermaid
sequenceDiagram
participant Host
participant Agent
participant Workspace
participant City
Host->>Agent: new Agent(options)
Host->>Workspace: new Workspace(options)
Host->>City: city.agents.add(agent)
Host->>Agent: sessions.create({ workspace })
Agent->>Workspace: use current resource
Agent->>City: use injected Storage
Host->>Agent: dispose()
City->>Workspace: dispose registered resources
City->>Agent: detach runtime resources
```
`city.close()` stops registered Agents and Sessions, disposes registered Workspace resources,
closes the City Storage Provider, and then closes HTTP/RPC transports. A Workspace managed outside
City remains owned by its host.
## Package boundaries
| Package | Owns | Does not own |
| --- | --- | --- |
| `@downcity/type` | Neutral cross-package resource protocols | Concrete resources and lifecycle implementations |
| `@downcity/agent` | Agent, AgentSessions, Session, Store, SessionHooks, model Tool Loop | City composition, Power lifecycle, project resource implementation, platform Sandbox |
| `@downcity/city` | City, Workspace/Shell implementations, Power SDK/runtime, Hook scheduling, RemoteAgent, HTTP/RPC transports, local host data | Agent execution internals, concrete built-in Powers |
| Sandbox packages | Native process isolation for one platform | Workspace, Agent, Session, or Power business behavior |
Continue with [Runtime architecture](/en/docs/agent/runtime-architecture).
### Agent Runtime Architecture
Source: https://downcity.ai/en/docs/agent/runtime-architecture/
The runtime is designed to execute every input in a deterministic order, expose intermediate model and Tool state, and recover Sessions after process interruption.
## Session is the execution boundary
Each Session owns independent:
- ID, metadata, and model override.
- Message history and System Snapshot.
- Prompt/Command queue.
- Tool approval state.
- Composer and Executor.
- Live Mutation stream.
```ts
// Session 在创建时选择 Workspace。
const session = await agent.sessions.create({ workspace });
const turn = await session.prompt({ query: "Inspect and fix the project" });
const result = await turn.finished;
```
`prompt()` returns a Turn Handle instead of direct text. `finished` resolves for both success and failure; inspect `result.success` and `result.error` for the outcome.
## How one Prompt runs
```mermaid
sequenceDiagram
participant App as Host
participant Session
participant Queue as SessionQueue
participant Messages as SessionMessages
participant Input as StepInput
participant Composer
participant Executor
participant Model as LanguageModel
participant Tool
App->>Session: prompt(query)
Session->>Queue: enqueue Prompt
Queue->>Messages: persist User Message
Queue->>Executor: create stable run context
Executor->>Input: request this step's input
Input->>Composer: read canonical history and checkpoint
Composer-->>Input: base system, dynamic context, messages, tools
Input-->>Executor: base snapshot + current dynamic context, messages, tools
Executor->>Model: run model Step
Model-->>Executor: text / reasoning / tool chunks
Executor->>Messages: write Assistant draft and Mutations
Executor->>Tool: execute Tool Call
Tool-->>Executor: Tool Result
Executor->>Input: reassemble input for the next Step
Executor->>Messages: commit final Assistant Message
Executor-->>App: turn.finished
```
The runtime guarantees:
1. The User Message is persisted before the model call.
2. Streaming Assistant output is first written as a recoverable draft.
3. Text, Reasoning, Tool Calls, and Tool Results preserve canonical model-stream order.
4. Complete model Steps and Tool state changes commit to canonical history.
5. An interrupted run can recover from the draft and Action state.
## State checkpoints
Only one execution loop is active per Session. Every input that can affect the next Step enters one ordered queue:
- User Prompts.
- Workspace environment updates.
- Power registry updates.
- Session model updates.
- Explicit compaction.
Changes are committed at Step boundaries, never halfway through a model call or Tool execution. An active Step uses the stable execution view created for it.
Model resolution order is:
```text
Session model > Agent model
```
Agent and Session hold model instances supplied by the host. The SDK does not select or restore model services from a string model ID.
## Composer and Executor
`SessionComposer` owns model-context policy: returning base system blocks, dynamic system context for this step, a history view, and tools, and advancing its own derived state through `advance_context()`. The default Composer reads the latest summary from the current checkpoint and returns it in `context_system_blocks`.
`StepInput` freezes base blocks and assembles the base snapshot followed by the Composer's current dynamic blocks each step. `Executor` uses that input for model requests and Tool execution, handling aborts, retries, and context-limit recovery. SessionLoop owns the queue and Turn orchestration.
These components do not depend on physical Session storage paths, the Agent list, or HTTP/RPC transports.
## System Snapshot
Base system instructions and dynamic system context have different lifetimes:
- First assembly: freeze Agent identity, instruction, core, Power system, and stable Session context.
- `snapshot()`: persist the current base snapshot.
- `syncshot()`: regenerate the base snapshot from current Agent instructions and Power system; replace an existing persisted snapshot, or update only memory if none exists.
The Composer's `system` / `system_blocks` are base instructions; optional `context_system_blocks` are regenerated each step. Neither `snapshot()` nor `syncshot()` freezes dynamic summaries.
`system()` previews follow the same order as model requests: the base snapshot first, then the latest dynamic context. Agent instruction updates do not automatically rewrite existing base snapshots; checkpoint summary updates require no base instruction refresh.
## Messages and persistence
Persisted Sessions belong to the Agent storage scope provided by City. Without City, the default is in-memory storage. A default local Session contains:
```text
~/.downcity/agents//sessions///
├─ session.db
└─ attachments/
```
- `session_state.system_snapshot` stores explicitly persisted base system text.
- `messages` and `message_parts` store canonical history.
- The Composer's own derived tables store checkpoint summaries and boundaries.
Compaction changes only the history view sent to the model; canonical history is neither deleted nor rewritten. Recovery reads the base snapshot and current checkpoint separately, and builds the history view from canonical Parts. Without a base snapshot, base instructions are regenerated from the Agent's current instruction and powers.
Ordinary model chunks drive live rendering and in-memory assembly. Stable semantic checkpoints, including complete model Steps, Tool state changes, and Message closure, commit to SQLite. Hosts read structured state through `session.messages()`, `get_info()`, and `system()`.
## Live observation
`subscribe()` emits Mutations that occur after subscription:
```ts
const unsubscribe = session.subscribe((mutation) => {
if (mutation.variant === "delta" && mutation.type === "text") {
process.stdout.write(mutation.delta);
}
});
```
Mutations cover complete Messages, Assistant Parts, text/reasoning deltas, Turn state, and Session state. After a disconnect, reload the canonical snapshot with `messages()` before establishing a new subscription.
## Power runtime
Powers belong to City, not Agent or Workspace. City owns one instance per Power ID and projects its Actions, System text, Hooks, Resolve Points, and HTTP routes into every Agent/Workspace execution entry.
PowerRegistry projection changes take effect at Session checkpoints. A Power initialization failure isolates that Power without blocking others. Agent disposal stops Sessions and ActionSchedule; City closes the Power `initialize/dispose` lifecycle.
ActionSchedule is a local delayed Power Action scheduler owned by the Agent. Events are stored in the Agent's storage scope; after restart, abandoned running entries recover to pending. It is not a distributed scheduler and provides no cross-machine leader election.
## City Powers
Every Agent receives three City-owned powers. They are the single entry point for "what only the harness knows" plus the generation models City itself holds.
```jsonc
{ "action": "sandbox.explain_path", "args": { "path": "~/.downcity/powers/messenger" } }
```
| Power | Action groups | Answers |
| --- | --- | --- |
| `context` | `env`, `sandbox`, `workspaces`, `usage` | Which Agent, Session, Workspace, model, timezone and local date this turn runs under; which sandbox backend and instance this Session runs in, which host directories are mounted, and why a path is blocked; every Workspace registered in this City; user-level token usage |
| `ai` | `image`, `sound` | Generate images; transcribe audio and synthesize speech |
| `agent` | `agent` | Every Agent registered in this City |
An action id is `group.action`, independent of which power owns it: `env.get` belongs to `context`, and both `image.*` and `sound.*` belong to `ai`. Calling a power with no arguments lists its actions; nothing here returns credential values, and each action declares `read` or `write` so you can see which ones consume quota or change state before calling them.
Availability follows the same rule as Powers: everything City registers is available to every Agent, with no per-Agent gating and no configuration file.
### Image and sound
Both use the models available to your Federation account, so there is no separate configuration and nothing to set up. Because there is no configured default, pass `model` explicitly or take it from `image.models` / `sound.models`; `asr` and `tts` fall back to the first suitable model when none is given.
Image generation is a two-step job: `create` returns a `job_id`, `result` reads it. Creating an image consumes quota, so the model must confirm with you first. `result` writes the generated images into the power's private directory and returns their local paths; render them with ``.
Automatic transcription of inbound voice messages belongs to the Messenger power, which calls the `ai` power's `sound.asr` when a channel delivers a voice or audio attachment. If transcription fails for one attachment, the message still arrives.
## Security model
Security is enforced at distinct capability boundaries:
| Capability | Enforced boundary | Permission semantics |
| --- | --- | --- |
| File/Search Tools | Rooted LocalFileSystem | May actively access only the Workspace |
| Sandbox Shell | Workspace Sandbox | Commands run in the Workspace's isolated, persistent environment |
| Host Shell | Approval gateway | The user explicitly authorizes one host command with a recorded reason |
| Power | Power business authorization | Workspace does not own all Power resource access |
| City Power | Declared per action | Answers runtime facts and runs declared `read` actions; `write` actions consume quota or write files under the Agent's directory |
| Custom Tool | Registering host | Agent Core does not infer business permissions |
Explicit attachments may use an absolute path selected by the host because they are declared Prompt inputs. This does not expand where model-driven File/Search Tools may browse.
## Cross-platform strategy
Node.js already normalizes files, paths, networking, JSON, timers, AbortController, and basic child processes. Agent, Session, Store, and Workspace therefore contain no operating-system branches.
Isolation differences are contained by the neutral Sandbox Provider protocol. Each Shell receives its Provider explicitly and owns the isolated, persistent Sandbox created when it binds a Workspace. City only manages Workspace resources and does not know whether their Shell uses a local container, microVM, remote host, or another backend. The default implementation uses microsandbox microVMs.
## Lifecycle
```mermaid
flowchart LR
Agent["new Agent"] --> Register["City registers Agent"]
Power["City registers Power"] --> Initialize["Power initialize"]
Register --> Running["execute Sessions"]
Initialize --> Running
Running --> Close["city.close()"]
Close --> Sessions["stop Agent Sessions"]
Sessions --> Dispose["Power dispose"]
Dispose --> Workspace["release Workspace / Shell"]
```
Sessions wait for the Agent's City execution binding before execution. `agent.dispose()` does not stop City Power instances. `city.close()` closes Transports, Agents, Powers, Workspaces, and Shells after active Hook/Action leases finish.
Continue with [Agent Lifecycle](/en/docs/agent/lifecycle).
### Agent Lifecycle
Source: https://downcity.ai/en/docs/agent/lifecycle/
`new Agent(options)` creates only the Agent identity, model, instructions, custom Tools, Session collection, and ActionSchedule. Powers do not belong to Agent. After City registers the Agent, it projects City-owned Power capabilities into the Agent execution entry.
Run only one active runtime for the same Agent ID in the same physical Workspace. ActionSchedule is a local scheduler and does not coordinate duplicate Agent processes.
```ts
import { Agent } from "@downcity/agent";
import { City, Shell, Workspace } from "@downcity/city";
import { MicrosandboxProvider } from "@downcity/sandbox-microsandbox";
const shell = new Shell({ sandbox_provider: new MicrosandboxProvider() });
const agent = new Agent({
id: "my-agent",
model,
});
const workspace = new Workspace({
id: "project",
path: process.cwd(),
shell,
});
const city = new City({ agents: [agent], workspaces: [workspace] });
const session = await agent.sessions.create({ workspace });
const turn = await session.prompt({ query: "Start" });
await turn.finished;
await city.close();
```
Sessions wait until the Agent's City execution binding is ready. `agent.dispose()` releases only Agent-owned Sessions, ActionSchedule, and execution bindings. `city.close()` first stops Agent Sessions, then stops the single City-owned Power instances and closes Workspaces, Shells, and Transports.
Continue with the [Agent SDK docs](/en/agent-sdk-docs).
### Power
Source: https://downcity.ai/en/docs/power/overview/
A **Power** is Downcity's single extension product unit. City provides and owns it, projecting runtime capabilities into Agent/Session scopes while also supporting host management logic, a Sidebar + Mainview workspace, and Config.
```text
Power
├── main optional: City instances, lifecycle, management logic, and actions
└── renderer optional: Sidebar + Mainview and/or Config
```
## What a power does
- Exposes tools the Agent can call during execution
- Hooks into City Power lifecycle (`initialize`, `dispose`)
- Manages its own state, connections, and background tasks
- Provides a Sidebar + Mainview workspace and edits configuration in a separate Config on its Catalog detail page
- Runs inside the City process boundary, not as a separate service
Each Power ID maps to one instance and one configuration inside a City. The host persists Config and
projects an immutable `PowerContext.config` snapshot for each execution. Agents own neither Powers,
configuration, nor lifecycle. Powers model multiple accounts in their own Config instead of using a
generic named-configuration layer.
## Built-in powers
Downcity ships several built-in powers that cover common agent needs:
- **Chat** — connects messaging channels (Telegram, Feishu, QQ, etc.)
- **Task** — schedules and runs background tasks
- **Memory** — persists conversation history and context
- **Shell** — executes local commands in a sandboxed environment
- **Schedule** — cron-style job scheduling
- **Web** — browses the web and extracts content
- **Skill** — composes reusable tool chains
## Writing a power
In the SDK, provide a Power instance directly without using the install protocol:
```ts
const city = new City({ powers: [github_power], workspaces: [workspace] });
city.agents.add(agent);
```
Add a `power.json` with a unified `main` and optional `renderer` entry only when the Power must be installed and managed by CLI or Desktop.
## Where to learn more
- [Agent Powers Docs](/en/powers-docs) — built-in power manuals and examples
- [Agent SDK](/en/agent-sdk-docs) — how to register and use powers programmatically
- [Custom Power](/en/docs/power/custom) — the unified main install protocol
### Messenger Power
Source: https://downcity.ai/en/docs/power/messenger/
Messenger Power is a channel runtime owned by City. It does not belong to an individual Agent and does not expose long-lived state through `context.agent.chat`.
## Desktop workflow
Open Messengers to see every Bot Account in a dedicated Sidebar. Use the plus button in the Sidebar header and choose Telegram, Feishu/Lark, or QQ from the dropdown to create a Bot Account. You can add multiple bots for the same provider. Feishu/Lark defaults to scan sign-in, so you never have to paste an App ID or App Secret.
Selecting an Account lets you manage:
- enabled state, credentials, connection tests, and reconnects
- the default Agent for new Conversations
- Access requests and grants for external identities
- each Conversation's Agent, Channel Session, and paused state
- Inbox and Outbox items that exceeded automatic retry limits
- Activity records that exclude message bodies and secrets
Desktop applies Account saves immediately. It restarts only that Account's Connector, so Desktop, City, and other Bot Accounts do not need to restart. Credentials can be entered in Settings. Stored secrets are never echoed; leave a secret field empty to preserve its current value.
:::callout
Telegram and similar platforms may require a proxy in some networks. As soon as a proxy is enabled at the system or Desktop level, channels use it automatically.
### Network and connectivity
Telegram, Feishu, and QQ requests all go through one shared power egress layer, so behavior is identical:
- Every request has an overall timeout, so a connection can never hang forever. On failure the Account moves to `Error` and shows the reason directly.
- Proxy priority: the Desktop network proxy setting, then the operating system proxy, then `HTTPS_PROXY` and related variables from `Global / Env`. On macOS the power inherits the system proxy automatically, and system bypass lists are converted into `NO_PROXY`.
- When the proxy changes (including toggling the system proxy or a VPN), Desktop re-resolves it within 30 seconds and reconnects enabled channels. No restart is needed.
- Only `http://` or `https://` proxy URLs are supported. A `socks5://` URL fails immediately with an actionable message. `NO_PROXY` supports host names, `.example.com`, `*.example.com`, and IPv4 CIDR.
- After an unexpected disconnect the Account reconnects with capped backoff (at most once every 5 minutes) and resets on success. While an Account is disconnected, Outbox deliveries are only delayed, and do not consume retry attempts.
If an Account stays in `Connecting`, click Test connection once. If it still fails, the error text shown in the UI names the concrete cause, such as an unusable proxy or an unreachable endpoint.
### Agent attachments
Agents output attachments as `reports/daily.md`, with a file path relative to the current Workspace inside the tag. Desktop chat displays attachments in message order: documents have a file link, `photo` displays an image, and `audio`, `voice`, and `video` display playback controls. Local media uses Desktop's controlled file protocol; file links use the existing chat file navigation.
Tags in code blocks, inline code, or escaped text remain examples. An incomplete streaming tag stays readable and becomes an attachment after it closes. Do not place Markdown links or `http://filename` inside a tag: these display a format error with the original tag. File links remain available when a media preview cannot load. Unified attachment cards show the file type and name; hover over a truncated name to see the full path. Invalid tags are available under “Show details”.
## Account configuration
Account definitions and credentials have one source of truth: City Power Config.
```json
{
"accounts": [
{
"account_id": "support-telegram",
"name": "Support Bot",
"provider": "telegram",
"enabled": true,
"agent_id": "support",
"bot_token": ""
}
]
}
```
Feishu/Lark accounts use `app_id`, `app_secret`, and optional `domain`. QQ accounts use `app_id`, `app_secret`, and optional `sandbox`.
Adding a Feishu/Lark Channel in Desktop defaults to scan sign-in. Click Scan to create, scan the QR code with Feishu, and confirm on your phone; the App ID and App Secret are written automatically and the Account starts immediately, so nothing has to be copied from the Open Platform. The confirmation page is pre-filled with an app name and description, and pre-selects the scopes this channel needs together with the `im.message.receive_v1` event.
Scan sign-in uses the OAuth 2.0 Device Authorization Grant (RFC 8628) and can only create a new app, so it never overwrites an existing app's configuration. QR code lifetime follows the platform response (currently about one hour), and you can regenerate it after it expires. When scanning is not possible, such as when the organization has not enabled developer access or you want to reuse an existing app, switch to Manual credentials on the same page.
## Messages and Sessions
An allowed external message is persisted to Inbox, then routed through a Conversation to its own Channel Session (`category = "chat"`, `type = "channel"`). Each chat and thread under a Bot Account has a separate Session that subsequent messages reuse. Histories are separate from other chats and from the Agent's main conversation. Session Messages remain the only complete conversation history.
IM routing binds only an Agent and requires no Workspace selection. In Desktop, Channel Sessions and the Agent's main conversation default to the same main Workspace (`agents//main`), with the same Workspace tools, Powers, custom Agent tools, and Session management tools. Histories remain separate. Files and Shell use the current Workspace; Session management tools can create project Work Sessions. SDK hosts supply the default main context through the Agent's `workspace` option. An unconfigured Agent is selected automatically only when City has exactly one Agent.
Changing a Conversation's Agent or resetting it creates a new Channel Session and preserves the previous Session. Existing IM Work Sessions are also preserved during upgrade; chats continue in newly created Channel Sessions. Received attachments live in Messenger storage; outgoing attachments may use that storage and the Session's current project directory.
```text
Platform → Access → Inbox → Conversation → Channel Session
→ Outbox → Platform
```
Inbox deduplicates provider message IDs and prompts Session with a stable `request_id`. If the process exits after the User Message is committed, recovery does not append a second User Message. Agent results use stable Delivery IDs when entering Outbox, preventing duplicate jobs during recovery.
Outbox provides persistence, leases, bounded retries, and manual recovery. When a provider has no idempotent send protocol, external delivery is at-least-once: a crash after provider acceptance but before local acknowledgement can cause a repeated send.
## Agent Actions
An Agent can only access Conversations it owns through strict actions:
- `context`: read the current Chat Session route
- `list`: list Conversations owned by the current Agent
- `history`: read canonical Agent Session messages
- `send`: persist text to the reliable Outbox
- `react`: persist a Telegram message reaction to the reliable Outbox
## SDK assembly
```ts
import { MessengerPower } from "@downcity/powers/messenger";
const city = new City({
powers: [new MessengerPower()],
workspaces: [workspace],
power_host,
});
```
The City host provides Power Config, lifecycle Storage, and Agent Session capabilities. Connectors are restored during `initialize()` and closed together during `dispose()`.
## Feishu dependency
A host that enables a Feishu/Lark Account must install:
```bash
npm install @larksuiteoapi/node-sdk@^1.73.3
```
Scan sign-in relies on the SDK's `registerApp` and requires `^1.67.0` or later. On older versions the scan entry reports that an upgrade is needed, while manual credentials keep working.
## Related documentation
- [Power Lifecycle](/en/agent-sdk-docs/powers/lifecycle)
- [Built-ins Overview](/en/powers-docs/builtins/overview)
### Task Power
Source: https://downcity.ai/en/docs/power/task/
{/* User guide for Todo and Schedule shells; execution stays with the existing City TaskPower. */}
Switch between **Memo, Needs attention, List, Board, Calendar, and Timeline** in the Sidebar. Selecting a task opens details beside the collection on wide screens, making it possible to inspect adjacent tasks without leaving the view. Narrow content areas use a detail page with Back. Expand or close details explicitly; search, filters, sorting, dates, and collection position remain available.
All four views share search and completion filters, retaining the same task set when switching views. List and Board also support field sorting. The sidebar attention queue prioritizes review, failures, preparation, and active work, and keeps the selected task accessible. Use the main search to find tasks across the complete collection.
Memo uses Tiptap directly with its official TaskList and TaskItem extensions. A new document starts with a Todo; typing, Enter, Backspace, nesting, and paste use the editor's standard behavior. Exit the list to write paragraphs, headings, or code freely. The application never splits document content into business tasks. The whole document autosaves, and checkboxes are document formatting only: writing, selecting, and checking never invoke a model or start an Agent.
The memo automatically saves to this Desktop's local browser storage, surviving view changes and refreshes; this is not cloud synchronization. Save failures retain current editor content with an error and retry action. Unreadable stored data is preserved rather than overwritten with an empty document.
Selecting text shows a small How should I handle this? entry beside the selection. Write an instruction and send without leaving the document or choosing modes. Summarizing, rewriting, explaining, and extracting a todo list return a local preview without creating a business task. Replace selected text explicitly applies the result and can be undone. If the original selection was edited or deleted during processing, replacement is disabled; the result remains available to copy.
Only explicit requests to create, record, schedule, or delegate work enter the existing task flow with the original source and user instruction. A task link appears beside the selection without automatic navigation; source text stays intact. Read-only text processing uses the default text model from settings and has no tool privileges. Source and instruction together accept up to 24,000 characters; oversized requests are retained and rejected with a clear prompt.
The leading circle toggles personal one-time work between completed and unfinished. Agent results still require review before acceptance; recurring enable state is separate from completion. Each row's `···` menu offers applicable actions such as adjusting requirements in the input dialog, start or retry, open body, reopen, pause or enable recurrence, and delete with confirmation. Active execution restricts editing, deletion, and duplicate starts. Failed field saves retain edits; successful changes apply directly to the task.
Default sorting puts unfinished work first, ordered by its nearest execution or planned time, then undated work, with closed tasks last. Click Name, Type, Status, Executor, or Time headers to toggle ascending/descending order; arrows show the direction. Time sorting uses actual instants and the next calculable recurring trigger, keeping undated, paused, or unpredictable recurrence last in either direction. Creation time and task ID break ties consistently. List and Board share a collection toolbar for default sorting, field selection, and direction; the list headers and toolbar stay synchronized.
## Visual hierarchy
All Mainviews share the window header, content margins, local toolbar height, and content starting position. List and Board show collection context and sorting; Calendar and Timeline share one date-navigation component. Calendar's Week/Month controls select its local date range. Neutral surfaces, consistent typography, fine separators, and shared control sizes establish hierarchy. Color is reserved for status dots, narrow status bars, and errors. List separates Unfinished and Completed with counts and headers; Board uses column headings, counts, and lightly surfaced cards. Calendar and Timeline use fine grids, today markers, and clear time positions. Task input opens on demand to give views more room. Light and dark themes share semantic tokens, with hover, selected, and keyboard focus feedback. Popovers have opaque theme backgrounds.
## Views
Sidebar is the only place for task view navigation. Switching closes the selected detail and marks the current view. Collection and detail scroll independently. Expand hides the collection temporarily; collapse or close returns to its preserved position.
Needs attention uses unresolved task records for reviews, reminders, failed or missed work, and preparation questions. Selecting an entry locates its task or specific delivery without completing or dismissing it. Ordinary notifications appear as updates with an explicit Mark as read action; reading a notification does not resolve the task record. The current Task interface has no in-run question-answer or resume channel; tool approvals remain in the original execution session.
Board groups tasks into Not started, In progress, Needs attention, and Completed. Recurring tasks show their enable state separately. Card titles open details, timing uses field editors, and each card shares the list's action menu. Completing an occurrence does not end recurrence. Dragging between columns is not supported.
Calendar defaults to Month and can switch to Week. Neutral surfaces, fine date grids, and a single today marker keep the view simple; entries show only timing and title. Month displays only the complete weeks needed to cover that month, including weekends. Each cell previews three entries, with More expanding the remaining entries in place. Week displays all entries ordered by actual start time; entry height does not represent execution duration.
Click an entry for a lightweight preview containing executor, status, and full start/end times. Edit timing there or explicitly open the full task body; closing preserves the calendar position. Recurring status comes from the matching occurrence, so future dates do not inherit historical completion. Drag one-time plans to a date while preserving their time and duration; recurring and deadline entries are not drag-editable. Add note opens Memo; daily plus buttons or double-clicking empty date space supply a date used only when the user explicitly records or delegates memo content, never merely by writing. Plus buttons appear on hover, keyboard focus, or touch devices. The grid uses the device timezone, displays multi-day ranges on each occupied date, and never invents durations. The footer returns to List for unscheduled, out-of-range, or unexpanded tasks.
Timeline shows a navigable two-week range with a fixed task column, sticky date header, and today line. Click an out-of-range direction hint to locate its date. Planned ranges appear as bars and time points as separate diamond markers. Recurring tasks show their next calculable trigger. Undated tasks, paused recurrence, and advanced rules without a prediction remain accessible below the timeline. Timeline is currently read-only, without drag editing or dependency links.
## Todo
A memo Todo is simply a Tiptap document item, without a business task identity, per-item menu, or task-state synchronization. Explicitly processing a selection may create trackable work; source text and task links are stored outside the document. Editing or checking the document never changes the generated task, whose acceptance remains in task details.
Todo represents one-time work, with no time, a specific time, or a planned time range. A requested time can trigger one reminder or execution. A planned range does not imply continuous execution, and a deadline does not start an agent. Complete personal todos from the list and undo that completion. For agent results, complete the todo or request revisions.
If saving succeeds but starting fails, the form reports that the todo is saved but not started. Retry starting the same object instead of creating another todo.
## Schedule
Schedule represents recurring work based on Cron and a timezone. An explicit processing instruction for selected memo content can arrange a weekly research report or a one-time reminder. Merely writing those sentences in Memo never enables an automation.
Recurring tasks show a time summary and an enable switch. Detailed settings are available under More. Pausing does not stop active work, and a successful run does not end recurrence.
Personal reminders create an actionable reminder without an agent run. Planned ranges use planned_at and planned_end_at; the end must follow the start and does not imply repeated execution. Automatic triggers require City to remain running. Missed one-time Todos need a user decision; recurring work missed while offline is not replayed in a burst.
## Creation APIs
Use `task.create()` for structured task fields: it validates and saves without an internal model. Prefer it when the chatting Agent already knows the title, instructions, and timing. Use `task.generate()` for natural-language input from the Task page or an Agent; both share the same generation action.
Pass `text` to create, or `task_id` with changes to revise the same task. Generation waits for validation and saving and returns the complete task. Reuse `submission_id` for uncertain new submissions. Successful generation applies the arrangement without confirmation. Recording work does not start it; explicit immediate requests start execution and timed work waits for its trigger. Manual `create` work starts through `run`. Model failures retain the task identity for retry. Shared time validation checks formatting, timezone, and past triggers; relative dates use the current generation time.
## Input and saving
Memo follows write, autosave, explicitly process content, then inspect the linked task. Writing and checking do not create tasks or trigger execution. Only explicit actions in the processing panel create work. Generated tasks keep source links even if preparation or scheduling needs correction.
Existing tasks still offer Adjust requirements in their own context. Its Write directly method replaces the body while retaining title, executor, and schedule, without starting execution; AI mode interprets changes. This editor is separate from Memo's free writing. Linked tasks and deliveries are not deleted when the local memo source is edited.
Todo or Schedule follows the complete request, independently of list filters. A deadline does not trigger execution. Titles may repeat or change while identities stay stable.
## Task body and history
Select a task to read it within the current workspace: wide screens keep the collection beside details, while narrow screens provide Back. Task requirements are readable by default. Existing deliveries appear directly in the task with acceptance, revision, and failure actions; execution and error details expand on demand. A completed run does not by itself complete the work.
Tasks are not split into separate blocks by internal state or type. Older tasks remain in the same list with their identities and history intact. Reading a notification does not complete or accept work.
Execution history opens with the latest page. Choose Load more history to see earlier runs; the count shows loaded runs. Progress refreshes preserve loaded history and the current selection. An attention entry for an older run locates its result directly inside the task without loading all preceding history.
## Results and recovery
References share a compact block across the composer, queue, and sent messages. Task deliveries show the task title and result summary; messages, files, and code selections use distinct icons and source information. Click to expand the complete context. Editable references have a right-side removal action; read-only messages do not. Blocks have no shadows or decorative borders, and presentation never truncates the context sent to the model.
Delivery results provide two actions. Copy task reference writes structured HTML and readable plain text. Pasting into ChatInput restores the reference block; other apps can read the source and full output. Reference blocks have a Copy reference action, and selecting a reference in the editor supports system copy. Plain-text paste and paste inside code blocks remain text. Continue task opens a workspace new conversation for the task's Agent and Workspace, prefilling ChatInput with a structured delivery reference without sending. No existing conversation needs to be open. Existing new-conversation draft content is preserved; the Session is created on send through the normal application workflow. Missing execution targets are reported locally rather than silently replaced.
Results and history stay with the original object. One-time agent results require acceptance; recurring results follow the configured per-run acceptance setting.
Explicit acceptance and revisions with feedback publish replayable facts atomically with work state, retaining the specific result, original Agent/Workspace and bounded source snapshots. Execution success, opening a result and ordinary completion do not create acceptance facts. The official Power assembly lets Memory read these facts. Background consolidation is disabled by default and must be enabled for an exact scope in Memory; Task sources remain private to the original Agent. Deleting a Task archives its published command facts before removing the definition and run directories. Deletion does not erase every source copy.
Request revisions in the task's delivery section, then choose Submit and start revisions to save feedback and start a subsequent execution on the same task. If starting fails after saving, feedback remains available and Start revisions retries execution without resubmitting it. Previous results remain available. Feedback on a recurring result does not automatically change its standing instructions.
Retry failed execution separately from retrying AI organization. If an arrangement is saved but synchronization fails, retry synchronization without recreating work or calling the model again.
An Agent task's execution Session acts as a Work Main. It can dispatch independent work to multiple Work Children and incorporate their results within its original execution. Children and simulated reviewers cannot dispatch further work. While waiting, the Main can receive follow-up input and pass requirements to Children. A Child's public question notifies the Main while its pending state stays in the Child's original interaction. The Main can ask the user and relay the actual answer. Approvals and secret questions use only their original trusted entry points; the Main cannot approve or relay private answers.
After a City restart, interrupted work is retained for review rather than silently replayed. Shell tasks with `auto_notify_on_exit` enabled report completion automatically to the original execution; late results cannot wake it after it stops. Restart recovery only delivers saved completion results. Processes that cannot be taken over are reported as interrupted or unknown, without rerunning commands. Wait for active execution to finish before editing its definition or deleting it.
Chat-created work retains its original delivery session even if the executor changes. Results can still be queued for asynchronous handling in that Chat after its original Turn finishes or is stopped. Stopping Chat's current reply does not cancel the background Main; explicitly stopping the Main cascades to its Children. Explicitly instruct the executing agent to use Messenger when external delivery is required.
Continue with [Messenger Power](/docs/power/messenger) or [Agent Powers Docs](/powers-docs).
### Memory Power
Source: https://downcity.ai/en/docs/power/memory/
Each Downcity platform data root has one local User independent of Federation login accounts. City owns base user information; MemoryPower owns User and Agent memories.
## Per-turn context
Initial system assembly or syncshot → load both Profiles → freeze with Instruction → process messages and optional tools.
User Profile applies across local Agents and Sessions; Agent Profile applies to one Agent. Identity and Instruction share one Agent system message, immediately followed by a separate Agent Profile message. User Profile is an independent system message before Session information. Both Profiles are frozen with Instruction and never enter user content. New Sessions and syncshot read the complete current Profile. Existing Sessions retain their frozen system and receive bounded turn-local reference updates when core versions change. These updates invalidate the earlier snapshot for that scope. If the current content exceeds the budget, omitted content must be read again or loaded through a full snapshot refresh. Historical preferences do not define the current task or override current requests and permissions.
## Saving
```json
{"target":"user","mode":"profile","content":"Before the main answer, remind me to speak English and briefly correct my expressions."}
```
remember.target accepts user, agent and current_workspace. mode accepts profile or knowledge, defaulting to knowledge. Profile supports User/Agent; Workspace supports knowledge only. User writes need no login or identity callback. The Agent decides when to call tools and confirms saving only after success.
## Storage and maintenance
`user/user.json` holds base information, `user/PROFILE.md` holds global agreements, and `agents//PROFILE.md` holds Agent-specific agreements. Published scope manifests manage knowledge; search/read/list access only the current effective set. User knowledge is stored once and shared across local Agents. Profile uses separate files, scope locks and pending-operation recovery. It is outside the knowledge manifest and does not share an atomic transaction with knowledge commits.
The runtime does not automatically migrate or fall back to existing wiki files. Use the SDK-level `create_memory_import_changeset` helper to explicitly construct an import change set, then commit through the Provider. Confirm sources, scope and backups before importing.
Both Profile scopes use deterministic read, append and exact-edit operations. Writes carry a base version and trusted sources; replaying a request does not append it twice, and version conflicts require a fresh read. Edits require unique matches, non-overlap and preserved source markers, with a backup before content changes. To consolidate a Profile, explicitly call `memory.optimize` with `target=user` or `target=agent`. The Memory Coordinator submits an optimization Job to a dedicated Memory Session. Length checks help assess whether consolidation is useful and do not trigger it automatically. The Profile file service does not call models or run optimization timers.
`digest`, `revise` and `optimize` run asynchronously and return a Job ID. Requests made in a Session subscribe that calling Session and Turn to the eventual result, including success, no change or failure. For `digest`, the receiving Session is the caller, which may differ from the source Session. Feedback is injected only while the original Turn can receive it. If that Turn has ended, the result remains available in processing records; no new Turn starts automatically. Completion feedback is persisted and handled idempotently: `delivery_status=delivered` means injected, while `delivery_status=saved` means retained without injection and ends delivery. Delivery failures are retried with backoff without changing the memory commit status. Management-page requests have no chat recipient. Use processing records to check the result when needed, and avoid repeated polling or repeating a saving confirmation already delivered for that Job.
Use `memory.jobs` for paginated records in the current Agent and Workspace, `memory.job_status` for a specific request, and `memory.retry` to retry a failed record. Lists and status contain no source text. To inspect changes and evidence, call `memory.job_detail` with `{"job_id":""}`. The detail endpoint checks the current Job's Agent/Workspace scope and returns `{job, changes}` with the authorized source excerpts persisted for that request. Lists and status contain no source text. The processing records view shows fixed before/after content, the version read for the change and original source excerpts. Profile changes show the exact edited regions. These snapshots describe that operation, not the latest content; records without captured snapshots return an empty changes list.
Only `succeeded` confirms a commit; `skipped` means no changes were needed. Pending or failed changes shown in details do not establish that memory took effect. Within the same request scope, optimizing the same Profile version reuses a stable source identity, and digesting the same captured sources under the same extraction policy reuses the processing request. Unrelated changes to stored knowledge do not create another digest request.
There is no per-turn chat copying or automatic per-turn capture. Forgetting knowledge removes it from the current effective set and suppresses identical later submissions using exact fingerprints of normalized content; it does not guarantee suppression of semantic rephrasings. Deleting a Profile stops use of its current content. Backups, original Sessions and source-content copies in Jobs remain; these operations do not erase every historical copy. Switching service accounts does not switch local memories. Channel authorization remains the host's responsibility.
## Background consolidation
Memory's background consolidation page offers switches for an exact Agent, Workspace and knowledge target, disabled by default. Trusted inputs are directly entered corrections and, in the official Power assembly, Task accept facts and revise facts with explicit feedback. Execution success and a Turn ending do not establish acceptance. Private Session history is not imported automatically. Task facts publish atomically with acceptance state and retain fixed source snapshots in an archive before Task deletion; deleting a Task does not erase every source copy.
Maintenance checks run every five minutes. Empty queues make no model calls. Each batch fixes one Agent and target with at most 4 facts, 16 sources and 32,000 characters. Each scope reserves at most 2 automatic computations per UTC day, including retries, at least 10 minutes apart. Explicit requests take priority at Job boundaries. Disabling stops new automatic computation; work already started may complete within its bounds.
Automatic results write only Agent/Workspace knowledge. Task sources remain private to the original Agent unless sharing is explicitly authorized. Profiles and User knowledge are not modified automatically. The page shows backlog, accepted sequence, continuous processed watermark, deferrals, errors, source boundaries, batches and corresponding Jobs. Only succeeded reconciled with a commit receipt or an explicit skipped result marks input processed. Failures and quota deferrals retain input. Retry automatic batches from this page; ordinary memory.retry handles failed explicit requests. Background work has no chat recipient, so a commit does not establish summary delivery.
- [Memory Power reference](/en/powers-docs/builtins/memory)
### MCP Servers
Source: https://downcity.ai/en/docs/power/mcp/
MCP is managed by the built-in Skill Power. Its unified Sidebar lists individual resources under Skills and MCP; selecting a server shows status, tools, and errors. Manage server definitions in Skill Config. Existing server definitions and OAuth credentials remain in the global MCP storage directory and are shared across Agents and Workspaces.
Enable a server for an Agent in **Agent Profile → Skills**. Access requires an explicit assignment, stored as a JSON array of server IDs at `~/.downcity/agents//mcp-servers.json`. A missing file grants no access. Global server enablement alone does not grant access; removing an assignment preserves the shared definition and credentials. Host actions `skill.mcp.assign` and `skill.mcp.unassign` accept `{ agent_id, server_id }` and are not exposed to the model.
## Configure a server
Each server uses one file at `~/.downcity/powers/mcp/servers/.toml` by default. The filename is its server ID. If the host uses a different MCP config path, the `servers` directory is beside that config file: `dirname(config.path)/servers`.
For an already installed local stdio server:
```toml
title = "Filesystem"
enabled = true
command = "mcp-server-filesystem"
args = ["/absolute/allowed/directory"]
cwd = "/absolute/working/directory"
env = { LOG_LEVEL = "info" }
request_timeout_ms = 60000
max_result_chars = 100000
```
Replace the command and arguments with those required by your server. For a Streamable HTTP endpoint:
```toml
title = "Remote MCP"
url = "https://mcp.example.com/mcp"
headers = { "X-Client" = "downcity" }
```
Specify exactly one non-empty `command` or `url`. `args`, `cwd`, and `env` belong to local programs; `headers` belongs to HTTP endpoints. There are no `source`, `install`, or `transport` sections. `title` is optional. Omitted `enabled` defaults to `true`; optional `request_timeout_ms` and `max_result_chars` default to `60000` milliseconds and `100000` characters. Set `cwd` explicitly for project-specific servers: a shared connection does not inherit the caller's Workspace. `${NAME}` in arguments, working directories, URLs, and headers reads from the host environment.
The Desktop editor edits the actual server file. Use explicit Save or Delete for each server. File changes are checked against the original text (`expected_content`); if another edit has changed the file, the operation is rejected to prevent stale content from overwriting it. Reread the file before saving again.
Initialization, definition reads, and single-file saves only scan and validate definitions; they do not start or connect to a Server. After editing files outside Desktop, reread definitions in Config to discover the changes without executing a Server. Explicit Test, Mainview connection Refresh, or the first `tools`/`call` request connects to the Server. Refreshing a resource reconnects only the selected Server; Config's global Refresh reconnects all enabled Servers. Tool discovery reads every page of the tool list for both stdio and HTTP connections. Validation errors identify the affected file while valid servers remain available. Changing, disabling, or deleting a definition releases its affected connection; City shutdown closes all connections.
Loading or editing a definition does not install software. Known implicit-install runners such as `npx`, `bunx`, and `uvx`, along with package-manager install-and-run entry points, are rejected. Install the required program through the existing approval workflow first, then configure its installed executable. Existing `config.servers` collections are not read or automatically migrated; create individual server files explicitly.
## HTTP OAuth authorization
For HTTPS servers implementing MCP OAuth, a 401 starts SDK discovery, dynamic client registration and authorization code login with PKCE. Downcity opens the system browser and accepts the callback on `127.0.0.1`; the pending connection resumes after login. Test, connection Refresh, tool discovery/calls and explicit reauthorization can open the browser. Reading status or saving definitions never does.
```toml
title = "OAuth MCP"
url = "https://mcp.example.com/mcp"
auth = "oauth"
# Set a pre-registered public client ID when dynamic registration is unavailable:
# client_id = "your-client-id"
# client_name = "Downcity"
```
These fields belong at the TOML root. `auth` is optional: a standard 401 also triggers discovery. Pre-registered clients must accept loopback callbacks with dynamic ports. OAuth metadata, issuer, registration and token endpoints must use HTTPS. Static `headers` remain available for API keys; when an OAuth token is available it supplies Bearer authorization.
The MCP server detail view displays `none`, `authorizing`, `authorized` or `expired` and provides Reauthorize and Cancel authorization buttons. Servers connect independently, while operations for one server are serialized to avoid duplicate login windows. Authorization waits at most five minutes and responds to cancellation and City shutdown. Tool operations still honor `request_timeout_ms`, so reauthorization during a call may have a shorter remaining deadline.
Credentials are stored under `dirname(config.path)/auth/`, isolated by server ID, exact endpoint and issuer. Files use `0600` permissions and the directory uses `0700`. The plaintext records contain client information, tokens and expiry, never authorization codes, state or PKCE verifiers. Tokens are excluded from Agent status and diagnostic errors. The SDK refreshes refresh tokens; failed refresh can lead to login again. The SDK manages session headers, protocol negotiation and SSE. An explicit HTTP 404 allows one session rebuild and retry; ambiguous network failures never replay a tool call.
Servers must implement the required discovery and authorization protocol. Twinkle Cloud protocol compatibility, initial login, refresh and restart reuse have not been verified against its live service.
## Agent workflow
Agents use the Skill Power's `servers`, `tools`, and `call` actions. Servers are not registered as separate Powers, and external tools are discovered on demand. The `list` and `lookup` actions remain available for Skills.
```ts
skill({ action: "servers" });
skill({ action: "tools", args: { server_id: "filesystem" } });
skill({ action: "call", args: {
server_id: "filesystem",
tool_name: "read_file",
arguments: { path: "/allowed/example.txt" },
} });
```
Use `servers` to list servers assigned to the calling Agent and their status, including disabled or invalid definitions, `tools` to inspect original tool names and input JSON Schemas, then `call` to invoke a tool. Replace the example tool name and path with values supported and permitted by your server. MCP validates arguments locally before sending them. Unassigned, disabled, or invalid servers cannot be called. Assignment checks apply to both `tools` and `call`.
This structured discovery and invocation interface has no standalone shell executable. Server file management is available in Desktop; the MCP Agent interface is provided by `skill` through `servers`, `tools`, and `call`.
## Approval and limits
`call` is classified as write access and has `approval: false`; calls to enabled servers assigned to the calling Agent execute without an additional MCP approval. MCP provides no installation or uninstallation tools. Program installation and removal use the existing approved execution workflow. Server descriptions and results are external data, never Agent instructions. Calls support cancellation and the configured timeout; oversized results carry a truncation marker.
stdio servers execute local programs. Configure trusted servers explicitly and maintain credentials in the owning environment settings instead of sending plaintext through chat. Interactive MCP input requests are not supported.
The three Agent actions remain stable when server files change. Server Power registration and synchronization are unnecessary.
### Shell
Source: https://downcity.ai/en/docs/power/shell/
Shell is a Workspace capability, not a Power. It owns its Sandbox Provider, the isolated Workspace Sandbox, and reusable Shell Sessions.
## What it does
- Executes commands in the Workspace Sandbox by default
- Keeps installed tools and HOME state across Chat Sessions
- Captures stdout, stderr, and exit codes
- Supports timeouts and cancellation
## Long-running work and completion notifications
Use Shell's `exec` action for short commands and `session_start` for long-running or interactive processes. With `auto_notify_on_exit: true`, command completion automatically reports success, failure, or an explicit stop to the original Session. No polling is needed, and each completion is handled once.
Notifications are processed at execution checkpoints, without a guarantee of immediately interrupting model requests or synchronous tools. If the original execution has stopped, closed, or been replaced, results remain saved and late notifications do not wake it again. Use `auto_notify_on_exit: false` for long-lived services. After restart, only delivery of saved completion results is restored. Original processes that cannot be taken over are reported as interrupted or unknown; commands are not automatically rerun.
See [Shell and Sandbox](/en/agent-sdk-docs/local-agent/shell-reference) for calls and lifecycle details.
## Safety
Shell has only two targets: `sandbox` and `host`. Sandbox execution is the default and cannot see arbitrary host paths. Host execution requires an explicit reason and host approval; Sandbox failures never fall back to the host.
## Use cases
- Running build scripts
- File system operations
- Querying system state
- Executing project-specific tools
Continue with:
- [Messenger Power](/en/docs/power/messenger)
- [Task Power](/en/docs/power/task)
- [Agent Powers Docs](/en/powers-docs)
### Custom Power
Source: https://downcity.ai/en/docs/power/custom/
One directory defines one Power. The Power ID is its install directory, City catalog key, and runtime identity. There is no separate Extension identity.
## Two optional entries
```text
Power
├── main provides City instances, lifecycle, management logic, and actions
└── renderer declares a Sidebar + Mainview workspace and/or Config
```
Each entry is optional, but at least one is required. A Power may provide only City runtime capabilities, only a Sidebar + Mainview workspace, only Config, or the complete experience.
Recommended development layout:
```text
github-power/
├── power.json
├── package.json
├── README.md
├── assets/icon.svg
├── src/
│ ├── power.ts
│ ├── main.ts
│ └── renderer.tsx
└── dist/
├── main.js
└── renderer.js
```
Both entries use ESM. `main.js` must be self-contained. `renderer.js` is a single-file browser bundle that default-exports a Renderer definition with an optional `sidebar + mainview` pair and an independent `config`. Downcity does not install dependencies or run build scripts.
## Direct SDK usage
SDK users can construct a `CityPowerRegistration` directly without `power.json`:
```ts
const registration = {
id: "github",
title: "GitHub",
description: "GitHub integration",
readme: "/absolute/path/README.md",
has_config: false,
has_sidebar: false,
has_mainview: false,
power: new GithubPower(),
};
const city = new City({
powers: [registration],
workspaces: [workspace],
});
city.agents.add(agent);
```
The following entry protocol is only needed when CLI or Desktop must install, discover, and manage the Power.
## Power definition
```json
{
"schema_version": 1,
"id": "github",
"version": "1.0.0",
"title": "GitHub",
"description": "GitHub integration",
"readme": "./README.md",
"icon": "./assets/icon.svg",
"main": "./dist/main.js",
"renderer": {
"entry": "./dist/renderer.js",
"sidebar": true,
"mainview": true,
"config": true
}
}
```
`renderer.sidebar` and `renderer.mainview` must both be `true` or both be `false`; `renderer.config` is independent. The actual default export must exactly match these three static capabilities. `package.json` must declare `"type": "module"`. `readme` must point to a `.md` user document inside the Power root. Desktop safely renders that file in the Power Overview; its name and subdirectory are up to the author, and it should describe purpose, configuration, and required credentials. The icon may be an HTTP(S) URL or a file relative to the Power root and is used in Power navigation and the Overview.
## Unified Power entry
The `main` file default-exports one Power instance. There is no separate `agent` entry or second
main lifecycle. During `initialize()`, `power.action()` registers Sidebar/Mainview Actions and
`power.config_action()` registers Config Actions:
```ts
import { Power, type PowerLifecycleContext } from "@downcity/city/power";
class GithubPower extends Power {
readonly name = "github";
readonly title = "GitHub";
readonly description = "GitHub integration";
initialize({ power, notifications }: PowerLifecycleContext) {
power.config_action({
id: "config.read",
run: async (_input, context) => {
const config = context.config.get();
return { api_url: config.api_url, token_configured: Boolean(config.token) };
},
});
power.config_action({
id: "config.save",
run: async (input, context) => {
const current = context.config.get();
const config = validate_and_restore_secret(input, current);
await context.config.set(config);
return { saved: true };
},
});
void notifications.publish({
topic_key: "sync:repository",
title: "Repository sync completed",
route: { repository: "downcity", view: "activity" },
});
}
}
export default new GithubPower();
```
One Power ID maps to one instance, one lifecycle, and one configuration per City. City injects the
unique Config store into Config actions, while the execution instance reads its current snapshot from
`PowerContext.config`.
`notifications.publish()` and `notifications.dismiss()` are always bound to the current Power. The host namespaces `topic_key` and treats `route` as a route inside that Power workspace, so a Power cannot impersonate another Power or navigate to arbitrary Desktop pages. Only the latest unread notification for the same `topic_key` is retained.
`PowerLifecycleContext.system` exposes only explicitly authorized City host capabilities. To append a background result to an existing Session, call `append_agent_session_message({ agent_id, workspace_id, session_id, category, text })`. All four identity fields must come from an explicit persisted target; a Power must not scan for or guess a Session.
For functional pages such as a Skill manager, `system.list_workspaces()` returns summaries of Workspaces registered by the host. A Power is trusted local Node.js code; it must validate action inputs and own its file, network, and long-lived resource behavior.
## Renderer entry
The Renderer declares UI slots in one bundle. `sidebar` and `mainview` form the Power workspace, must be declared together, share a host-owned JSON route, and cause the host to add a dynamic top-level navigation entry. `config` is independent from the workspace and appears only on the Power Catalog detail page. Optional `agent_config` contributes one tab to Agent Profile. These surfaces use host-provided UI Components:
```tsx
import { useEffect, useState } from "react";
import { define_power_renderer } from "@downcity/city/power/react";
export default define_power_renderer({ config: function GithubConfig({ config, ui }) {
const { Button, Group, Input, LoadingState, Page, Row, Toolbar } = ui.components;
const [config_state, set_config_state] = useState<{ api_url: string }>();
useEffect(() => {
void config.invoke<{ api_url: string }>("config.read").then(set_config_state);
}, [config]);
if (!config_state) return ;
return
void config.invoke("config.save", config_state).then(() => ui.toast({ type: "success", message: "Saved" }))}>Save} />
set_config_state({ ...config_state, api_url })} />} />
;
} });
```
The Renderer bundle must leave `react` and `react/jsx-runtime` as host externals mapped to `downcity-power://runtime/react` and `downcity-power://runtime/react/jsx-runtime`. Bundle other frontend dependencies into the single `renderer.js` file.
Desktop loads the Renderer in its host React tree. Sidebar and Mainview use `power.invoke()` for Power-level actions and coordinate through `navigation`; Config uses `config.invoke()` for the current Power's Config actions. Each slot receives only its required gateway and host UI—never the Desktop controller. Renderer is trusted local UI code, so install only trusted sources.
Sidebar and Mainview also receive a read-only `notifications` array scoped to the current Power. Each item includes the local `topic_key`, content, route, and creation time so navigation objects can render unread state. Navigating to the notification's exact route lets the host mark it read; the Renderer cannot publish or mutate notifications.
When a Sidebar needs a creation entry in its header, pass the host-provided `SidebarCreateMenu` through the `Sidebar` component's `actions` prop. The host owns the header, plus button, and dropdown presentation; the Power declares only the creation types and the business navigation for each selection.
Use `SidebarTreeItem` for a tree Sidebar: `depth` expresses hierarchy, `kind` distinguishes `branch` and `leaf`, parents own expansion through `expanded` and `on_toggle`, and `on_select` updates the Mainview through shared `navigation`. When `leading` is omitted, the host supplies consistent default icons for branches and leaves. A branch with no children can omit `on_toggle` and will not show a disclosure button. History and other deeper navigation should remain in this tree instead of consuming Mainview space. Use `ItemMenu` for row actions and the host-safe `Markdown` for Markdown content. After a mutation, call `ui.invalidate()`; the host increments the shared `ui.revision` for that Power across Sidebar, Mainview, Config, and Agent Profile tabs. Reload snapshots in place, retaining existing data and an open reader during background refresh; reset Agent-specific state when `agent_id` changes. Keep refresh state out of the route.
### Agent Profile tab
Declare `agent_config: { id, label, component }` to contribute one Agent Profile tab. `id` and `label` must be non-empty strings. The host collects declarations from enabled Powers and namespaces the tab ID by Power. Catalog refreshes preserve the selected tab and mounted component while the same renderer registration remains available. No additional `power.json` capability flag is required, and the slot can be declared independently of Sidebar, Mainview, and Config.
```tsx
import { define_power_renderer } from "@downcity/city/power/react";
import type { PowerAgentConfigComponentProps } from "@downcity/city/power/react";
function AgentSettings({ agent_id, ui }: PowerAgentConfigComponentProps) {
const { Page, Row } = ui.components;
return
;
}
export default define_power_renderer({
agent_config: { id: "settings", label: "Settings", component: AgentSettings },
});
```
The component receives exactly `{ agent_id, power, ui }`. `agent_id` identifies the Agent being configured. `power.invoke(action_id, input)` uses the owning Power's business action gateway, as in Mainview; it does not use the Config gateway. The Power validates the target Agent and action inputs. The slot receives no `navigation` or `notifications` props.
`PowerAgentConfigDefinition`, `PowerAgentConfigComponent`, and `PowerAgentConfigComponentProps` are exported from `@downcity/city/power/react`. Use `ui.components` for layout and `ui.invalidate()` after mutations; the host advances the Power's `ui.revision` so its surfaces can reload. The built-in Skill Power uses this generic slot for **Agent Profile → Skills**, including skill links and MCP assignments.
## Config interaction
```text
Open the Powers Catalog and select a Power
→ edit the Power's unique configuration in Config
→ save and let the Power refresh affected long-lived resources
```
Each Power ID has one Config, independent from Sidebar/Mainview. The host only persists it and does not interpret fields or generate a form from JSON Schema. Structure, validation, defaults, Secret behavior, and resource refresh after save belong to the Power.
Configuration is stored under `~/.downcity/powers//config.toml` with directory mode `0700` and file mode `0600`. The current store uses TOML, so values must be a TOML-compatible JSON object. `agent.json` stores no Power references; City automatically provides every Power and the same configuration to every Agent.
## Install
```bash
city power install ./github-power
# Configure GitHub on its detail page in Desktop Powers
city power config github --set '{"api_url":"https://api.github.com"}'
city power update github
city power uninstall github
```
The installer copies only `power.json`, `package.json`, the Markdown file declared by `readme`, runtime entries, and an optional local icon. It never runs dependency installation, build scripts, or any entry. Local paths cannot escape the Power root or use symlinks. Installed artifacts receive a SHA-256 integrity digest. Install only trusted sources.
Continue with:
- [CLI Commands](/en/docs/cli/commands)
- [Agent Powers Docs](/en/powers-docs)
### City
Source: https://downcity.ai/en/docs/city/overview/
**City** is Downcity's local Agent host container. It keeps Agent instances in memory and forwards HTTP/RPC requests to the selected Agent.
## What City owns
- **Agent collection** — `city.agents.add(agent)` admits an existing Agent, `city.agents.get(agent_id)` reads one, and `city.agents.list()` lists them.
- **HTTP/RPC forwarding** — City owns two transport ports and forwards requests by `agent_id`.
- **Host lifecycle** — CLI/Desktop create and dispose City, Agent, Workspace, and platform resources; City owns its server lifecycle.
## What City does not own
- Model catalogs, identity, usage, and billing, which belong to Federation/Embassy.
- Database adapters for Agent configuration and Workspace assembly, which belong to the host composition root.
- Concrete Power storage, which belongs to the selected Power Provider/Adapter.
These belong to the Agent runtime.
## How Agents connect to City
When you run `city on`, the CLI reads configuration from the global DB, explicitly creates every Agent, registers them with one `City`, and starts City's HTTP/RPC servers.
When you use the SDK directly, create an `Agent` yourself. Call `city.agents.add(agent)` when you need unified HTTP/RPC forwarding.
## Where to learn more
- [City SDK](/en/city-sdk-docs) — the SDK for building on City infrastructure
- [Payments](/en/payments) — accounts, balance, usage, and payment APIs
- [Agent SDK](/en/agent-sdk-docs) — how Agents consume City services at runtime
### Model Pool
Source: https://downcity.ai/en/docs/city/model-pool/
City owns the model catalog through the Federation AIService. Agents do not embed provider keys or model definitions directly. Instead, they bind to models by ID, and City resolves the ID to a live model instance at runtime.
## How it works
1. City registers model providers (OpenAI, Anthropic, Google, local models, etc.)
2. Each provider exposes capabilities and model IDs
3. The Federation AIService maintains a unified catalog
4. Agents bind to a model ID like `"default"` or `"quality"`
5. At runtime, the ID is resolved to a live model instance
## Model binding
For Desktop- or CLI-managed Agents, the binding is stored in the user-level Agent configuration:
```json
{
"execution": {
"type": "api",
"model_id": "quality",
"reasoning_effort": "high"
}
}
```
In Desktop, open **Model** in the Agent configuration to select its default model and reasoning effort. Choices come from the model's published capabilities. Models without configurable reasoning hide the selector. Choosing **Follow model default** removes `execution.reasoning_effort`.
`reasoning_effort` is optional; `high` in this example must be a supported effort. Explicit session or execution reasoning takes precedence, followed by the Agent default and then the model default. New sessions, background tasks and delegated work inherit the effort when using the Agent's default model. Switching models retains only supported efforts; otherwise the model default applies. An Agent's default effort applies only to its configured default model.
Desktop saves affect subsequent execution; an active turn keeps its configuration, and existing session overrides retain priority. CLI configuration changes apply when the Agent is next assembled.
For SDK projects, the model is passed directly to the constructor or session.
## Provider management
City handles:
- Provider registration and authentication
- Model capability discovery
- Usage metering per provider
- Failover between providers
Continue with:
- [City Identity](/en/docs/city/identity)
- [Usage & Billing](/en/docs/city/usage-billing)
### Identity
Source: https://downcity.ai/en/docs/city/identity/
Federation issues user identities and stores account data. Clients access Federation directly
through Embassy. A product configures its trusted Bureau business endpoint only when it needs a
backend of its own.
## Identity Boundaries
- **Federation**: the server runtime that issues `user_token` credentials and manages accounts, Services, and Bureau records.
- **Embassy User**: holds the current `user_token` and performs user login and business requests.
- **Embassy Admin**: manages Federation with an Admin Session, including authorizing Federation to issue Bureau Tokens.
- **Bureau**: a product partition selected by `bureau_id`; its backend uses an independent Bureau client as its machine identity.
Embassy exposes only `user` and `admin` identity domains:
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: "https://fed.example.com",
});
```
Embassy is not bound to a Bureau. A login flow supplies `bureau_id` only when it needs a product partition.
## User Identity
Account flows live under `embassy.user.account`. After login, the same Embassy instance starts
using the new User Token immediately:
```ts
const providers = await embassy.user.account.providers();
await embassy.user.account.login({
provider: "email",
client_type: "cli",
bureau_id: "product-web",
input: {
email: "user@example.com",
password: "password",
},
});
const current_user = await embassy.user.current();
const user_token = embassy.user.account.token();
```
Email login requires completed verification. The SDK automatically exchanges the completed login for a token. `await embassy.user.account.logout()` revokes the current token before clearing local credentials; failure retains it for retry. Bureau validates new protected requests online with Federation and rejects access when validation is unavailable; existing streams continue.
A User Token is a JWT signed by Federation with Ed25519. It carries `user_id`, `bureau_id`,
issuer, audience, and expiry claims. Public verification keys are available at:
```text
/.well-known/downcity.json
/.well-known/jwks.json
```
User AI, Payment, and regular Service requests go directly to Federation:
```ts
const models = await embassy.user.ai.catalog();
const accounts = embassy.user.service("accounts");
const services = await embassy.user.list_services();
```
When the current Bureau has a trusted `server_url`, relative-path requests are sent to that origin
with the current User Token. Embassy does not forward the token to another origin:
```ts
const result = await embassy.user.post(
"/reports/summary",
{ range: "today" },
);
```
## Administrator Identity
An administrator exchanges an ID and password for an expiring Admin Session. There is no Root
Admin Token:
```ts
await embassy.admin.login({
admin_id: "owner",
password: "password",
});
const current_admin = await embassy.admin.current();
const bureaus = await embassy.admin.bureaus.list();
```
If the password is lost, an operator with deployment access resets it with
`fed deploy --admin-reset`.
## Bureau Token
An authenticated Federation Admin can issue a Bureau Token:
```bash
fed bureau token
```
The CLI asks Federation to generate a high-entropy token. Federation stores only its `token_id`,
purpose, hash, and lifecycle status. The plaintext is returned once and belongs in the service environment:
```bash
DOWNCITY_FEDERATION_URL=https://fed.example.com
DOWNCITY_BUREAU_TOKEN=fb_br_xxx.secret
```
The business service verifies incoming Federation User Tokens through the independent `Bureau` client:
```ts
import { Bureau } from "@downcity/federation";
const bureau = new Bureau({
federation_url: process.env.DOWNCITY_FEDERATION_URL!,
bureau_token: process.env.DOWNCITY_BUREAU_TOKEN!,
});
const identity = await bureau.identify(request);
```
`bureau_token` is a long-lived, revocable opaque Bearer credential. It is not a JWT and cannot issue
User Tokens. It is bound to a `bureau_id` when created; `identify()` validates the signature,
issuer, audience, expiry, and that `bureau_id`. Revoke a leaked token immediately with
`fed bureau token revoke `.
Federation remains the sole User Token issuer. Account login and Admin management APIs are only
entry points into Federation's issuing flow; a Bureau Token cannot call the User Token issuing API.
| Credential | Holder | Purpose | Verification |
| --- | --- | --- | --- |
| `user_token` | User client | Access Federation and Bureau business APIs | Federation JWKS signature |
| `admin_token` | Administrator Embassy | Federation control plane | Federation Admin Session |
| `bureau_token` | Bureau business service | Prove machine identity and call `identify()` | Federation credential hash |
Continue reading:
- [Federation SDK](/en/city-sdk-docs/packages/federation)
- [Model Pool](/en/docs/city/model-pool)
- [Usage & Billing](/en/docs/city/usage-billing)
### Usage & Billing
Source: https://downcity.ai/en/docs/city/usage-billing/
City meters every model call and tracks usage across all connected Agents and products. This is the foundation for billing, quotas, and cost management.
## Usage tracking
- Every model request is metered (tokens in, tokens out)
- Usage is aggregated per user, per project, and per model
- Real-time usage dashboards are available in the Console
Federation administrators with an active Admin Session can read server-side aggregates:
```text
GET /v1/usage/admin/overview?from=2026-07-07&to=2026-08-05&timezone=Asia/Shanghai
GET /v1/usage/admin/users?from=2026-07-07&to=2026-08-05&timezone=Asia/Shanghai
GET /v1/usage/admin/retention?from=2026-07-07&to=2026-08-05&timezone=Asia/Shanghai
```
`overview` returns range-active users, true de-duplicated daily DAU/WAU/MAU series, outcomes, token
composition, Credits, model and action distributions, local-hour activity, and average/P50/P95
duration. `users` returns calls, input/output/total tokens, success rate, top model, Credits, duration,
and last activity per user. `retention` combines Accounts registration time with real AI Usage active
dates to calculate D1, D3, D7, D14, and D30 registration-cohort retention. Failed and cancelled calls
still represent real product activity, so they count toward activity and remain visible in outcomes.
## Balance
- Users maintain a balance account in City
- Balance is consumed as usage accrues
- Low balance triggers alerts
- Auto-recharge can be configured
## Billing
City integrates with Stripe for:
- One-time payments
- Subscription plans
- Usage-based billing
- Invoice generation
## Quotas
- Soft quotas warn before limits are reached
- Hard quotas block requests when exceeded
- Quotas can be configured per user, per project, or per model
Continue with:
- [Model Pool](/en/docs/city/model-pool)
- [City Identity](/en/docs/city/identity)
### Federation & Service
Source: https://downcity.ai/en/docs/federation/overview/
**Federation** is the shared server runtime that City connects to. It owns user identity, City isolation, Service routing, model catalogs, usage, and payments, while providing a unified interface over multiple AI providers.
## Federation AIService
The Federation AIService is a City component that:
- Registers model providers and their capabilities
- Exposes a unified model API regardless of the backend
- Tracks usage and routes requests to the appropriate provider
- Handles failover and rate limiting
An Agent binds to a model through an ID like `"default"` or `"quality"`. The Federation AIService resolves this ID to a live model instance at runtime.
## Service / Action infrastructure
City also provides a general-purpose **Service** and **Action** layer for building backend capabilities that Agents can call:
- **Service** — a long-running backend capability (e.g., a knowledge base, a search engine, a database)
- **Action** — a discrete operation that an Agent can invoke (e.g., send an email, query a database, call an external API)
Services and Actions are registered with City and can be discovered and called by any connected Agent.
## Relationship to City
`Federation` is the server and `City` is the user client carrying a `user_token`. When you use the City SDK, you are interacting with:
- City identity and auth
- Federation AIService (model catalog and routing)
- Service/Action infrastructure (backend capabilities)
- Usage, balance, and billing (City Services)
Federation generates an Ed25519 Key Ring on first startup and publishes verification keys through `/.well-known/jwks.json`. Embassy can connect to Federation directly; a product deploys Bureau only when it needs its own backend capabilities. A Bureau Token and the independent Bureau client let that service verify User Tokens locally. Federation does not create Bureau Tokens on startup.
## Local service operation
Local Federations use macOS user-level launchd or Linux user-level systemd. `[deployment.process]` defaults to `auto_start = false` and `restart_on_failure = true`: unexpected exits trigger recovery every 10 seconds, limited to 5 attempts within 60 seconds. `fed stop` disables automatic startup and stops the service. It remains stopped across system restarts until an explicit deploy/restart.
Automatic startup requires explicit opt-in. macOS starts after user login; Linux requires the user's manager to exist and be available. The CLI does not enable linger. System service definitions contain no secrets; runtime configuration is stored separately. See [CLI Quickstart](/en/city-sdk-docs/packages/cli/quickstart) for configuration examples and `status`/`logs` behavior.
## Administrator login and recovery
The first `fed deploy` interactively asks you to set a Federation administrator ID, password, and confirmation. The password must be at least 12 characters; Federation stores only a salted password digest. After starting `fed web --id fed_x` for the saved connection, enter those credentials on the login page. The browser never receives the remote administration Session Token, which remains in the local BFF process.
An ordinary deployment never changes the administrator. If the password is lost, only an operator with Local host authority or Cloudflare Worker/D1 deployment authority can run:
```bash
fed deploy --admin-reset
```
Non-interactive environments must also pass `--yes`; this only confirms the reset and does not skip credential prompts. The CLI applies recovery directly through a local SQLite transaction or Wrangler-authorized remote D1 access; Workers do not receive recovery environment variables, and plaintext passwords never enter the database. A successful recovery revokes every previous administrator session. Federation exposes no anonymous password-reset API.
`fed deploy` continuously reports the current stage and elapsed time for builds, typechecks, Cloudflare account checks, D1 / Queue / R2 preparation, Worker deployment, health checks, and administrator verification. CI and redirected output receive stable line-based progress logs instead of terminal animation.
Fed has no global active/default connection. Target selection uses mutually exclusive, exact-match `--id ` or `--name `; without a selector, a TTY prompts for this operation only and non-interactive execution fails. Duplicate names prompt in a TTY and fail outside one.
`fed bureau token --id fed_x` opens the interactive token manager for that connection. Selectors can also be placed on the `token` parent command, as in `fed bureau token --id fed_x list`. Choose Issue, or run
`fed bureau token --id fed_x issue `, to enter a purpose and use an Admin Session to ask Federation
to issue the credential. Federation generates the plaintext and stores only its purpose, hash, and
lifecycle state. The plaintext is returned once and configured as `DOWNCITY_BUREAU_TOKEN` on the
Bureau server. Federation and Bureau can run on different servers. A Bureau Token proves machine
identity and cannot issue User Tokens.
## Where to learn more
- [City SDK](/en/city-sdk-docs) — building on City and Federation
- [Payments](/en/payments) — usage, balance, and billing APIs
### Organizations
Source: https://downcity.ai/en/docs/federation/organizations/
`OrganizationsService` owns Organizations, Memberships, Join Requests, and governance roles. Federation is the authority for these relationships.
An Organization stores no product backend address and owns no product resources. Bureau reads its Bureau URL from trusted product configuration and sends the current `user_token` to that Bureau. Bureau verifies the user, checks Membership, and applies product resource permissions.
- Client and backend API: [Organizations Federation API](./organizations-api)
- Product backend integration: [Integrate Organizations into Bureau](./organizations-bureau)
## Install
```ts
import { Federation } from "@downcity/federation";
import { OrganizationsService } from "@downcity/services";
const federation = new Federation({ database });
federation.use(new OrganizationsService({
max_organizations_per_user: 3,
}));
```
The quota counts every active Organization the user owns across Federation. Archiving releases the slot, and ownership transfer moves it to the new Owner.
## Organization scope
Create a Federation-wide Organization:
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: process.env.DOWNCITY_FEDERATION_URL!,
user_token,
});
await embassy.user.service("organizations").action("create").invoke({
name: "Genesis Research",
scope_type: "federation",
});
```
Create an Organization for the current Bureau:
```ts
await embassy.user.service("organizations").action("create").invoke({
name: "Genesis Research",
scope_type: "bureau",
});
```
Members can access a `federation` Organization with a token for any Bureau in the same Federation. A `bureau` Organization requires `user_token.bureau_id` to equal `scope_bureau_id`. Federation derives the Bureau scope from the verified token; clients cannot submit or override it.
Federation-wide does not mean public. The service exposes no public search. Products distribute `organization_id` through invitation links, QR codes, or their own flows.
## Membership
A Membership represents one period in which a User belongs to an Organization. Leaving or removal permanently closes that record. Rejoining creates a new `membership_id`.
```ts
await embassy.user.service("organizations").action("join-requests/create").invoke({
organization_id: "org_01J...",
});
```
Owner, Admin, and Member are Organization governance roles. They do not grant editor, viewer, or repository permissions in a product.
## Call a product Bureau
Bureau sends the same `user_token` to the HTTPS Bureau configured by the product:
```ts
await embassy.user.post("/v1/projects", {
organization_id: "org_01J...",
});
```
Bureau verifies the token with Federation JWKS and calls `membership/get` for the current relationship. Organizations Service issues no `organization_token` and makes no callback to user-controlled URLs.
## Databases and archive
The service supports better-sqlite3, PostgreSQL, and Cloudflare D1 through `context.transaction()`. It contains no database-specific branch.
Archive is terminal. It stops governance writes and releases the Owner quota. Bureau decides what happens to product resources.
### Organizations Federation API
Source: https://downcity.ai/en/docs/federation/organizations-api/
This reference covers Organizations Actions for clients and Bureau. See [Integrate Organizations into Bureau](./organizations-bureau) for product authorization.
## Install
```ts
import { Federation } from "@downcity/federation";
import { OrganizationsService } from "@downcity/services";
const federation = new Federation({ database });
federation.use(new OrganizationsService({
max_organizations_per_user: 3,
}));
```
| Option | Required | Meaning |
| --- | --- | --- |
| `max_organizations_per_user` | yes | Maximum active Organizations a user may own across Federation |
The service supports better-sqlite3, PostgreSQL, and Cloudflare D1 through `context.transaction()`.
## Endpoint and authentication
```text
{federation_origin}/v1/organizations/{action}
```
Every Action requires a Federation `user_token`:
```http
Authorization: Bearer ub_
```
Federation reads `user_id` and `bureau_id` from the verified Token. GET Actions use query parameters; POST Actions use JSON.
## Types
```ts
type Organization = {
organization_id: string;
name: string;
scope_type: "federation" | "bureau";
scope_bureau_id: string;
state: "active" | "archived";
created_by: string;
created_at: string;
updated_at: string;
archived_at: string;
};
type Membership = {
membership_id: string;
organization_id: string;
user_id: string;
role: "owner" | "admin" | "member";
state: "active" | "removed";
created_at: string;
updated_at: string;
removed_at: string;
removed_by: string;
};
type JoinRequest = {
request_id: string;
organization_id: string;
user_id: string;
state: "pending" | "approved" | "rejected" | "canceled";
requested_at: string;
decided_at: string;
decided_by: string;
};
```
For `scope_type = federation`, `scope_bureau_id` is empty. For `scope_type = bureau`, Federation derives `scope_bureau_id` from the creator's verified `user_token.bureau_id`.
## Permissions
| Operation | Owner | Admin | Member |
| --- | --- | --- | --- |
| Read Organization and members | yes | yes | yes |
| Rename | yes | yes | no |
| Decide Join Requests | yes | yes | no |
| Remove Member | yes | yes | no |
| Remove Admin | yes | no | no |
| Assign or revoke Admin | yes | no | no |
| Transfer ownership | yes | no | no |
| Archive | yes | no | no |
| Leave | transfer first | yes | yes |
## Actions
| Method | Action | Authorization | Purpose |
| --- | --- | --- | --- |
| `GET` | `my` | User | List visible Organizations for the caller |
| `GET` | `get` | Member | Read Organization and current Membership |
| `POST` | `create` | User | Create an Organization as Owner |
| `POST` | `update` | Owner/Admin | Rename |
| `POST` | `archive` | Owner | Archive terminally |
| `GET` | `membership/get` | Member | Read current Membership |
| `GET` | `members/list` | Member | List active Memberships |
| `POST` | `members/role` | Owner | Set Admin or Member |
| `POST` | `members/remove` | Owner/Admin | Remove a manageable member |
| `POST` | `members/leave` | Admin/Member | Leave |
| `POST` | `owner/transfer` | Owner | Transfer the unique Owner |
| `POST` | `join-requests/create` | User | Apply to join |
| `POST` | `join-requests/cancel` | Applicant | Cancel a pending request |
| `GET` | `join-requests/list` | Owner/Admin | List pending requests |
| `POST` | `join-requests/decide` | Owner/Admin | Approve or reject |
## Organization Actions
### `GET my`
```http
GET /v1/organizations/my
GET /v1/organizations/my?include_archived=true
```
The default response contains active Organizations only. Each item includes `role`, `membership_id`, and `membership_state`. Federation Organizations are visible across Token Cities; Bureau Organizations require a matching Token Bureau.
### `GET get`
```http
GET /v1/organizations/get?organization_id=org_01J...
```
Requires an active Membership and returns `{ organization, membership }`. Members may read an archived Organization but cannot mutate it.
### `POST create`
Federation-wide:
```json
{ "name": "Genesis Research", "scope_type": "federation" }
```
Current Bureau:
```json
{ "name": "Genesis Research", "scope_type": "bureau" }
```
Returns `{ organization, membership }`, with the caller as the unique Owner. The trimmed name must contain 1–120 characters.
### `POST update`
```json
{ "organization_id": "org_01J...", "name": "New Name" }
```
Owner/Admin only. Scope is immutable after creation.
### `POST archive`
```json
{ "organization_id": "org_01J..." }
```
Owner only and irreversible. Archive stops governance writes and releases the Owner quota. Membership and Join Request history remains.
## Membership Actions
### `GET membership/get`
```http
GET /v1/organizations/membership/get?organization_id=org_01J...
```
Returns `{ organization, membership }`. Bureau may forward the same user Token to this endpoint. Removed users receive `403 NOT_AN_ORGANIZATION_MEMBER`.
### `GET members/list`
```http
GET /v1/organizations/members/list?organization_id=org_01J...
```
Returns active Memberships in `{ "items": Membership[] }`.
### `POST members/role`
```json
{
"organization_id": "org_01J...",
"membership_id": "mem_01J...",
"role": "admin"
}
```
Owner only. `role` accepts `admin` or `member`. Use `owner/transfer` for ownership.
### `POST members/remove`
```json
{ "organization_id": "org_01J...", "membership_id": "mem_01J..." }
```
Owners may remove Admins or Members. Admins may remove Members. The unique Owner cannot be removed.
### `POST members/leave`
```json
{ "organization_id": "org_01J..." }
```
Admins and Members may leave. The Owner transfers ownership first.
### `POST owner/transfer`
```json
{ "organization_id": "org_01J...", "membership_id": "mem_new_owner" }
```
The target must have an active Membership and an available Owner quota. The previous Owner becomes Admin.
## Join Request Actions
### `POST join-requests/create`
```json
{ "organization_id": "org_01J..." }
```
Users apply with a known ID. A duplicate returns the same pending request. Existing members receive `{ state: "joined", organization, membership }`.
### `POST join-requests/cancel`
```json
{ "request_id": "join_01J..." }
```
The applicant may cancel their pending request.
### `GET join-requests/list`
```http
GET /v1/organizations/join-requests/list?organization_id=org_01J...
```
Owner/Admin only. Returns pending requests.
### `POST join-requests/decide`
```json
{ "request_id": "join_01J...", "decision": "approved" }
```
`decision` accepts `approved` or `rejected`. Approval creates a new Member Membership in the same transaction.
## Errors
| HTTP | Code | Meaning |
| --- | --- | --- |
| `400` | `ORGANIZATION_INPUT_INVALID` | Invalid name, ID, role, or decision |
| `400` | `ORGANIZATION_SCOPE_INVALID` | Invalid `scope_type` |
| `401` | `AUTH_REQUIRED` | Missing valid user identity |
| `403` | `ORGANIZATION_BUREAU_MISMATCH` | Token Bureau cannot access the Bureau Organization |
| `403` | `NOT_AN_ORGANIZATION_MEMBER` | No active Membership |
| `403` | `ORGANIZATION_ROLE_DENIED` | Governance role denies the operation |
| `404` | `ORGANIZATION_NOT_FOUND` | Organization does not exist |
| `404` | `ORGANIZATION_MEMBERSHIP_NOT_FOUND` | Membership is absent or inactive |
| `404` | `JOIN_REQUEST_NOT_FOUND` | Join Request is absent or unavailable |
| `409` | `ORGANIZATION_LIMIT_REACHED` | Owner quota is full |
| `409` | `OWNER_TRANSFER_REQUIRED` | Transfer ownership first |
| `410` | `ORGANIZATION_ARCHIVED` | Organization is archived |
Branch on `error.code`, not the message text.
### Integrate Organizations into Bureau
Source: https://downcity.ai/en/docs/federation/organizations-bureau/
Bureau is the trusted product backend. Bureau sends the Federation `user_token` to the HTTPS Bureau configured by the product. Bureau verifies the user and Bureau before checking Organization Membership.
## Authorization order
```text
Bureau
-> user_token + product request
-> Bureau verifies Federation JWT and bureau_id
-> Bureau reads organization_id from the resource record
-> Bureau checks Federation Membership
-> Bureau enforces product roles and resource permissions
```
A valid Membership means that the user belongs to the Organization. It does not grant access to every product resource owned by that Organization.
## Verify `user_token`
Bureau uses its configured Federation issuer and JWKS to validate:
- JWT algorithm and signature;
- `iss` and `aud`;
- `exp` and `nbf`;
- `user_id` and `bureau_id`;
- whether `bureau_id` is allowed by the current product.
Do not log the Authorization header or forward the token to services outside product configuration.
## Check Membership
Bureau can forward the same user Token to Federation:
```http
GET /v1/organizations/membership/get?organization_id=org_01J...
Authorization: Bearer ub_...
```
A successful response contains the Organization and active Membership. Federation returns `403 NOT_AN_ORGANIZATION_MEMBER` after the user leaves or is removed.
## Verify resource ownership
Product resource tables store `organization_id`:
```sql
CREATE TABLE projects (
project_id TEXT PRIMARY KEY,
organization_id TEXT NOT NULL,
name TEXT NOT NULL
);
```
For `/v1/projects/:project_id`, Bureau reads the Project first and checks Membership against `project.organization_id`. Never use a client-supplied Organization ID as the resource authority.
## Product permissions
Bureau applies its own permission model after Membership succeeds:
```text
Federation Membership
-> user belongs to Organization
Product Role / ACL
-> user may read, edit, or manage a resource
```
Organization Owner, Admin, and Member govern the Federation relationship only. Bureau stores product roles such as editor, viewer, or billing_admin.
## Cache and revocation
Check Federation online for writes, administration, and sensitive reads that require immediate revocation. Low-risk reads may use a short-lived cache; the maximum revocation delay equals the cache TTL.
At minimum, include Federation issuer, `user_id`, and `organization_id` in the cache key. Bureau owns the TTL decision. Organizations Service maintains no cross-server revocation Outbox.
## Checklist
- [ ] Read the Bureau URL from trusted product configuration
- [ ] Receive `user_token` only over HTTPS
- [ ] Verify issuer, audience, signature, time, and `bureau_id`
- [ ] Do not log or forward the Authorization header
- [ ] Read `organization_id` from the resource record
- [ ] Check Membership online for sensitive operations
- [ ] Apply product permissions after Membership
### Model Provider
Source: https://downcity.ai/en/docs/federation/model-provider/
The Federation AIService abstracts over multiple AI model providers. A model provider is any backend that can serve model requests — OpenAI, Anthropic, Google, or a local inference server.
## Registration
Providers register with City by exposing:
- Available model IDs
- Capability flags (streaming, tool use, vision, etc.)
- Authentication requirements
## Unified API
Regardless of the backend, the Federation AIService exposes a unified API to Agents. This means:
- Agents do not need provider-specific code
- Switching providers is a configuration change, not a code change
- New providers can be added without modifying Agents
## Capability discovery
When an Agent binds to a model ID, City reports:
- Whether the model supports streaming
- Whether the model supports tool use
- Maximum context length
- Pricing per token
Continue with:
- [Service](/en/docs/federation/service)
- [Action](/en/docs/federation/action)
### Local Proxy
Source: https://downcity.ai/en/docs/federation/local-proxy/
Use the Downcity local proxy skill when you want a local Federation service that exposes Codex or Claude Code model access without registering anything into an existing Fed server.
The generated project runs:
- CLIProxyAPI on `127.0.0.1:8317`
- Downcity local Federation on `127.0.0.1:3000`
- Model endpoints under `/v1/ai/models` and `/v1/ai/chat/completions`
## Install the skill
Run the following command from a joint workspace checkout containing the private repository.
Install the skill with the Vercel Labs `skills` CLI:
```bash
npx skills add ./private/apps/homepage/resources/downcity-local-proxy-skill \
--skill downcity-local-proxy \
--agent codex \
--global \
--yes
```
## Prompt Codex
After installing, ask Codex:
```text
Use downcity-local-proxy to create ./downcity/local-proxy with Codex and Claude Code enabled, then install dependencies and start the local Federation service.
```
## Start manually
The skill creates a standalone project. From the generated directory:
```bash
cd ./downcity/local-proxy
pnpm install
pnpm start --codex
pnpm start --claude-code
pnpm start --codex --claude-code
```
Use `--login` when CLIProxyAPI needs OAuth setup or refresh:
```bash
pnpm start --codex --login
pnpm start --claude-code --login
```
The local proxy writes runtime files under `.downcity/` inside the generated project. It does not modify global Downcity CLI state or register itself with an existing Fed server.
Continue with:
- [Model Provider](/en/docs/federation/model-provider)
- [Service](/en/docs/federation/service)
### Service
Source: https://downcity.ai/en/docs/federation/service/
A **Service** is a long-running backend capability that Agents can call. Unlike tools (which run inside the Agent process), Services run as independent backends and are accessed via the City network.
## Examples
- Knowledge base (semantic search over documents)
- Search engine (web search, internal search)
- Database (structured data storage and query)
- File store (document upload and retrieval)
## Registration
Services register with City by:
1. Declaring their API schema
2. Exposing health and capability endpoints
3. Receiving a service ID
## Discovery
Agents discover Services through City. When an Agent needs a capability, it asks City for available Services, then routes requests to the appropriate one.
Continue with:
- [Model Provider](/en/docs/federation/model-provider)
- [Action](/en/docs/federation/action)
### Action
Source: https://downcity.ai/en/docs/federation/action/
An **Action** is a discrete operation that an Agent can invoke. It is the unit of work in the Service/Action layer. Actions are exposed by Services and can be composed into workflows.
## Examples
- `send_email` — send an email to a recipient
- `query_database` — run a SQL query
- `call_api` — invoke an external HTTP API
- `upload_file` — store a file in the file store
## Schema
Every Action declares:
- Input schema (parameters it accepts)
- Output schema (what it returns)
- Error conditions
- Required permissions
## Invocation
Agents invoke Actions through the City layer. The City routes the request to the Service that owns the Action, then returns the result to the Agent.
## Composition
Actions can be composed into higher-level workflows. For example, a "onboard user" workflow might invoke `create_account`, `send_welcome_email`, and `add_to_crm` in sequence.
Continue with:
- [Model Provider](/en/docs/federation/model-provider)
- [Service](/en/docs/federation/service)
### Routing
Source: https://downcity.ai/en/docs/federation/routing/
The Federation AIService handles request routing and failover across model providers and Services. This ensures Agents stay available even when individual backends are down.
## Model routing
When an Agent sends a model request:
1. The Federation AIService looks up the model ID
2. It selects the provider with the best health and lowest latency
3. It forwards the request
4. If the provider fails, it retries with the next available provider
## Service routing
When an Agent invokes an Action:
1. City resolves the Action to the Service that owns it
2. It checks the Service's health and load
3. It routes the request to the best instance
4. If the Service is unavailable, it returns an error or queues the request
## Failover
- Provider health is monitored continuously
- Failed requests are retried with exponential backoff
- Circuit breakers prevent cascading failures
- Load balancing distributes traffic across healthy instances
Continue with:
- [Model Provider](/en/docs/federation/model-provider)
- [Service](/en/docs/federation/service)
### Architecture
Source: https://downcity.ai/en/docs/concepts/architecture/
Current Downcity is best understood through five layers:
1. `console`
2. `agent`
3. `execution context`
4. `session`
5. `power runtime`
## Layers
### `console`
- global control plane
- process registry
- city-level configuration and inspection
### `agent`
- owns one project runtime
- holds model access, session store, power registry, and runtime host state
### `execution context`
- shared capability surface exposed during execution
- the place powers read stable runtime abilities
### `session`
- owns one execution thread and its prompt/run state
- the unit that actually runs model + tool flow
### `power runtime`
- all capability modules are modeled as powers
- some are local and action-first
- some are managed and lifecycle-owned
## Managed vs local powers
### Local powers
- usually attached directly to one SDK `Agent`
- examples: `skill`, `web`, `sound`
### Managed powers
- runtime-owned modules that start and stop with one target agent
- examples: `chat`, `task`, `memory`, `shell`, `schedule`
## Main takeaway
Do not use the old split-layer language for the current system.
The current model is:
- session executes
- powers expose capability
- managed powers own long-lived runtime modules
### Project Logic Overview
Source: https://downcity.ai/en/docs/concepts/project-logic-overview/
Downcity is easiest to understand from the product problem first: AI builders should not rebuild the same agent backend for every product, workflow, or customer demo.
The core relationship is:
- product surfaces own the user experience
- agents execute work inside explicit runtime boundaries
- Downcity runtime services own repeated infrastructure such as models, env, auth, service routing, usage, balance, and payment
- Console, Chrome Extension, SDKs, and UI components expose that runtime to builders and teams
## Runtime nouns
- `downcity`: the overall runtime and CLI surface
- `console`: global control plane
- `agent`: one project runtime
- `session`: one execution thread
- `power`: one capability boundary
- `city`: the current package/runtime name for City infrastructure
## The shortest model
- products create the experience
- agents run the work
- sessions execute turns
- powers expose capabilities
- City keeps repeated backend concerns out of every product
## Power families
### Local powers
- attached directly to one SDK `Agent`
- usually action-first or hook-oriented
### Managed powers
- owned by one target agent runtime
- may hold lifecycle-owned runtime state
## Why this matters
When reading current code or docs, start with the product boundary:
- if you need product operation, look at `downcity`, `console`, and product docs
- if you need execution ownership, look at `agent` and `session`
- if you need capability ownership, look at `power`
- if you need shared backend ownership, look at the City SDK and services docs
### Security and Permissions Overview
Source: https://downcity.ai/en/docs/security/overview/
Downcity security has three layers:
1. Agent isolation: one running agent is bound to one `projectRoot`.
2. Chat Access: per-Agent grants decide which external Chat users can send messages into the Agent.
3. Local configuration: model, Workspace, Agent, and Power configuration is stored on the local machine and primarily isolated by file permissions.
## What to watch first
1. Avoid stale `DC_CITY_HOST/DC_CITY_PORT` in your shell, or requests may hit the wrong agent.
2. New users cannot enter an Agent by default, so review pending Access Requests after enabling a channel.
3. Local configuration is plaintext. Do not copy `~/.downcity`, Agent configuration, or Power configuration to untrusted locations.
## Recommended reading
1. [API Authentication](/en/docs/security/api-authentication)
2. [Permissions](/en/docs/security/permissions)
3. [Data Storage and Permissions](/en/docs/security/data-security)
4. [Invocation Routing and Isolation](/en/docs/concepts/invocation-routing-and-isolation)
### API Authentication
Source: https://downcity.ai/en/docs/security/api-authentication/
Downcity now uses a single external auth model:
- no username/password sign-in
- no browser session layer
- all external auth goes through Bearer tokens
- tokens are managed by the local CLI on the same machine
The currently exposed endpoints are:
- `GET /api/auth/status`
- `GET /api/auth/me`
- `GET /api/auth/token/list`
- `POST /api/auth/token/create`
- `POST /api/auth/token/delete`
## Token ownership
Tokens are created and stored on the same local machine that owns the runtime. A token name is only for human identification and management. It does not represent a different token type or channel scope.
## Use the token
Send the token through the `Authorization` header:
If the token is valid, the endpoint returns the current subject, roles, and permissions.
## Manage tokens
Token creation, listing, and deletion are local-machine operations. HTTP token-management endpoints require an existing Bearer token, so external callers cannot silently mint authority without first holding authority.
## `DC_AUTH_TOKEN`
Main rule first:
- only external HTTP calls need a Bearer token
- local managed commands now call the local agent daemon over HTTP by default
For direct API usage, the important rule is:
- external calls always authenticate through `Authorization: Bearer `
Inside the CLI/runtime, the only auth env var most users need is:
| Variable | Intended For | Purpose |
| --- | --- | --- |
| `DC_AUTH_TOKEN` | users, scripts, CI | explicitly choose which token a CLI/API invocation should use |
HTTP calls that need auth use this resolution order:
1. `--token`
2. `DC_AUTH_TOKEN`
So:
- `DC_AUTH_TOKEN` is the explicit override
- protected HTTP calls normalize `DC_AUTH_TOKEN` into the Bearer header
If you see `Missing bearer token`:
- do not start by suspecting `sessionId`
- first confirm that the target HTTP endpoint is actually protected
- then check whether the current process has any valid token source
- if this happens inside an agent/Bash/ACP subprocess, first check whether the command should receive an explicit token
Concrete token workflows live in [Downcity CLI product docs](/en/docs/reference/cli).
## Current scope
The current model is intentionally token-only:
- username/password login removed
- `bootstrap-admin` removed
- `login` removed
- `password/update` removed
- Console UI, Chrome extension, and external scripts all use explicitly minted Bearer tokens
Future integrations will stay on this Bearer token model instead of reintroducing a separate login session layer.
### Chat Access
Source: https://downcity.ai/en/docs/security/permissions/
Chat Access is an admission capability of the Messenger Power. It answers one question: may a direct or group message from an external Chat user enter a specific Agent?
It is not an Agent Core permission system or a general Role/Permission model. After admission, the Messenger Power passes the message to the Agent without propagating roles or permissions into Sessions or other Powers.
## Core rules
- Default deny: without an explicit `allow` grant, the message does not enter the Agent.
- Per-Agent isolation: approval for Agent A does not grant access to Agent B.
- Per-account isolation: identity uses `channel + issuer + subject_id`, so the same user contacting two bots has two principals.
- Explicit scopes: persisted grants are only `direct` and `group`; `all` in management commands expands to two grants.
- `deny` differs from `revoke`: denial prevents new requests, while revocation lets the user request access again.
## Approval flow
When an unapproved user sends a direct message, the Messenger Power creates or reuses a pending request and returns a command like:
```bash
city power action chat access-approve assistant --input '{"request_id":"req_xxx"}' --token
```
Administrators can inspect requests first:
```bash
city power action chat access-snapshot assistant --input '{}' --token
```
Unapproved group messages are silent by default, but their pending requests appear in the same management list.
## Storage
Each Agent stores its own data at:
```text
~/.downcity/agents//powers/messenger/messenger/access.db
```
The Chat Access database contains principals, requests, allow/deny grants, and audit events. It does not contain bot tokens, app secrets, or message bodies. Messenger channel credentials belong to the unique plaintext configuration in `~/.downcity/powers/messenger/config.toml`; the Messenger Config UI never returns their plaintext values when reading configuration.
## Difference from City Auth
An Agent Token protects the HTTP control plane. Each token belongs to one Agent and has full access to that Agent API; it contains no User, Role, or Permission. Chat Access decides whether an external Telegram, Feishu, or QQ user may send messages to a specific Agent. Their data, identities, and decision paths are separate.
## Related docs
- [CLI Commands](/en/docs/cli/commands)
- [Messenger Power](/en/docs/power/messenger)
- [`.downcity` Directory](/en/docs/reference/dot-downcity)
### Data Storage and Permissions
Source: https://downcity.ai/en/docs/security/data-security/
Local CLI and Desktop state use plaintext SQLite/JSON files:
1. Workspace indexes, platform settings, and local tokens: `~/.downcity/downcity.db`
2. Agent definitions and identity instructions: `~/.downcity/agents//agent.json` and `SOUL.md`
3. Power definitions and unique configuration: `~/.downcity/powers//power.json` and `config.toml`
## File Permissions and Boundaries
Database files, Agent configuration directories, and Power configuration files are restricted to the current user by default (`0600` for files and `0700` for directories). This is not encrypted storage: a process that can read the local user's files can also read these configurations.
`city env` is an explicit file-based configuration feature. Global Env is stored in plaintext at
`~/.downcity/.env`, and Workspace Env is stored in plaintext in the project `.env`. The Global file
is restricted to the current user, and project `.env` is added to `.gitignore` by default. Use the
launch environment or a secret manager when stronger secret protection is required.
## Best practices
1. Never commit `~/.downcity` or local configuration files.
2. Never commit Workspace `.env`, and keep `~/.downcity/.env` accessible only to your user account.
3. Use process environment variables or an operating-system secret manager when stronger protection is required.
## Related docs
- [Model binding](/en/docs/configuration/model)
- [Model Configuration](/en/docs/configuration/model)
### CLI
Source: https://downcity.ai/en/docs/cli/overview/
The Downcity package installs two independent tools:
- `city` (alias `downcity`) is the local City container for Agents, powers, environment variables, and Federation connections.
- `fed` (alias `downfed`) is the Federation Server Manager. Its TUI manages registered servers, `fed web` starts the local Web control plane, and project commands read `federation.toml` from the current project. Federation project configuration uses TOML only; JSON configuration is not supported.
For local deployments, omitting `deployment.port` uses the fixed default port `12314`. Set `port` in `[deployment]` to override it. If the selected port is occupied, deployment fails; the CLI does not scan for another port or infer one from deployment history.
## City data model
Agents and Workspaces are independent global entities. An Agent is identified by `agent_id`, keeps its structured definition in `~/.downcity/agents//agent.json`, and keeps its stable identity instructions in `SOUL.md`. A Workspace is identified by `workspace_id` and points to a project directory. An Agent can enter multiple Workspaces; neither entity stores a persistent binding to the other. CLI and Desktop own separate City instances but share the same user-level files and Workspace index.
Federation Admin configuration and Embassy User Sessions also live in `~/.downcity/downcity.db`. On upgrade, administration configuration in the legacy `~/.downcity/federation.db` is migrated once. The old file remains available for manual recovery but is no longer read at runtime.
Each Power uses its stable ID as `~/.downcity/powers//`, with one plaintext configuration in `config.toml`. A third-party installation contains one `power.json`, the `package.json` that establishes its ESM boundary, and optional self-contained `main` and `renderer` entries declared by the manifest—not source or build configuration. City provides every registered Power and the same configuration to every Agent; `agent.json` stores no Power reference. `downcity.db` stores Workspace indexes, tokens, and platform state, not Agent or Power configuration.
## City commands
| Command | Purpose |
|---|---|
| `city agent` | Manage global Agents |
| `city power` | Manage Power artifacts, unique configuration, and actions |
| `city env` | Manage environment variables injected by City |
| `city federation` | Manage Federation connections |
Automation can override the current Embassy user identity with `DOWNCITY_FEDERATION_URL` and `DOWNCITY_USER_TOKEN`. The legacy `DOWNCITY_CITY_URL`, `DOWNCITY_CITY_USER_TOKEN`, `CITY_URL`, and `CITY_USER_TOKEN` variables are no longer parsed.
`city init`, `city update`, and `city config` are no longer provided. Upgrade globally with `npm i -g downcity@latest`.
Every command that operates on one Agent targets an `agent_id`. If omitted in a TTY, City opens the global Agent selector. Non-interactive calls fail with `Agent ID is required`; the current directory is never used for inference.
## Platform support
The CLI architecture is cross-platform. macOS and Linux are stable targets; Windows adapters are currently preview quality.
Continue with [CLI commands](/en/docs/cli/commands).
### CLI Commands
Source: https://downcity.ai/en/docs/cli/commands/
## City lifecycle
```bash
city on # Start the single CLI City daemon
city on --port 5314 --rpc-port 15314
city status
city restart
city off
city reset # Confirm and reset the local configuration database
city reset --yes # Skip confirmation
```
The CLI City uses one HTTP port and one native TCP RPC port. Both protocols route all Agents by `agent_id`.
`city reset` first stops the CLI City daemon, then removes `downcity.db`, `downcity.db-wal`, and `downcity.db-shm`. It preserves `.env`, Agent/Power configuration, and Session files inside Workspaces.
## Agent
```bash
city # Open the Agent list directly
city agent # Open the same Agent list
city agent create [path] # No path: current directory or native folder picker
city agent list
city agent model [agent_id]
city agent chat [agent_id]
```
The bare `city` command opens the Agent list directly. It does not show Agent runtime status. `city agent list` prints every Agent as `name · agent_id`. Federation, global Powers, language, and command help appear in a Settings group at the end of the same list.
Agents assembled by City enable the `ask_user` tool by default.
Selecting an Agent in the `city agent` panel opens its most recent conversation and enters that Session's Workspace. When the Agent has no history yet, Chat opens in the current Workspace and creates a new Session. The model can present text, single-select, or multi-select
questions when key information is missing. The CLI submits the complete answer set
to the current Session and continues the same Turn. Press Esc to stop that Turn.
For passwords, API keys, and tokens, `ask_user` uses `type: "secret"` with a snake_case
`name`. Local Sessions collect masked input, then ask you to confirm the private value count,
names, and replacement of existing same-name values. The model receives only a Session private
reference. Values are held in Session memory and are lost after release or restart. CLI transports
without the dedicated private submission method refuse private forms before collecting input;
use Desktop or a local Session. Do not paste credentials into ordinary chat or text questions.
Agents and Workspaces are registered independently. An Agent enters a selected Workspace for each execution and stores no persistent Workspace binding. Agents have no independent started state. `city agent chat --session-id ` must reference an existing Session and enters that Session's Workspace; `--workspace ` keeps Chat in that Workspace by limiting session lookup to it, requiring it to match the Workspace of a selected `--session-id` Session, and creating new Sessions there. In Chat, use `/new` to create a Session, `/session` to select an existing Session or create one, and `/config` to open Agent configuration. Configuration returns to the same conversation. Chat uses RPC while City is running; scriptable one-shot calls can use the local assembly path while City is off.
Use the slash command to open the system file picker and attach local files to the next message:
```text
/attach
```
`/file` is an alias. On Unix, `Ctrl-V` (or `Alt-V` on Windows) also tries to paste clipboard images or files first, and falls back to normal text paste when no supported attachment is available.
Approval requests are handled by the dedicated interaction panel; `/approve` and `/deny` are no longer slash commands.
## City Tokens
City owns connection credentials. Grant access to selected Agent IDs, or explicitly allow all existing and future Agents. `city` is the executable; `downcity` is an alias, without an additional `city` subcommand.
```bash
city token
city token create
city token list
city token create --name chrome --agents researcher,programmer --never-expires
city token create --name automation --all-agents --expires-at 2027-01-01T00:00:00Z
city token update --agents researcher
city token delete
```
The interactive menu supports creation, summary viewing, editing and revocation. Creation requires a name, scope and expiry policy. Missing options are prompted in a terminal and rejected in noninteractive execution. Interactive creation includes Agent multiselect, 30/90 days, no expiry or a custom date, followed by confirmation. Omit the ID on update/delete to select a record. Complete options run directly; use `--json` for scripts.
Plaintext is shown once at creation and never appears in summary queries. Enter it directly in Chrome settings. Lost credentials must be replaced. Revocation or scope reduction rejects new requests and closes affected HTTP streams within the approximately one-second authorization check interval. Cancellation cannot undo completed external effects.
The old `city agent token` command and Agent Tokens are no longer accepted. Issue a new credential with `city token create`; old records are not automatically migrated or granted broader access. Token management remains local and is not granted to remote connection credentials.
## Powers
`city power list` shows each Power title, stable ID, purpose, source, and whether it provides Config.
```bash
city power list
city power install
city power update
city power uninstall
city power inspect
city power config
city power config --set '{"key":"value"}'
city power action [agent_id] --input '{"key":"value"}' --token
```
A third-party source directory defines exactly one Power. Its `power.json` declares `schema_version: 1`, a globally unique `id`, a version, a required relative `readme` path to a `.md` file, and optional `main` and `renderer` entries. `main` is a self-contained unified City Power ESM. The `renderer` object declares a single-file ESM entry and static `sidebar`, `mainview`, and `config` capabilities; Sidebar and Mainview must be paired. At least one of the two runtime entries is required. `package.json` must declare `"type": "module"`. The installed directory keeps only declared artifacts, documentation, an optional icon, and local `config.toml`. Installation never runs dependencies, build scripts, or any third-party entry.
A Power that declares Config stores one configuration in `powers//config.toml`. The Power
owns its structure, validation, Secret projection, and Config UI. CLI `config --set` only replaces a
complete JSON object explicitly; it does not generate a generic form or print credential values. Without
`--set`, it reports only whether Config exists and its field names.
City automatically provides every registered Power to every Agent; `agent.json` stores neither Power
references nor configuration. A Power models its own account collection and selection rules when it
needs multiple accounts. After Config is saved, the Power refreshes affected long-lived resources.
The CLI, Agent Power tools, HTTP, and scheduled jobs all invoke Power Actions. There is no `power command`, and Chat is not a top-level CLI special case.
## Env and Federation
```bash
city env # open the Env TUI
city env list --global
city env list --agent
city env set --global
city env set --agent
city env delete --global
city env delete --agent
city federation
```
Global Env is stored in `~/.downcity/.env`; Workspace Env is stored in `.env` at the project root.
You can also use “Configure Env” in `city agent` to select an Agent's Workspace. After a change, the CLI City updates affected
runtime Agents and Workspace broadcasts the new snapshot to existing Sessions.
Agents not held by that City receive the configuration the next time a City assembles them.
Agents running in the same Workspace share one project `.env`. Runtime precedence is Global `.env`,
then Workspace `.env`, then explicit process environment variables. `list` never prints plaintext
values; `copy` requires an explicit local CLI invocation.
Federation user requests go through Embassy. Interactive sessions are stored in
`~/.downcity/downcity.db`; automation can explicitly override the current session with
`DOWNCITY_FEDERATION_URL` and `DOWNCITY_USER_TOKEN`. These identity variables are never injected
from Global `.env` into Workspace processes.
## Fed
```bash
fed # Federation Server manager TUI
fed web --id fed_x # local Web admin UI for this operation's Federation
fed web --name my-fed --no-open --port 43128
fed server add
fed server --id fed_x
fed manage --id fed_x
fed server manage --id fed_x
fed bureau token --id fed_x # open the Bureau Token manager TUI
fed bureau token --id fed_x issue
fed bureau token --id fed_x list
fed bureau token --id fed_x revoke
fed query GET /health --id fed_x
fed status --id fed_x
fed logs --id fed_x
fed stop --id fed_x
fed restart --id fed_x
fed clean --id fed_x --dry-run # preview only
fed clean --name my-fed # preview, then interactive confirmation
fed clean --id fed_x --yes # explicit non-interactive confirmation
fed backup --id fed_x # online SQLite snapshot, includes WAL
fed restore --id fed_x --path /path/to/backup_id --dry-run
fed restore --id fed_x --path /path/to/backup_id --yes
fed create # --path defaults to .
fed create --path ./my-fed
fed deploy # --path defaults to .
fed deploy --path ./my-fed
```
`fed create` and `fed deploy` accept an explicit `--path `, defaulting to `.`; positional path arguments are not accepted.
Fed has no global active/default Federation and does not store `active_server_url`. `stop`, `restart`, `clean`, `backup`, `restore`, `status`, `logs`, `query`, `web`, `server`, `manage`, and `server manage` accept mutually exclusive `--id ` or `--name ` selectors. Both match exactly. Without a selector, a TTY opens a list for this operation only; non-interactive execution fails with a missing-selector error. Duplicate names require a further selection in a TTY and fail outside a TTY. Lists have no global-current star marker. `fed manage --id fed_x` opens the target's management workspace directly, with no action positional argument; `fed server manage` supports the same selectors.
Bureau Token commands follow the same selection rules. Selectors can also appear on the `token` parent command, as in `fed bureau token --id fed_x list`; issue/list/revoke retain their existing command structure.
`fed status` works with any saved connection and shows the registry record and a live `/health` probe. Local instances also report launchd/systemd manager status separately. The record, system service state, and health probe are independent facts. A local release is healthy only when `ok: true` and its `fed_id`, `release_id`, and `instance_id` all match the managed instance. `fed logs`, `fed stop`, and `fed restart` work only with CLI-managed local instances. Logs come from the existing `service.log`. `stop` disables automatic startup and stops the service. The stopped state survives system restarts until an explicit `fed deploy` or `fed restart`; those operations restore the automatic startup policy from persisted configuration. Restart uses only the installed release and persisted runtime configuration, without reading or building source, and works after the original project is deleted. An explicitly selected database keeps its absolute path; preserve that file when deleting the project. Remove connection in the management UI only removes the saved connection; it does not stop the service.
`fed clean` only cleans local releases of registered Feds. Without either mutually exclusive `--id` / `--name` selector, a TTY opens a list for this operation only; non-TTY execution fails. It previews release IDs, sizes, and deletion or retention reasons before confirmation. `--dry-run` only previews. Non-interactive deletion requires explicit `--yes` and still applies all protection checks. The default policy always retains the 3 most recent successful releases; there is no `--keep` option.
Releases referenced by `current.json`, the registry, service `launch.json` (including pending recovery startup), or in-progress attempts are protected, as are candidates whose cleanup could not be confirmed. Unknown or damaged releases and those without trustworthy deployment records are retained with an explanation. Protection-information errors, including an unverifiable runner, refuse cleaning outright. After target selection, the same Fed lock covers preview, confirmation, and deletion to prevent concurrent cutovers. Failed artifacts are deleted only through manual `fed clean`; the CLI does not automatically clean releases. `clean` never deletes data, config, logs, staging, or deployment history. Deployment attempts are stored at `~/.downcity/federation/deployments//attempts/.json` to identify successful and failed history, which remains after release deletion. See [Clean Local Releases](/en/city-sdk-docs/packages/cli/quickstart#clean-local-releases).
`fed backup` creates a consistent online SQLite snapshot for a registered local release. `fed restore --path ` requires explicit persistent stop facts, verifies ownership, SHA-256 and SQLite integrity, saves the current database before confirmation, and atomically replaces it without starting the service. `--dry-run` performs read-only preflight; non-interactive replacement requires `--yes`. Backup files use `0600` and can contain accounts, sessions and credentials; keep them out of Git and release artifacts. Restore does not switch application versions or guarantee schema compatibility. See [SQLite Backup and Restore](/en/city-sdk-docs/packages/cli/backup-and-restore).
See [Independent Local Node Releases](/en/city-sdk-docs/packages/cli/quickstart#independent-local-node-releases) for installation paths, runtime configuration, Node requirements, and dry-run boundaries. Local targets retain `deployment.scripts.build` and reject `deployment.scripts.deploy`.
Local services use macOS user-level launchd or Linux user-level systemd. The `[deployment.process]` table in `federation.toml` supports `auto_start = false` (default) and `restart_on_failure = true` (default). Only booleans are accepted; unknown fields are rejected, and Workers projects cannot declare this table. Recovery uses 10-second intervals with at most 5 attempts within 60 seconds. Only explicit `auto_start = true` persists a definition in macOS `~/Library/LaunchAgents` or enables the Linux user service in `default.target.wants`. macOS starts after user login; Linux requires an available user manager. The CLI does not enable linger or guarantee Linux startup at boot. System service definitions contain no secrets; runtime configuration is stored separately. See [CLI Quickstart](/en/city-sdk-docs/packages/cli/quickstart) for configuration examples.
`fed web` starts the local control plane at `http://127.0.0.1:43128` by default for the
Federation selected by `--id` / `--name` or the one-time TTY list. The local CLI process keeps
the administrator session token; it is never sent to the browser. To keep the administrator control plane off the
network, the command only listens on `127.0.0.1`, `localhost`, or `::1`. The UI includes the
Dashboard, users, Bureaus, models, Env, Credits, Usage, payments, the Service catalog, and a
debugger. Analytics are organized into overview, activity, consumption, retention, quality, and
per-user detail views.
The Usage Dashboard uses the browser's IANA timezone. DAU counts unique users with at least one
AI Usage record today; WAU and MAU use rolling 7-day and 30-day windows. The user-usage view lists
all registered users, including users with zero usage. It defaults to descending Total Tokens—the
same metric as the overview's token-consumption ranking—and also supports sorting by calls, Credits,
P95 duration, and last activity. Each row includes input, output, and total tokens, success
rate, top model, duration, and applied Credits consumption. Charts cover DAU/WAU/MAU, local-hour
activity, stacked token composition, model/action distribution, outcomes, latency, and
D1/D3/D7/D14/D30 cohort retention.
### Project Init
Source: https://downcity.ai/en/docs/cli/init/
`city agent create` registers the Workspace independently and creates the Agent's user-level `agent.json` and `SOUL.md`. It does not generate an Agent declaration inside the Workspace or persist an Agent-Workspace binding.
```bash
city agent create
```
Without a path, the interactive flow lets you use the current directory or open the operating system's native folder picker. Pass a relative or absolute path to skip that choice:
```bash
city agent create .
city agent create ./my-project
city agent create /absolute/path/to/my-project
```
Generated structure:
```text
my-project/
├── .env
├── .agents/
│ └── skills/
└── .downcity/
```
The Agent definition is written to `~/.downcity/agents//agent.json` with its `SOUL.md`; Workspace registration remains in `downcity.db`. Project `.env` overrides Global Env from `~/.downcity/.env`; explicit process environment variables have the highest priority.
```bash
# Allow replacing an existing Agent file definition
city agent create ./my-project --force
```
After initialization, add project Skills under `.agents/skills`, inspect the generated `agent_id` with `city agent list`, then run `city agent chat ` directly or use `city on` for the long-running City host.
Continue with:
- [Project Structure](/en/docs/cli/project)
### Project Structure
Source: https://downcity.ai/en/docs/cli/project/
Agent definitions, Power configuration, and runtime data use user-level files. A project directory is only a Workspace containing project env, Skills, and business source files.
## Directory layout
```text
my-project/
├── .env # project environment variables
├── .agents/
│ └── skills/ # user-managed, versioned Skills
└── src/ # application code (optional)
```
## Global config
The user-level configuration layout is:
```text
~/.downcity/
├── agents//
│ ├── agent.json
│ ├── SOUL.md
│ └── sessions/
│ ├── /
│ ├── archived-sessions/
│ └── logs/
├── powers//config.toml
├── runtimes/city/
└── downcity.db
```
`downcity.db` stores Workspace IDs and paths, tokens, and platform state. It does not store Agent definitions, Power configuration, or Agent-to-Workspace bindings. CLI and Desktop read the same files and database.
`agent_id` and `workspace_id` are independent global identities. A Session receives a Workspace only for a concrete execution. CLI City daemon state lives in `~/.downcity/runtimes/city/`; Sessions live under `~/.downcity/agents//sessions/`. A Session's `meta.json` records `workspace_id` only when a Workspace was supplied.
## Project assets
Global Env is stored separately in `~/.downcity/.env`. Project `.env` overrides Global Env, while explicit process environment variables have the highest priority. Project `.env` is added to `.gitignore` by default. `.agents/skills` is the only user-managed Agent capability asset intended for version control.
## Runtime data
Downcity does not create `/.downcity/`. Agent runtime data is centralized under the City-provided storage scope `agents//`; without a City, it remains in memory. Power-owned data uses the Agent-level scope exposed through PowerContext.
Continue with:
- [Project Init](/en/docs/cli/init)
- [Agent SDK](/en/docs/agent/sdk)
### Agent CLI
Source: https://downcity.ai/en/docs/cli/cli/
The `city` CLI is a local City host. It reads Agent and Power configuration, constructs Agents, Workspaces, and one instance of each Power separately, then lets City own their composition and long-running lifecycle.
## Project initialization
```bash
city agent create
```
With no path, choose the current directory or another folder through the native system picker. Relative and absolute path arguments are also supported, for example `city agent create .` and `city agent create ./my-project`.
This generates:
- `.agents/skills/`
- `.downcity/`
- `.env`
- Agent config in the CLI global DB
## Project directory structure
```text
my-project/
├── .env
├── .agents/skills/
├── .downcity/ # runtime data only
└── your application code
```
## Key commands
- `city` — open the Agent list; Federation and global Power actions are in its Settings group
- `city on` — start the CLI City and restore all bound Agents
- `city status` — inspect City, HTTP/RPC ports, and configured Agents
- `city restart` — restart City and reload configuration
- `city off` — stop the CLI City
- `city agent chat [agent_id]` — chat with an Agent even while City is off
## Chat TUI security policy
After selecting an Agent and entering its most recent conversation, use `/security` to choose the current Session security policy:
- `Default` — maps to the Session `ask` mode; every host Shell action requires explicit approval.
- `Always Allow` — maps to `always-allow`; future host Shell actions in the current Session are approved automatically.
The active policy appears in the Chat header. A policy change affects only future Shell requests in the current Session; an already pending request still requires an explicit response. `Always Allow` does not bypass dangerous-command rejection, Workspace boundaries, or other runtime safety checks.
## What the CLI does
1. Reads agent config from the CLI global DB
2. Resolves `execution.modelId` through the connected Federation AIService
3. Passes the resolved config to `new Agent(...)`
4. Reads configuration through repositories, creates Agents explicitly, and registers them with `new City(agents)`
5. Exposes Agents by `agent_id` over one HTTP port and one RPC port
## CLI vs SDK
The CLI is for day-to-day project management. The SDK is for embedding agent behavior into your own applications. Both use the same execution core.
Continue with:
- [Agent SDK](/en/docs/agent/sdk)
- [Agent Lifecycle](/en/docs/agent/lifecycle)
### CLI Commands
Source: https://downcity.ai/en/docs/reference/cli/
Downcity docs explain the design model, runtime boundaries, and configuration semantics.
`downcity` / `city` hosts local Agents, manages local projects, and connects this machine to a Federation. Federation creation, deployment, and infrastructure operations belong to `fed` / `downfed`. For concrete flags, use the local command help from the installed CLI; the City SDK docs cover the SDK-side CLI boundary.
- [CLI: fed and city](/en/city-sdk-docs/packages/cli)
## Local help
For exact flags, use local command help from the installed CLI. Product docs describe the supported command groups and common workflows.
## Interactive TUI
Running `city` or `downcity` without a subcommand now opens the interactive TUI by default. The `city` side focuses on local Agents and Federation connection state; the `fed` side focuses on Federation management and deployment. In both CLIs, the left sidebar carries menu hierarchy with a breadcrumb at the top, while loading states, forms, tables, JSON, messages, and selection details render in the right section until you exit the TUI.
## CLI language
`city` and `downcity` support both Chinese and English.
- Use `--lang zh` or `--lang en` to switch the current command explicitly.
- If `--lang` is not passed, the CLI first uses the last language selected in the interactive menu, then falls back to `DC_CLI_LANG`, `LC_ALL`, `LC_MESSAGES`, and `LANG`.
- In interactive mode, both `city` and `downcity` can change the default language from their menus and persist that preference locally.
Examples:
```bash
downcity --lang en --help
city --lang zh
DC_CLI_LANG=zh downcity agent --help
```
### .downcity Directory
Source: https://downcity.ai/en/docs/reference/dot-downcity/
`~/.downcity/` is Downcity's user-level configuration and runtime data directory. Downcity does not create a `.downcity/` directory inside each project.
## Typical layout
```text
~/.downcity/
├── agents//
│ ├── agent.json
│ ├── SOUL.md
│ ├── sessions///
│ ├── archived-sessions///
│ └── logs/
├── powers//
│ └── config.toml
├── runtimes/city/
└── downcity.db
```
## Key folders
### `agents//logs/`
Daily JSONL logs: `.jsonl`.
### `agents//sessions///messages/`
Conversation source of truth: `active.jsonl`, `agent_message.json`, and sequence-named `segments/*.jsonl`.
`category` has exactly two values, `chat` and `work`, and it is the only field that enters the directory
name. The role `type` is stored in Session metadata.
### Memory
Long-term Memory is not part of the Workspace `.downcity/` contract. Agent-private content lives under `agents//powers/memory/`; City-shared User and Workspace content lives under `memory/` and is isolated by `MemoryPower` subjects. City only supplies the shared root and does not implement Memory data logic.
### Power runtime data
Power-owned runtime data uses the Agent-level storage scope exposed by PowerContext. Power definitions and unique configuration remain under `~/.downcity/powers//`.
### Skills location
`SkillPower` scans `.agents/skills` (project) by default. If `use: ["home"]` is enabled in the constructor, it also scans `~/.agents/skills` (user).
## Security guidance
- `~/.downcity/` may contain sensitive configuration, conversations, tokens, and execution traces.
- Do not commit or copy the directory to an untrusted location.
### HTTP API Reference
Source: https://downcity.ai/en/docs/reference/api/
> User-facing runtime API. For most operations, CLI (`downcity ...`) is recommended first.
## Core endpoints
### `GET /health`
```json
{ "status": "ok", "timestamp": "2026-03-08T12:00:00.000Z" }
```
### `GET /api/status`
```json
{ "name": "downcity", "status": "running", "timestamp": "..." }
```
### `POST /api/execute`
Request body:
```json
{
"instructions": "Summarize today's changes",
"chatId": "default"
}
```
## Managed power API
### `GET /api/powers/list`
List managed power states.
## Power API
### `GET /api/powers/catalog`
List registered powers.
### `POST /api/powers/availability`
```json
{ "power_name": "sound" }
```
### `POST /api/powers/action`
```json
{
"power_name": "sound",
"action_name": "models",
"payload": { "capability": "asr" }
}
```
## Console UI API (summary)
### `GET /api/ui/powers`
Returns power summary plus availability state (used by Console UI panels).
Example:
```json
{
"success": true,
"powers": [
{
"name": "sound",
"actions": ["models", "asr", "tts"],
"pipelines": ["chat.augmentInbound"],
"guards": [],
"effects": [],
"resolves": [],
"hasSystem": true,
"hasAvailability": true,
"availability": {
"enabled": true,
"available": true,
"reasons": []
},
"config": {
"actions": [
{
"name": "models",
"supportsCommand": false,
"supportsApi": false,
"apiMethod": "",
"apiPath": ""
}
]
}
}
]
}
```
### `POST /api/dashboard/sessions/:sessionId/execute`
Execute one turn in a specific session (for example a selected chatKey).
Request body example with attachment:
```json
{
"instructions": "Please read the attached markdown and provide an actionable summary.",
"attachments": [
{
"type": "document",
"fileName": "page.md",
"contentType": "text/markdown; charset=utf-8",
"content": "# Captured Web Page\n\n..."
}
]
}
```
Notes:
- `sessionId` should be the exact target session returned by agent. For chat sessions, this is an opaque ID managed by the chat power (not a parseable platform key).
- Attachments are materialized by agent and injected as `` tags before the user instruction.
- If `sessionId` maps to a chat conversation, execution is enqueued into the same chat power queue (same behavior as platform inbound messages), and chat history is appended before execution.
- Chat-context calls return immediately with queue metadata (`queued=true`, `queueItemId`, `queuePosition`).
## Action routes
Power actions use:
- `/api/powers/action`
Except for `GET /health`, Agent HTTP APIs require a Bearer Token issued for that Agent. Tokens do not contain Users, Roles, or Permissions; they only grant access to their owning Agent.
## Debug baseline
Make sure the agent is running before calling APIs. Runtime startup belongs to the [Agent start workflow](/en/docs/reference/cli); the health endpoint belongs to the running Agent HTTP surface.
### Contributing
Source: https://downcity.ai/en/docs/community/contributing/
Thank you for your interest in contributing to Downcity! This guide will help you get started.
## Ways to Contribute
### 🐛 Report Bugs
Found a bug? Report it:
1. Search existing issues first
2. Create a bug report with:
- Clear title and description
- Steps to reproduce
- Expected vs actual behavior
- Environment details (OS, Node version, etc.)
- Screenshots if applicable
### 💡 Suggest Features
Have an idea? Propose it:
1. Check roadmap and existing discussions
2. Create a feature request with:
- Problem statement
- Proposed solution
- Use cases
- Potential implementation
### 📖 Improve Documentation
Docs are code too! You can:
- Fix typos and grammar
- Add examples
- Clarify confusing sections
- Translate to other languages
- Add new guides
### 🔧 Code Contributions
Ready to code? Great!
1. Start with good first issues (tagged `good-first-issue`)
2. Follow the contributing guide below
3. Submit a pull request
---
## Development Setup
### Prerequisites
- Node.js >= 18
- pnpm (recommended) or npm
- Git
### Fork and Clone
```bash
# Fork the repository on GitHub
# Clone your fork
git clone https://github.com/YOUR_USERNAME/downcity.git
cd downcity
# Add upstream remote
git remote add upstream https://github.com/genesiscosmos/downcity.git
```
### Install Dependencies
```bash
# Install dependencies
pnpm install
# Setup development environment
pnpm dev:setup
```
### Build and Test
```bash
# Build the project
pnpm build
# Run tests
pnpm test
# Run linter
pnpm lint
# Type check
pnpm typecheck
```
---
## Project Structure
```
downcity/
├── packages/
│ ├── cli/ # CLI tool
│ ├── core/ # Core agent logic
│ ├── llm/ # LLM provider implementations
│ └── tools/ # Built-in tools
├── private/apps/homepage/ # Documentation site
└── examples/ # Example configurations
```
---
## Making Changes
### Branch Strategy
```bash
# Create a feature branch
git checkout -b feature/my-feature
# Or for bug fix
git checkout -b fix/issue-123
# Or documentation
git checkout -b docs/update-guide
```
### Commit Messages
Follow conventional commits:
```
feat: add support for custom tools
fix: resolve race condition in task scheduler
docs: update installation guide
chore: upgrade dependencies
test: add tests for permission system
refactor: improve LLM provider abstraction
```
### Code Style
Follow the project's code style:
```bash
# Run formatter
pnpm format
# Run linter
pnpm lint:fix
# Type check
pnpm typecheck
```
---
## Pull Request Process
### Before Submitting
1. **Run tests**: `pnpm test`
2. **Format code**: `pnpm format`
3. **Check types**: `pnpm typecheck`
4. **Update docs**: If applicable
5. **Add tests**: For new features
### Submitting PR
1. Push to your fork
2. Create pull request to `genesiscosmos/downcity:main`
3. Fill PR template:
- Description of changes
- Related issues
- Testing steps
- Breaking changes (if any)
### Review Process
Maintainers will review your PR and provide feedback. Address review comments and push updates to your branch.
### Merging
Once approved, your PR will be merged. Maintainers will:
- Squash commits if needed
- Update changelog
- Deploy to production
---
## Coding Standards
### TypeScript
- Use strict mode
- Avoid `any` type
- Prefer `const`/`let` over `var`
- Use arrow functions for callbacks
- Document public APIs
- In `cli/city/src`, you can use `@/` path aliases (mapped to `src`), and `pnpm build` will rewrite them to runnable relative paths in `bin`
### Testing
- Write unit tests for new features
- Aim for >80% code coverage
- Mock external dependencies
- Test edge cases
### Documentation
- Document public APIs
- Add JSDoc comments
- Include usage examples
- Update guides if behavior changes
---
## Development Workflow
### Example Feature Development
```bash
# 1. Create branch
git checkout -b feature/add-discord-power
# 2. Make changes
# ... edit files ...
# 3. Commit changes
git add .
git commit -m "feat: add Discord bot power"
# 4. Test
pnpm test
# 5. Push to fork
git push origin feature/add-discord-power
# 6. Create PR on GitHub
# Visit your fork and create pull request
```
### Syncing with Upstream
Keep your fork up-to-date:
```bash
# Fetch upstream
git fetch upstream
# Merge upstream main
git checkout main
git merge upstream/main
# Push to your fork
git push origin main
```
---
## Community Guidelines
### Code of Conduct
- Be respectful and inclusive
- Provide constructive feedback
- Accept feedback gracefully
- Focus on what is best for the community
### Getting Help
- Ask questions in Discord
- Start discussions for complex topics
- Request reviews early (WIP PRs)
### Recognition
Contributors are recognized in:
- Release notes
- Contributors section
- Annual community highlights
---
## Developer Certificate of Origin
By contributing, you agree to the DCO:
```
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1. The making of contributions and patches to the Project by
developers and other stakeholders is the intended method
of cooperation and collaboration for the Project.
2. The Developer Certifies that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open
source license and I have the right under that license to
submit that work with modifications, whether created in whole
or in part by me, under the same open source license (unless
I am permitted to submit under a different license), as
indicated in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including
all personal information I submit with it, including my
sign-off) is maintained indefinitely and may be redistributed
consistent with this project or the open source license(s)
involved.
```
Add this to your commits:
```bash
git commit -s -m "feat: add new feature"
```
---
## Project-Specific Guidelines
### Core Package Changes
For changes to `packages/agent`:
- Add tests for new features
- Update architecture docs if needed
- Consider backward compatibility
### CLI Changes
For changes to `cli/city`:
- Update CLI help text
- Add usage examples
- Document new commands
### Documentation Changes
For changes to `private/apps/homepage/`:
- Test locally: `pnpm dev`
- Check for broken links
- Update navigation if needed
---
## Release Process
Maintainers follow this process:
1. Update version in `package.json`
2. Update CHANGELOG.md
3. Create release branch
4. Test thoroughly
5. Tag release
6. Build and publish
7. Create GitHub release
8. Announce on community channels
---
## Resources
### Documentation
- [Architecture](/en/docs/concepts/architecture) - System architecture
- [Power Commands](/en/docs/reference/cli) - User-facing power command docs
- [API Reference](/en/docs/reference/api) - Runtime HTTP API docs
### Community
- [Discord](https://discord.gg/downcity) - Real-time chat
- [Telegram Community](https://t.me/+iozIHyXr-BJhNjE1) - Q&A
- [GitHub Issues](https://github.com/genesiscosmos/downcity/issues) - Bug reports
### Related Projects
- [Fumadocs](https://fumadocs.com) - Documentation framework
- [DeepSeek](https://www.deepseek.com) - AI model
- [OpenAI GPT](https://openai.com) - AI model
---
## Recognition
Thank you for contributing! Your help makes Downcity better for everyone.
Contributors are recognized in:
- [Contributors](https://github.com/genesiscosmos/downcity/graphs/contributors)
- Release notes
- Annual highlights
---
## Next Steps
Ready to contribute?
1. Look for [good first issues](https://github.com/genesiscosmos/downcity/labels/good-first-issue)
2. Join the [Discord community](https://discord.gg/downcity)
3. Start coding! 🚀
### Downcity Docs
Source: https://downcity.ai/zh/docs/
Downcity 是给 AI builders 的 Agent 基础设施。这套文档帮助你运行本机 Agent、接入 City、连接模型和 Power,并把 Agent 工作流做成真实产品表层。
最短产品模型:
- 产品负责用户体验
- Agent 在明确运行边界里执行任务
- Downcity 提供模型、工具、任务、记忆、服务、权限、用量、计费和控制台这些可复用运行层
## 从这里开始
## 运行与控制
- [Agent](/zh/docs/agent/overview/):执行能力与运行边界。
- [Power](/zh/docs/power/overview/):工具与集成的组织方式。
- [City](/zh/docs/city/overview/):宿主、资源和工作空间。
- [Federation & Service](/zh/docs/federation/overview/):共享模型与产品服务。
- [安全](/zh/docs/security/overview/):权限、审批与隔离边界。
- [CLI](/zh/docs/cli/overview/):在终端管理本机运行环境。
## 文档 Space
- [Products](/zh/docs/):产品级文档:Agent、Power、City、Federation、安全和参考。
- [Agent SDK](/zh/agent-sdk-docs/):可编程 Agent、Session、Local/Remote Agent、模型绑定和 Power API。
- [City SDK](/zh/city-sdk-docs/):`City`、`Federation`、downcity 身份、token、service/action 基建和部署。
- [Payments](/zh/payments/):accounts、balance、usage、Stripe payment services。
- [Agent Powers Docs](/zh/powers-docs/):内建 Power 手册和 Power 示例。
- [UI SDK](/zh/ui-sdk-docs/):可复用 UI 组件和 Workboard 界面。
### 快速开始
Source: https://downcity.ai/zh/docs/quickstart/
Downcity 有多个用户表层。这个页面是入口地图,不是命令教程。
你可以按目标选择入口:
- 想运行本地 Agent、管理项目 Agent、使用内建 Power 命令,看 [Downcity CLI](/zh/docs/reference/cli)。
- 想创建、管理或部署 Federation 项目,看 [CLI](/zh/city-sdk-docs/packages/cli) 里的 `fed/downfed`。
- 想把 Agent 能力嵌入自己的 Node.js 应用,看 [Agent SDK](/zh/agent-sdk-docs)。
- 想构建 service、模型供应、计费、usage 或 admin 表层,看 [City SDK](/zh/city-sdk-docs)。
- 想理解内建 Power 行为或编写 Power 集成,看 [Agent Powers Docs](/zh/powers-docs)。
- 想查 Downcity CLI、Downcity Console、Chrome Extension 的产品用法,看 [Products Docs](/zh/docs)。
## 推荐阅读顺序
先理解模型:
1. [Downcity 的整体关系](/zh/docs/concepts/project-logic-overview)
2. [Agent 总览](/zh/docs/agent/overview/what-is-agent)
3. [配置模型](/zh/docs/configuration/overview)
再选择具体使用表层:
- 本地 CLI 使用:[Downcity CLI](/zh/docs/reference/cli)
- 项目 Agent 工作流:[Agent CLI 产品文档](/zh/docs/reference/cli)
- Power 工作流:[Power CLI 产品文档](/zh/docs/reference/cli)
- Federation / 本机 Agent 命令:[CLI](/zh/city-sdk-docs/packages/cli)
- SDK 集成:[Agent SDK](/zh/agent-sdk-docs)
## 这个 Space 解释什么
Downcity docs 解释为什么系统要拆成 Downcity、City、Agent、Powers、services、permissions 和 configuration 这些层。
具体命令参数、示例和一步步操作指南,放在产品文档或 SDK 文档里。
### Desktop 消息
Source: https://downcity.ai/zh/docs/desktop/
{/* Desktop 面向用户的消息阅读、文件预览与折叠操作说明。 */}
## 系统要求
macOS 版本需要 **macOS 13 Ventura 或更新版本**。
## 输入与焦点
搜索、设置表单和多行编辑使用统一的输入样式。悬浮时背景轻微变化,点击或通过键盘进入后,聚焦背景会持续显示;输入框不绘制外扩光圈,靠近面板或滚动区边缘时也保持在容器内。搜索头和聊天编辑器由整个输入区域表达焦点,内部字段不重复显示背景。只读内容可以选择和复制,禁用字段保持弱化,输入错误在字段旁说明。
聊天草稿会在暂停输入后自动保存在本机。离开输入区或切换会话时,会立即保存待保存的内容;切换回来时,各会话会恢复各自的草稿。
## 测试 System One 决策模型
在 **设置 → 模型** 的决策模型区域点击 JEV 或其他决策模型,在详情中使用 **测试决策模型**。表单预填了可直接运行的示例;修改待判断内容与判断问题,选择布尔判断、选项判断或评分,再点击 **运行测试**。选项判断每行填写一个不重复的候选项(2–255 项);评分需要填写上下界,区间宽度为 1–9。切换答案类型时,请同步调整判断问题。
结果展示结构化答案、上游提供的概率或选项分布、用量以及本次耗时。失败时在表单内显示错误,可以修改输入后重试。测试使用当前账户,按模型正常计费;关闭详情不会取消已经提交的请求。
## City Remote
在 **设置 → 通用 → City Remote** 启用 HTTP 连接,默认监听 `127.0.0.1:5314`。开关直接生效;修改地址或端口后点击保存更改。页面显示实际运行状态、连接地址及启动失败原因。把运行中的地址复制到 Chrome 扩展的 City URL,无需另行执行 `city on`。
在同一页创建 City Token,填写名称、选择允许的 Agents(或明确允许全部现有及未来 Agent)和过期时间。点击创建 Token,在弹窗中选择 30 天、90 天、永不过期或自定义日期。明文仅在创建后的独立弹窗中显示一次,复制到 Chrome 的访问凭据后点击完成。已有凭据可修改范围、有效期或撤销;CLI 的 `city token` 管理的是同一份凭据。
服务默认关闭,开启设置会在下次 Desktop 启动时恢复。关闭开关、修改监听设置或退出 Desktop 会断开远程连接。Desktop 与 CLI 仍采用单宿主机制,不需要同时启动。`127.0.0.1` 仅供本机连接;监听其他地址时使用对应机器地址,并自行配置所需的网络访问。
## 粘贴图片与附件保存
粘贴图片后,输入草稿中的附件以 Data URL 保存在本地 IndexedDB。发送时,Session 会将附件解码保存到自己的 `attachments` 目录,消息的 file part 记录本地绝对路径,并紧跟一个 `attachment_path` context part,以“对应图片路径:…”(其他文件为“对应附件路径:…”)向模型提供保存路径。
## 连续发送与接管
在 Chat 中发送消息时,只有会话空闲且待发送列表为空才会立即提交;当前一轮仍在执行,或待发送列表里还有消息时,新输入会追加到待发送列表末尾,等上一个 Turn 结束后按顺序逐条提交,不会越过前面排队的内容。
列表中的消息在真正提交前只是本地记录:可以编辑、删除、调整顺序,或逐条暂停。`⌥/Alt + ⌘/Ctrl + Enter` 直接追加一条暂停项,不会自动发送;`⌘/Ctrl + Shift + Enter` 绕过整个列表立即提交当前输入,不影响列表中的其他消息。提交失败的消息保留在列表中并转为暂停,修复后可以重试。
每一轮工作由发起者占用。同一用户可以持续补充;如果当前工作由其他对象发起,队列提交会被拒绝,消息保留在待发送列表中并转为暂停,不会丢弃。需要接管时,先使用停止按钮,等待当前工作停止,再发送自己的消息。停止只针对界面已显示的那一轮;状态已变化时请刷新后重试。提交被拒绝不会把原有工作标为执行失败。
停止前登记的完成通知仍会携带原任务的停止结果送达,不会使用接管后新一轮的回答。
## 重试失败的 Agent 回复
当对话中最新可见的消息是已结束且包含可恢复错误的 Agent 回复时,可点击错误卡片右侧的**重试**。会话忙碌、等待或正在提交,有消息排队、历史记录正在加载,或本次重试仍在提交时,按钮不可用。请先处理待回答问题或操作审批;会话接收重试请求时也会检查这些待处理项。
重试会保留已有输出和工具结果,失败卡片留在历史中,新的 Agent 尝试追加到对话末尾,不会重复显示一条用户消息。Agent 根据现有上下文继续执行,不会从头重放整个请求。已执行的操作仍可能再次发生,重试不保证这些操作的副作用只发生一次。
提交重试期间,按钮显示加载指示并阻止重复点击。提交失败时会显示错误,按钮恢复可用后可以再次重试。
## 回答问题与操作确认
Agent 的待回答问题和操作审批集中显示在聊天输入框上方,单聊与群聊使用相同入口。交互卡片使用统一浅色背景和圆角,多条待处理项通过左右箭头切换;群聊会标出当前发起的成员。切换待处理项或折叠消息中的工具详情不会清空已填写内容,多题问题也可通过左右箭头返回修改。补充说明按需展开填写。
长内容在待处理区内滚动,聊天输入框保持可见。提交成功后,该项从待处理区移出;提交失败会显示错误并保留内容,可直接重试。工具详情只展示工具执行信息,不重复展示审批卡片或“已允许”等审批结果。待处理交互统一在输入框上方操作,不再提供独立的右侧作答面板。
## 手动压缩上下文
在已有单聊 Session 的输入框中输入 `/`,选择 `/compact`,即可将较早的稳定对话内容合并为上下文摘要,原始聊天记录仍然保留。会话运行中也可以提交;压缩请求进入 Session 队列,在维护检查点按队列顺序执行。压缩与 prompt 共用 Session 队列的忙碌状态,执行期间会话加载指示持续显示,队列全部排空后才结束;连续排队不会在命令之间提前显示空闲。压缩过程与结果显示在聊天时间线中,没有可压缩内容时也会给出提示。新对话草稿不显示该命令。
摘要历史以纯文本传入:用户和 Agent 保留正文,工具只保留结果,省略调用参数、调用 ID、协议状态和 JSON 包装;结构化结果按缩进键值呈现,保留必要的字段含义。压缩与正常对话共用模型可见内容的转换规则,忽略界面展示数据、活动记录和推理过程;附件保留引用与元信息,不重新读取二进制内容。工具结果中嵌套的图片 data URL 和明确的 base64 字段也只保留媒体类型与大小等元信息,同级页面文字、路径和 URL 继续保留;原始工具记录不变。系统以压缩较早稳定内容约 65% 为目标,在完整内容边界选择最近的位置;至少保留 10,000 tokens 的原始历史,此要求优先于比例。历史不超过该保留量,或没有可推进的完整内容时不压缩。保留量不包含 system、旧摘要和工具定义。每次压缩将旧摘要、本次所选的每条历史记录和最终摘要要求分别放入多条纯文本消息,一次请求模型生成新摘要;历史保持原顺序,不再拼成单条超长 user 消息,也不分批反复重写。没有固定的 16k 或 64k 输入限制;已知模型窗口时预留 4,000 tokens 输出和 2,048 tokens 安全余量,放不下时只缩小本次历史范围。窗口未知时不设置人为输入上限。当前模型接口没有 tokenizer,英文、代码与 JSON 按每三 ASCII 字符约一 token、其他字符按码点估算;连续的长编码串按更高 token 密度估算,避免当作普通英文文本。以上并非精确 token 计数。单次摘要输出上限为 4,000 tokens。
完整摘要生成成功后一次保存新摘要与边界;失败保持原摘要和边界不变。传输中断时最多重试同一请求一次,部分生成但尚未保存的摘要会丢弃。HTTP 400 等请求拒绝直接反馈,不自动当作上下文超限。使用新版 Federation 服务时,错误还会包含上游状态码、可用请求 ID 和经过脱敏、长度限制的响应正文,方便定位具体拒绝原因。
## 窗口与面板
左侧 Sidebar、中间正文和右侧 BayBar 共享窗口空间。调整窗口大小时,Sidebar 优先保持你设置的宽度,正文先随窗口伸缩;空间不足时,BayBar 会先收窄,再自动收起。正文阅读空间继续不足时,Sidebar 也会自动隐藏。默认宽度和 100% 界面缩放下,窗口窄于 860px 时隐藏 Sidebar,重新达到 908px 时恢复;你设置的 Sidebar 宽度和界面缩放会同步调整该阈值。关闭的面板会释放全部占宽。
拖动面板与正文之间的边界可以调整宽度,松开后保存。临时缩小窗口不会覆盖已保存的宽度;重新放大窗口后,自动收起的面板会在空间足够时恢复,手动收起的面板保持关闭。窄窗口中主动打开 BayBar 或点击文件链接时,它会覆盖右侧内容区域,调整窗口大小后重新按可用空间布局。
Sidebar 自动隐藏或手动收起后,将鼠标移到窗口左边缘或顶部 Sidebar 按钮,停留约 150ms 即可浮出导航。浮动导航覆盖在正文上方,正文位置与宽度保持不变。移开鼠标约 250ms 后收起;操作关联菜单、拖拽宽度或在导航内使用键盘时保持展开。点击顶部按钮可固定展开;空间不足时保持浮动,点击外部或按 `Escape` 关闭。
使用窗口顶部按钮或 `⌘/Ctrl+B` 开关 Sidebar,使用右上角按钮或 `⌘/Ctrl+L` 开关 BayBar。窗口缩放和面板拖拽立即跟随操作,点击开关时使用短动画;系统开启减少动态效果时省略该动画。
## 会话层级
Works 侧栏的 Workspace 分组内,子 Session 紧跟所属的父 Session,并逐级缩进。根会话与同级子会话按运行状态优先、最近更新时间其次排列。父会话不在当前 Workspace 分组中时,子会话仍会作为根会话显示。置顶时整棵子树一起进入置顶区,保留层级和展开状态。归档父会话时,其所有层级的子会话也会一起归档;如果其中任一会话正在运行或有排队输入,需要先结束或停止执行。
每个父会话默认最多显示 3 个直接子会话,超出时在第 4 行显示“更多(还有 N 条)”。点击可展开全部子会话,再点击末尾的“收起子会话”恢复为 3 个。多层子会话分别控制展开状态;Workspace 的“更多”按根会话分页,多选范围只包含实际显示的会话。如果当前打开项或已选项排在第 4 个及之后,会自动展开必要的父列表,并暂时禁用该列表的收起操作;切换会话或取消选择后恢复原来的手动展开状态。
## 置顶会话
在 Works 侧栏中,会话行的更多菜单里选择**置顶**,这条根会话及其所有层级的子会话会一起移到列表最上方的**置顶**区,不随任何 Workspace 折叠。置顶区按置顶先后排列,新置顶的在最前;它在行尾标出所属 Workspace。Chat 页头的会话菜单里有同一项,显示为**取消置顶**。子会话菜单显示“置顶所属会话”或“取消所属会话置顶”,操作作用于所属根会话及整棵子树;取消置顶后,各会话回到所属 Workspace,新建的子会话自动跟随根会话。置顶区同样默认显示 3 个直接子会话,可展开、收起。置顶只用于 Works 侧栏里的会话,群聊会话同样可以置顶。
## 分享消息与会话
分享图片和 PDF 在文档页首显示 Downcity Logo 与品牌名称,预览和保存结果一致。
在已完成的 Agent 回复下方打开更多菜单,选择**分享**,在预览中选择**保存为图片**、**保存为 PDF**或**保存为 Markdown**,包含 Agent 名称、发送时间和完整正文。
在 Chat Session 右上角的更多菜单中选择**分享**,再选择**保存为图片**、**保存为 PDF**或**保存为 Markdown**。导出会读取完整历史,按原始顺序包含用户消息和 Agent 回复;思考过程、工具调用记录和内部上下文不包含在内。Markdown 保留可编辑正文和附件链接;图片与 PDF 保留代码块、表格、数学公式、图片以及内置可视化的静态展示。第三方或无法渲染的可视化使用已发布的文字摘要。
点击分享后先打开预览。顶部通过分段按钮切换图片、PDF 和 Markdown,中间画布居中展示内容,底部集中显示内容开关、复制和保存操作。图片随窗口等比缩放;长图的全部分段按顺序连续滚动展示。
分享单条 Agent 回复时,如果存在上一条用户消息,可开启**包含上一条用户消息**,将其发送者、时间、正文和附件放在回复之前。默认关闭;切换选项会更新预览,图片、PDF 和 Markdown 保存相同范围的内容。上一条用户消息位于更早历史时也支持,无需先手动加载聊天记录。
PNG 按实际图片分段展示,底部的**复制图片**会将当前主要可见的那张图片复制到剪贴板,无需先保存文件;PDF 可查看分页,Markdown 展示待保存的源码。确认后点击对应格式的**保存为…**按钮,才会打开系统保存框;取消保存仍保留预览,关闭预览会释放准备的内容。资源加载失败会在预览中提示。
短图片选择文件保存位置;长内容会提示选择目录,并在其中新建文件夹,按顺序保存多张 PNG。PDF 自动分页,文字可选择。完成后可直接打开文件或图片目录;取消保存不会产生导出文件。图片资源读取失败时会提示错误,可以处理资源后重新导出。
## 消息与文件
点击对话中的工作区文件链接,会在右侧文件面板打开预览,当前对话保持可见。指向其他已注册工作区的文件也在该面板打开;链接带有行号时会定位到对应行。网页链接通过默认浏览器打开。
文件面板与 Workspace 主视图按格式选择预览方式:Markdown 展示排版后的文档;本地 `.html`、`.htm` 展示静态网页,支持相对路径的样式表、字体和图片,禁用脚本与页面内跳转。CSV、TSV 展示带行列编号的表格,保留引号内的分隔符与换行,最多展示 1,000 行、100 列。Markdown、HTML、CSV、TSV 均可通过文件菜单中的**源码模式**查看完整原始文本;带行号的文本链接默认进入源码模式。
Markdown 文件中的相对图片路径(如 `images/chart.svg` 或 `../images/chart.png`)按当前文档所在目录解析,BayBar 文件面板与 Workspace 预览均支持。
Markdown 中标记为 `mermaid` 的围栏代码块会显示为图表,并随可用宽度调整布局。图表跟随当前主题,可复制源码或打开全屏查看;全屏支持缩放、拖拽、适应窗口和下载保留当前主题的 PNG。生成中的不完整语法会保留最近一次成功图表,生成结束仍无法解析时显示源码与重试按钮。
Markdown 中标记为 `svg` 的围栏代码块会直接显示为图片,适配可用宽度;BayBar 文件预览与聊天消息均支持。流式生成尚未形成完整 SVG、内容无效或图片加载失败时显示源码。SVG 以隔离图片方式加载,不执行脚本。
PNG、JPEG、GIF、WebP、SVG、AVIF、APNG、BMP、ICO 文件以图片展示,可切换适配面板或原始尺寸。图片独立加载,不经过文本读取接口。其他二进制文件显示**用系统默认应用打开**按钮,点击后使用系统关联的应用打开;打开失败时显示原因,可再次尝试。文本预览仍限制为 2 MB;代码与配置文件展示源码。
在右侧 BayBar 文件面板中选中文字,选区附近会出现**引用**浮动按钮。点击后,当前聊天输入框会加入包含工作区、文件路径和选中文字的引用;源码模式还会附带选区行号。引用保留点击时的内容,可以随草稿保存或在发送前移除。清空选区、滚动、切换文件或更新文件内容后,浮动按钮会收起。Markdown、表格预览和源码支持该操作;HTML 网页预览需要先切换到源码模式,图片不提供文字选区引用。
Agent 消息采用左右布局:左侧竖排头像与可选折叠按钮,右侧顶部信息栏显示 Agent 名称和时间,中间展示消息主体,下方展示文件改动。信息栏与主体之间保留间距。复制、引用和分支等消息操作位于全部内容下方;有文件改动时,操作栏显示在文件改动卡片之后。
有执行过程时,头像下方显示箭头折叠按钮,与头像竖向排列。按钮常显,悬停时显示浅色背景;收起时箭头朝右,展开时朝下。点击按钮可展开或收起执行过程,也可以通过键盘操作。
生成过程中,执行过程默认展开;完成后默认收起。收起时隐藏过程,最终回答保持完整可见,不再显示工具摘要折叠栏。只有执行过程而没有最终回答时,左侧箭头仍可用于重新展开。
展开与收起以按钮为滚动锚点。手动切换后,这条消息会保留你的选择。没有执行过程的消息直接展示回答,不显示折叠按钮。
### Chrome 扩展
Source: https://downcity.ai/zh/docs/products/chrome-extension/
Downcity Chrome 扩展支持在侧栏与 Agent 对话、引用当前网页和选中文本。需要 Chrome 116 或更新版本,以及已启动、可访问的 Downcity City。
[下载 Chrome 扩展 ZIP](/download/chrome-extension)
当前通过 ZIP 分发,需手动安装,尚未上架 Chrome Web Store。安装包适用于 macOS、Windows 和 Linux 上的 Chrome。
## 手动安装
1. 下载 ZIP,解压到一个长期保留的目录,例如 `Documents/Downcity/chrome-extension`。
2. 在 Chrome 地址栏输入 `chrome://extensions`。
3. 打开右上角的 **开发者模式**。
4. 点击 **加载已解压的扩展程序**。
5. 选择直接包含 `manifest.json` 的解压文件夹。
6. 在浏览器工具栏中固定 Downcity 扩展,点击图标打开侧栏。
不要选择 ZIP 文件,也不要在加载后删除解压目录。
## 连接 Downcity
先启动 City,再打开扩展的 **设置**,填写:
| 字段 | 内容 |
| --- | --- |
| City URL | City 的 HTTP 地址,默认 `http://127.0.0.1:5314`;支持反向代理路径前缀 |
| 访问凭据 | City 接受的 Bearer Token;按服务端鉴权要求填写 |
| 默认 Agent | 点击连接 City 后,从可访问列表中选择,无需手填 ID |
| Default Ask | 从网页分享入口发送时使用的默认请求 |
在运行 City 的机器执行 `city token`,交互式创建凭据,选择允许访问的 Agents 和有效期;也可使用 `city token create --name chrome --agents --never-expires`。将签发时显示的明文直接填入访问凭据,旧 Agent Token 不再接受。
先点击 **连接 City / 刷新 Agent 列表**,选择默认 Agent,再点击 **保存并检查**。成功后关闭并重新打开侧栏,或点击 **重新连接**。列表为空时请检查凭据及 City 中是否已有 Agent。
`15314` 是 RPC 端口,不能作为 City URL。City URL 无需包含 `/agents/...`,扩展会根据 Agent ID 自动构造地址。Chrome 会话使用 `chrome` 来源分区,不绑定 Workspace。
## 使用
- 点击工具栏图标,或使用 `Command+I`(macOS)/ `Ctrl+I`(Windows、Linux)打开侧栏;如快捷键冲突,可在 `chrome://extensions/shortcuts` 调整。
- 输入请求并发送。输入框默认引用当前网页,删除该引用后不预先发送网页正文;本轮 Agent 仍可通过网页 Power 按需读取。
- 在普通网页中选中文本,点击选区旁的 **引用**,将选区加入输入框。
- Agent 回复支持 Markdown、推理文本和工具执行状态。
- 关闭再打开侧栏会恢复当前 City、Agent 对应的 Chrome 会话。
- **新对话** 会创建新的会话;之前的会话仍保留在 Downcity 中。
- 实时连接断开时点击 **重新连接**,重新加载已保存的消息。
侧栏发送会为本轮提供 `chrome_page` Power,Agent 可以调用 `read_page` 读取正文,或调用 `find_text` 查找关键词。能力固定到发送时的标签页和 URL,导航后拒绝读取;不提供点击、填写或跨标签页操作。请保持侧栏打开直到本轮完成,关闭或断线会中断客户端能力。Chrome 内部页面、Chrome Web Store 和部分受保护页面无法读取。需要人工授权的工具操作会显示等待状态,请在 Downcity 中处理。
## 更新与卸载
手动安装的扩展不会自动更新。下载新 ZIP,将内容替换到原目录,在 `chrome://extensions` 点击扩展卡片上的重新加载按钮,然后刷新需要引用的网页。
当前源码版使用 City、Agent 和 Token 配置,旧版 Workspace 会话不会自动迁入 Chrome 会话;服务端历史不会删除。下载包是否包含此能力取决于已发布版本。
在 `chrome://extensions` 点击 **移除** 可卸载扩展。浏览器配置会随卸载移除,服务端会话不会被删除。
## 下载校验
[当前版本元数据](/download/chrome-extension/latest.json) 提供 ZIP 的版本、文件大小与 SHA-256。下载地址最终会跳转到带版本号的 ZIP;同一路径追加 `.sha256` 即可下载校验文件。
[扩展数据与隐私说明](/zh/docs/products/chrome-extension-privacy)
### Chrome 扩展数据与隐私
Source: https://downcity.ai/zh/docs/products/chrome-extension-privacy/
本说明适用于包含请求级网页 Power 的当前源码版本,更新日期:2026-10-20。
## 读取和发送
扩展为显示当前页面引用而读取活动标签页的标题和 URL。网页中的选区脚本在本地检测选中文本,点击“引用”后将选区传入侧栏。
点击发送时,扩展把用户输入以及本次引用的正文、标题、URL 或选区发送到用户配置的 City 下指定 Agent。侧栏发送还会提供仅对当前 Turn 有效的网页读取与文本查找能力,固定到发送时的标签页和 URL;Agent 调用时,读取结果会发送到该 City。删除网页引用只取消预先发送正文,不撤销本轮按需读取能力。网页内容可能包含登录后可见的私人信息,请只在希望授权 Agent 阅读的页面发送。页面导航后拒绝读取,关闭侧栏会中断执行通道。
City 会按照用户配置执行 Agent 请求,内容可能被提供给用户配置的模型服务或工具。服务器侧的保存期限、模型提供方和工具行为取决于该 City 的配置。
## 本机保存
扩展使用 Chrome `storage.local` 保存 City URL、Agent ID、Agent Token、默认请求、服务端会话 ID、网页分享入口的最近发送记录,以及短期选区引用。Token 不写入 `storage.sync`。
发送记录包含网页 URL、请求文本和时间,不包含抓取的网页正文。卸载扩展会移除浏览器端配置;服务端会话需要在 Downcity 中单独管理。
## 权限用途
| 权限 | 用途 |
| --- | --- |
| `tabs` | 获取活动标签页标题、URL,以及响应标签页切换 |
| `activeTab`、`scripting` | 在发送网页引用或本轮 Agent 调用网页读取、查找 Action 时读取绑定页面内容 |
| `sidePanel` | 展示常驻对话侧栏 |
| `storage` | 保存本机设置、会话身份和短期引用 |
| HTTP/HTTPS host permissions | 连接用户自选的本机或远程 City,并在普通网页提供选区引用 |
扩展本身不包含广告、分析埋点或独立遥测上传,也不出售用户数据。官网安装包下载请求由 Downcity 的网站和 Cloudflare 处理,属于网站访问行为。
如有隐私问题,请通过 [Downcity GitHub Issues](https://github.com/genesiscosmos/downcity/issues) 联系维护者;公开反馈时请勿包含 Token 或私人网页内容。
### 官网账户
Source: https://downcity.ai/zh/docs/website-account/
{/* 官网账户的用户操作说明。 */}
点击官网导航中的 **登录**,选择当前可用的 GitHub 或 Google 登录方式。原登录弹窗会显示授权码,并打开授权窗口。完成第三方认证后,将原弹窗中的授权码输入确认页;确认授权后,原页面会自动继续并返回你之前浏览的页面。
如果授权窗口没有打开,请允许 Downcity 官网打开弹出窗口后重试。等待期间可以取消登录;登录过期或失败时,重新选择登录方式即可。
登录后,点击导航中的账户名称,选择 **账户信息**,可以查看名称、邮箱和用户 ID。第三方账户未提供邮箱时,页面会显示“未提供”。
## 余额与使用情况
用户中心采用左右布局,左侧可切换 **账户概览**、**用量与活动**、**账务记录**、**API Keys**、**调用记录**、**模型与接入** 和 **账户资料**。手机使用顶部栏目菜单。栏目通过 URL 的 `view` 参数定位,切换时复用已读取数据;刷新时保留当前内容。
用户中心提供:
- 当前可用 Credits,以及永久额度、限时额度和到期时间。
- 本月截至今日的消费、AI 请求次数和已计量 Token。
- 用量与消费折线图,可切换消费(USD)、Token 和请求次数,查看最近 7、30 或 90 天的每日趋势。悬停可查看当天各指标,覆盖前日期保留为空。
- 过去 365 天的活动热力图,按 AI 请求次数着色,鼠标悬停或键盘聚焦可查看当天详情,点击固定日期,关闭详情或按 Escape 取消固定。
- 概览中的最近 3 笔账务记录;账务栏目展示最近 20 笔,点击记录展开说明和状态。
统计按浏览器时区的自然日计算。AI 请求次数包含失败或取消的执行,Token 只统计实际已计量用量;消费来自独立账务记录,不根据 Token 推算。覆盖起点以前的日期不视为零活动。
额度入账可能来自充值或活动赠送,因此记录显示为“额度入账”。官网当前提供额度说明,尚未提供直接充值流程。服务暂时不可用时,对应区域会提示错误,点击 **刷新数据** 可重新查询。
## API Key 管理
在用户中心选择 **API Keys**(也可直接打开 [Key 管理](/zh/account?view=keys))。你可以查看自己的 Key、创建 Key、编辑名称、模型 / route 权限、到期时间和消费软上限,也可以停用、恢复或永久撤销 Key。
权限选项来自服务当前发布的语言模型与 route 目录。选“所有当前及未来发布的模型和 route”会同时允许以后新增的入口;不选择任何入口则不能推理。只授权某个 route 不会允许直接调用它的模型。已下线的旧权限会保留在编辑列表中,可以取消;目录读取失败时保持现有权限,刷新成功后再修改权限或创建 Key。
消费软上限以整数 Credits 填写,留空表示不限额,0 会阻断新调用。它按该 Key 自签发以来已经成功结算的累计消费检查,修改上限不会重置消费。**不预占资金**,多个并发在途请求可能让最终消费超过上限;所有 Key 共用账户余额。到期时间按浏览器本地时间填写,留空表示不自动到期。
创建成功后,完整 Key **只展示一次**,请立即复制并妥善保存。关闭弹窗、离开 Key 栏目或退出登录后,页面不会再次显示明文。复制不可用时,可选中文本手动复制。若创建时网络中断,请先刷新列表确认结果;发现新增 Key 但没有取得明文时,撤销它再重新创建。
停用可以恢复;撤销不可恢复,确认前请检查 Key 名称和前缀。停用、撤销或过期会阻断新请求,已经开始的调用仍会结算。Key 只能访问获准推理入口,不能用来登录或管理账户。OpenAI 客户端配置见 [模型中转接入指南](/zh/city-sdk-docs/service/ai/relay)。
## 调用记录
在 [调用记录](/zh/account?view=requests) 查看自己的模型中转请求,每页最多 20 条,支持按 Key 筛选、上一页、更早记录和刷新最新记录。Key 名称与前缀来自本人 Key 列表;暂不可用时显示 Key ID,登录身份调用会单独标明。
每条记录显示请求的公开模型 / route、执行状态、输入与输出 Token、已结算 Credits、耗时和结算状态。**未知 / 未提供不代表 0**;输入 Token 只有缓存与未缓存两部分均已提供时才相加,推理 Token 是输出的一部分,不额外重复计算。尚未结算、结算失败或没有费用字段时,不显示为免费。点击 **详情与尝试** 查看请求 ID、实际公开模型、计量拆分及安全的上游尝试信息,包括渠道 ID、实际上游模型、HTTP 状态和首个内容耗时;没有提示词、回答正文或渠道凭据。
当前只提供 Key 筛选,不支持后端未提供的日期、状态或模型筛选。执行前拒绝的请求可能没有记录;中断的请求也可能停留在进行中,应结合计量与结算状态判断。
## 模型与接入
[模型与接入](/zh/account?view=models) 实时读取当前可用的公开语言模型与 route,支持按名称或 ID 搜索。页面保留后端声明的上下文、推理档位和结构化价格,包括币种、计价单位、数量与适用条件;缺失字段明确标为未提供,不从标签推断工具或视觉能力,也不推算 Credits。
OpenAI Base URL 从网站服务端的 Federation 连接配置推导。选择模型或 route 以及协议后,可以复制 **OpenAI Chat Completions** 或 **Downcity 原生模型流** 的 curl 示例。示例只使用 `YOUR_DOWNCITY_API_KEY` 占位值,不读取或保存真实 Key;请在自己的安全客户端替换。原生流使用独立的 Downcity SSE 事件协议。当前不支持 Responses 和 Anthropic Messages;页面不宣称这些接口可用。
目录可见不代表调用 Key 获得权限,仍需在 Key 管理中授权相应入口。目录读取失败时显示错误,刷新后可重试;显示上次读取内容时会明确提示。
选择 **退出登录** 会撤销当前官网登录凭证,并结束当前浏览器会话。退出失败时,请在服务可用后重试。会话失效后,再次登录即可继续使用。官网退出不会退出桌面端或其他设备中的账户。
### Agent
Source: https://downcity.ai/zh/docs/agent/overview/
**Agent SDK** (`@downcity/agent`) 是执行 Agent 工作的核心运行时。Agent 负责身份、模型、指令、
Tool 与唯一的 `AgentSessions` 集合;每个 Session 可以接收一个 Workspace。`City` 持有 Workspace、
Power 唯一实例、Agent/Group 集合与 transport。
## Agent 做什么
- 读取项目配置(构造参数或项目目录)
- 维护会话和对话历史
- 在执行过程中调用工具
- 使用 City 投影到当前作用域的 Power 能力
- 绑定到模型进行推理
## 创建 Agent
在 Desktop 中点击“创建 Agent”会进入独立创建页面。你可以用自然语言描述想要的角色,让系统默认模型自动生成名称、简介、角色指令和推荐 Powers;也可以选择“手动配置”,从空白草稿开始填写。AI 只负责生成可编辑草稿,确认后才会真正创建 Agent。
创建时不需要手动设计内部 ID。Desktop 会根据名称生成稳定 ID;例如“研究助手”会生成 `yan_jiu_zhu_shou`。
AI 生成和 Agent 运行模型都默认选中 Desktop 设置中的系统默认文本模型,也可以分别调整;仅当默认模型不可用时才回退到第一个可用文本模型。Desktop 页面统一展示 Agent 名称,稳定 ID 只用于内部路由和存储。
名称和简介用于联系人列表与对话中的身份展示。内部 ID 继续用于本地目录、API 引用和运行时身份;如果名称生成的 ID 已存在,Desktop 会要求换一个名称,不会隐式追加随机后缀。
创建后可以在 Agent 配置中继续修改名称和简介。修改名称不会改变稳定 Agent ID,因此已有 Session、Group 引用和 Power 数据路径保持不变。
Agent 配置中的“删除 Agent”会永久删除该 Agent 的定义、头像、Session、日志、Schedule 与 Agent 作用域的 Power 数据。正在执行任务或仍属于 Group 的 Agent 不能删除,需要先结束执行或将它移出相关 Group。
## Desktop 完成提醒
当 Agent Session 在后台完成一次 Turn 时,Desktop 会在 Chat Sidebar 的 Agent 和下方对话列表的对应 Session 上显示蓝色未读圆点,并在系统应用图标上显示未读 Session 数量。正在前台查看该 Session 时不会产生未读;打开对应 Session 后,圆点和系统角标会同步清除。多次完成同一个 Session 只计为一个未读项。
## 创建 Group
点击“创建 Group”会进入独立创建页面。你可以描述团队目标,让所选模型根据当前已有 Agent 生成 Group 名称、协作目标和推荐成员;也可以从空白配置手动选择模型与成员。AI 结果在确认前始终只是可编辑草稿。
创建 Group 时只填写用户可见名称,内部 `group_id` 由 Desktop 根据名称自动生成。创建后可以修改名称、协作目标、模型与成员,但稳定 `group_id` 不会改变。Group 头像由成员 Agent 的头像组合展示。
```ts
import { Agent } from "@downcity/agent";
import { City } from "@downcity/city";
import { create_builtin_power_registrations } from "@downcity/powers";
import { Workspace } from "@downcity/city";
import { Shell } from "@downcity/city";
import { MicrosandboxProvider } from "@downcity/sandbox-microsandbox";
const agent = new Agent({
id: "repo-helper",
model: myModel,
tools: { my_tool: myTool },
});
const workspace = new Workspace({
id: "project",
path: "/path/to/project",
shell: new Shell({
sandbox_provider: new MicrosandboxProvider(),
}),
});
const city = new City({
workspaces: [workspace],
powers: create_builtin_power_registrations(),
});
city.agents.add(agent);
```
## 从历史消息创建 Session 分支
`session.fork()` 默认保留锚点消息。编辑并重新发送历史消息时,可以排除原消息,让新 Session 从修改后的内容继续:
```ts
const forked_session = await session.fork({
message_id,
include_message: false,
});
```
需要在当前对话中替换历史时,传入 `replace: true`:
```ts
await session.fork({ message_id, include_message: false, replace: true });
```
这会原地移除锚点及后续消息,保留当前 Session ID 与配置,不创建分支、不归档、不添加操作提示。当前 Session 必须空闲;省略 `message_id` 时不改变历史。Desktop 的“替换当前对话”使用该方式。
## 设置 Desktop Agent 头像
Desktop 会从用户级 Agent 目录读取头像。将图片放在对应 Agent ID 目录下即可:
```text
~/.downcity/agents//avatar.png
```
也支持 `avatar.jpg`、`avatar.jpeg` 和 `avatar.webp`,头像文件大小限制为 2 MiB。未配置头像时,Desktop 使用默认图标。
新建 Agent 时,Desktop 会从内置像素头像池随机选择一张并保存为该 Agent 的独立头像。在 Agent 详情页点击头像,可以再次随机选择内置头像或上传自定义图片。
## 关键概念
- **City** — 持有 Workspace、Power 唯一实例、Agent/Group 集合与统一 transport。
- **Session** — 一个执行线程。Agent 按需创建会话,并通过它们路由消息。
- **Tool** — Agent 在执行过程中可调用的函数。直接传给构造函数。
- **Power** — 由 City 提供和维护,并自动投影给全部 Agent 的扩展能力。
- **Model** — 推理后端。Agent 持有默认实例,Session 可设置自己的实例并优先使用。
## Agent 不做什么
- 不管理多个项目(那是 CLI / 控制台层)。
- 不拥有模型目录(那是 City / Federation)。
- 不持久化全局凭证(那是 City)。
保持这些边界清晰,你很容易回答:模型应该在哪配置?机器人凭证应该放在哪?这是控制平面故障还是项目运行时故障?
## 执行模型
Agent 执行模型很简单:
1. 接收消息或任务
2. 加载会话上下文(历史、工具、Power、提示词)
3. 调用模型
4. 如果模型要求调用工具,执行它并继续
5. 返回结果
继续阅读:
- [Agent SDK](/zh/docs/agent/sdk)
- [SDK 架构](/zh/docs/agent/sdk-architecture)
- [运行时架构](/zh/docs/agent/runtime-architecture)
- [Agent 生命周期](/zh/docs/agent/lifecycle)
### Agent SDK
Source: https://downcity.ai/zh/docs/agent/sdk/
`@downcity/agent` 用于在同一进程中创建 Agent、管理 Session 并执行模型调用。完整 API 参考在 [Agent SDK 文档](/zh/agent-sdk-docs)。
```ts
import { Agent } from "@downcity/agent";
import { City } from "@downcity/city";
import { create_builtin_power_registrations } from "@downcity/powers";
import { Workspace } from "@downcity/city";
import { Shell } from "@downcity/city";
import { MicrosandboxProvider } from "@downcity/sandbox-microsandbox";
const workspace = new Workspace({
id: "project",
path: process.cwd(),
shell: new Shell({
sandbox_provider: new MicrosandboxProvider(),
}),
env: { API_KEY: process.env.API_KEY ?? "" },
});
const agent = new Agent({
id: "repo-helper",
model,
tools: { search: search_tool },
});
const city = new City({
workspaces: [workspace],
powers: create_builtin_power_registrations(),
});
city.agents.add(agent);
// Session 在创建时选择 Workspace。
const session = await agent.sessions.create({ workspace });
const turn = await session.prompt({ query: "检查当前项目" });
const result = await turn.finished;
await agent.dispose();
```
`Workspace` 来自 `@downcity/city`,拥有项目文件、搜索工具、Env 与可选 Shell,但不拥有 Agent 身份、存储、Power 或 Session 语义。`agent.sessions.create({ workspace })` 在 City 提供的 Agent Storage 作用域内创建 SessionStore。
Agent 配置不绑定 Workspace。每个 Session 可以使用一个 Workspace;多个 Agent 也可以通过各自的 Workspace 实例操作同一物理目录。`agent.dispose()` 会释放 Agent 资源和 Session 使用的 Workspace 资源。
本地运行状态集中保存在项目目录之外:
```text
~/.downcity/agents//
├── sessions///
└── archived-sessions///
```
`category` 只有 `chat` 与 `work` 两个值,是唯一决定目录的字段;`type` 是分类内的具体角色。
不传 `origin` 时默认是 `{ category: "work", type: "work" }`。自定义角色必须同时声明分类,
恢复时通过 `get(session_id, category)` 明确读取同一个分类。详见
[Session 来源与类型](../agent-sdk-docs/sessions/origin-and-types)。
City 在添加 Power 时启动唯一实例与后台任务,Session 执行会自动等待初始化完成。关闭整个宿主
使用 `await city.close()`;只移除 Agent 使用 `city.agents.remove()`。HTTP 与 RPC 也由 City 统一提供。
## 流式消息
`subscribe()` 返回统一的实时 Session Mutation:
```ts
const unsubscribe = session.subscribe((mutation) => {
if (mutation.variant === "delta" && mutation.type === "text") {
process.stdout.write(mutation.delta);
}
});
```
Tool 生命周期使用 `type: "tool"`,用户参与使用 `type: "interaction"`。pending Interaction 携带完整请求,关联 Tool 同时进入 `waiting-user`;响应通过独立 Session 命令提交:
同一 Assistant step 内的 Part 顺序始终与模型流一致。即使 Tool 已提前进入执行准备,它也会等待对应的 Tool Part 出现在流中,不会越过尚未写入的前置文本。等待按 `tool_call_id` 相互隔离,多个 Tool 仍可并发执行;客户端应按 Mutation 与历史快照中的顺序直接渲染,无需自行重排。
```ts
const unsubscribe = session.subscribe((mutation) => {
if (mutation.variant !== "part" || mutation.part.type !== "tool") return;
const interaction = (mutation.part.interactions ?? []).find(
(item) => item.status === "pending",
);
if (interaction) render_interaction(interaction);
});
async function decide_approval(interaction_id: string, decision: "approved" | "denied") {
await session.respond({
interaction_id,
response: { type: "approval", outcome: decision === "approved" ? "resolved" : "denied", payload: { decision } },
});
}
```
历史快照使用 `session.messages()`。它按 Message 边界分页,并在存在更早历史时返回 `next_before_sequence` 游标。连接断开后重新读取快照并建立新的订阅。
需要渲染平铺活动时间线的宿主可以直接使用 SDK 投影,不需要依赖 `.downcity` 的物理文件名:
```ts
import { to_session_message_timeline_events } from "@downcity/agent";
const page = await session.messages();
const timeline = page.items.flatMap(to_session_message_timeline_events);
```
Session JSONL、日志和调度任务使用 City 注入的 StorageProvider 作用域;没有 City 时,Agent 使用进程内存储。项目 File/Search 工具无法访问这些私有状态;应用应通过 `Agent.sessions` 和 Session API 访问结构化状态。
继续阅读:
- [SDK 架构](/zh/docs/agent/sdk-architecture)
- [运行时架构](/zh/docs/agent/runtime-architecture)
- [完整 Agent SDK API 文档](/zh/agent-sdk-docs)
### Agent SDK 架构
Source: https://downcity.ai/zh/docs/agent/sdk-architecture/
Downcity 将执行主体、项目资源与扩展运行时分开。`Agent` 拥有身份、指令、模型、自定义 Tool 和
Session;`Workspace` 拥有项目资源与 Shell;`City` 持有 Power 唯一实例、生命周期与 Agent 集合。
```ts
import { Agent } from "@downcity/agent";
import { City } from "@downcity/city";
import { create_builtin_power_registrations } from "@downcity/powers";
import { Shell, Workspace } from "@downcity/city";
const agent = new Agent({ id, model, instruction });
const workspace = new Workspace({ id: "project", path, shell });
const city = new City({
workspaces: [workspace],
powers: create_builtin_power_registrations(),
});
city.agents.add(agent);
// Session 在创建时选择 Workspace。
const session = await agent.sessions.create({ workspace });
```
## 职责模型
```mermaid
flowchart TD
Host["宿主应用"] --> City["City
资源与生命周期容器"]
City --> Agent["Agent
身份、模型、指令、Session"]
City --> Workspace["Workspace
项目资源与 Shell"]
City --> Powers["Powers
唯一实例、配置投影、生命周期"]
Agent --> Enter["agent.sessions.create({ workspace })"]
Workspace --> Enter
Enter --> Sessions["AgentSessions
Session 集合"]
Sessions --> Session["Session
连续执行"]
Session --> Tools["Workspace + Agent + Power Tools"]
Session --> Context["City 投影的 PowerContext"]
Powers --> Context
City --> Storage["StorageProvider
默认 Memory"]
Session --> Storage
Workspace --> Files["项目 File/Search"]
Workspace --> Env["Workspace Env"]
Workspace --> Shell["Shell"]
Shell --> Sandbox["Sandbox Provider + Workspace Sandbox"]
```
依赖方向保持明确:
- `@downcity/agent` 只依赖 `@downcity/type` 中的中立资源协议。
- `@downcity/city` 依赖 Agent,并通过 Agent 内部绑定注入 Workspace、Tool 与 SessionHooks;Agent 不反向依赖 City。
- 宿主在构造每个 Shell 时选择 Sandbox Provider;City 不理解具体后端。
- Edge Adapter 使用 `@downcity/type/workspace`,不会加载 Node.js 本地实现。
## Agent 是主体
一个 Agent 可以跨项目复用,不能在配置中永久绑定单一 Workspace。
```ts
const agent = new Agent({
id: "repo-helper",
model,
instruction: "维护当前项目。",
tools: { company_search: company_search_tool },
});
city.agents.add(agent);
const frontend = await agent.sessions.create({ workspace: frontend_workspace });
const backend = await agent.sessions.create({ workspace: backend_workspace });
```
Agent 不持有 Power。City 按 Power ID 持有唯一实例,并把全部能力投影到 Agent/Workspace
execution entry。每次 Power Action 都获得当前 `PowerContext`,可以直接使用受限的 Agent、
Workspace、Session 与 Turn 句柄。Power 只有 City 级 `initialize/dispose` 生命周期;
Agent/Workspace 只定义当前调用范围。
## Workspace 是资源边界
`Workspace` 拥有:
- 稳定的 Workspace ID 与规范化项目路径。
- Rooted 项目文件能力和 File/Search 工具。
- Workspace 环境变量。
- 可选 Shell 及其 Sandbox Adapter。
Workspace 不创建 SessionStore,不理解 Agent ID,不注册 Power,不调用模型,也不创建 Storage。
构造参数中没有运行时数据根目录。
Shell 属于 Workspace,因为命令执行作用于 Workspace 资源。公开入口是:
```ts
import { Shell, Workspace } from "@downcity/city";
```
不再存在独立的 `@downcity/shell` 包。各平台 Sandbox 仍是独立安装的 package,由宿主注入 Shell。
## Session 是执行边界
`agent.sessions.create({ workspace })` 组合 Agent 与 Workspace,但不混合它们的所有权。Agent、Session 与 City 执行投影共同提供:
- Workspace Tool、Agent 自定义 Tool 与 Power 桥接 Tool 组成的最终工具集合。
- `AgentSessions` 与 Agent 领域的 `LocalSessionStore`。
- 带当前 Agent/Workspace/Session/Turn 的 PowerContext 与 execution lease。
- 日志、Power 调度任务和 Shell 绑定。
不同来源的 Tool 同名时直接失败,不会静默覆盖。同一个 Agent 可以持有绑定不同 Workspace 的多个
Session。Workspace 可以登记在 City 内,也可以由宿主在 City 外管理。
## 私有存储
City 注入本地持久化 Storage 时,运行状态集中保存在项目目录之外:
```text
~/.downcity/
└── agents/
└── /
├── sessions/
├── powers/
├── logs/
└── schedule.jsonl
```
City Storage 只是底层文件或数据库能力。Agent 解释 `agents//` 业务作用域,并在其中
创建 Session 与 Power Store。项目 File/Search 工具使用另一套 rooted FileSystem,无法读取或
修改 Session 历史、Power 状态与运行时数据。
## 环境变量与检查点
环境变量描述项目执行环境,因此属于 Workspace:
```text
/.env < WorkspaceOptions.env
```
`set_env()` 与 `patch_env()` 更新 Workspace 快照并同步 Shell。已有 Session 会在下一个 Step
检查点提交新环境,避免模型调用执行到一半时上下文发生变化。
Power registry 更新、Session model 更新和 compact 也遵循相同的检查点规则。
## 生命周期
```mermaid
sequenceDiagram
participant Host as 宿主
participant Agent
participant Workspace
participant City
Host->>Agent: new Agent(options)
Host->>Workspace: new Workspace(options)
Host->>City: city.agents.add(agent)
Host->>Agent: sessions.create({ workspace })
Agent->>Workspace: 使用当前资源
Agent->>City: 使用注入的 Storage
Host->>Agent: dispose()
City->>Workspace: 释放 City 内 Workspace
```
`city.close()` 会停止 Agent 与 Session,释放 City 内 Workspace、Storage 和 transport。City 外的
Workspace 仍由宿主负责释放。
## Package 边界
| Package | 拥有 | 不拥有 |
| --- | --- | --- |
| `@downcity/type` | 跨 package 的中立资源协议 | 具体资源实现与生命周期 |
| `@downcity/agent` | Agent、AgentSessions、Session、Store、SessionHooks、模型 Tool Loop | City 组合、Power 生命周期、项目资源实现、平台 Sandbox |
| `@downcity/city` | City、Workspace/Shell 实现、Power SDK/runtime、Hook 调度、RemoteAgent、HTTP/RPC transport、本地宿主数据 | Agent 执行内核、具体内建 Power |
| Sandbox packages | 单个平台的原生进程隔离 | Workspace、Agent、Session 或 Power 业务 |
继续阅读:[运行时架构](/zh/docs/agent/runtime-architecture)。
### Agent 运行时架构
Source: https://downcity.ai/zh/docs/agent/runtime-architecture/
Agent runtime 的核心目标是:让每次输入都按确定顺序执行,让模型和 Tool 的中间状态可以观察,让进程中断后的 Session 可以恢复。
## Session 是执行边界
每个 Session 拥有独立的:
- ID、Metadata 和模型覆盖配置。
- Message 历史与 System Snapshot。
- Prompt/Command 队列。
- Tool 审批状态。
- Composer 与 Executor。
- 实时 Mutation 流。
```ts
// Session 在创建时选择 Workspace。
const session = await agent.sessions.create({ workspace });
const turn = await session.prompt({ query: "检查并修复项目" });
const result = await turn.finished;
```
`prompt()` 返回 Turn Handle,而不是直接返回文本。`finished` 在成功和失败时都会 resolve,调用方通过 `result.success` 和 `result.error` 判断结果。
## 一次 Prompt 如何执行
```mermaid
sequenceDiagram
participant App as 调用方
participant Session
participant Queue as SessionQueue
participant Messages as SessionMessages
participant Input as StepInput
participant Composer
participant Executor
participant Model as LanguageModel
participant Tool
App->>Session: prompt(query)
Session->>Queue: 写入 Prompt
Queue->>Messages: 持久化 User Message
Queue->>Executor: 创建稳定 run context
Executor->>Input: 请求本步输入
Input->>Composer: 读取 canonical history 与 checkpoint
Composer-->>Input: 基础 system、动态上下文、messages、tools
Input-->>Executor: 基础快照 + 本步动态上下文、messages、tools
Executor->>Model: 执行模型 Step
Model-->>Executor: text / reasoning / tool chunks
Executor->>Messages: 写入 Assistant 草稿与 Mutation
Executor->>Tool: 执行 Tool Call
Tool-->>Executor: Tool Result
Executor->>Input: 下一 Step 重新组装输入
Executor->>Messages: 提交最终 Assistant Message
Executor-->>App: turn.finished
```
运行时保证:
1. User Message 在模型调用前持久化。
2. 流式 Assistant 先写可恢复草稿。
3. Text、Reasoning、Tool Call 和 Tool Result 保持模型流中的 canonical 顺序。
4. 完整模型 Step 与 Tool 状态变化提交到 canonical history。
5. 中断后可以根据草稿和 Action 状态恢复。
## 状态检查点
同一 Session 只运行一个活跃执行循环。所有可能影响下一 Step 的输入进入同一有序队列:
- User Prompt。
- Workspace env 更新。
- Power registry 更新。
- Session model 更新。
- 显式 compact。
这些变化只在 Step 边界提交,不会在模型调用或 Tool 执行中途隐式改变当前上下文。正在执行的 Step 使用创建时的稳定 execution view。
模型解析优先级为:
```text
Session model > Agent model
```
Agent 和 Session 都持有宿主传入的模型实例,SDK 不根据字符串 model ID 选择或恢复模型服务。
## Composer 与 Executor
`SessionComposer` 负责模型上下文策略:返回基础 system blocks、本步动态 system 上下文、历史视图与 tools,并通过 `advance_context()` 推进自己的派生状态。默认 Composer 从当前 checkpoint 读取最新摘要,放入 `context_system_blocks`。
`StepInput` 冻结基础 blocks,每步将基础快照与 Composer 本次返回的动态 blocks 按顺序组装。`Executor` 使用这份输入发起模型请求、执行 Tool,并处理 abort、重试和上下文超限恢复。SessionLoop 负责队列和 Turn 编排。
这些组件不依赖 Session 的物理存储路径、Agent 列表或 HTTP/RPC transport。
## System Snapshot
基础 system 与动态 system 上下文有不同的生命周期:
- 首次组装:冻结 Agent 身份、instruction、core、Power system 与稳定 Session context。
- `snapshot()`:持久化当前基础快照。
- `syncshot()`:根据 Agent 当前指令与 Power system 重新生成基础快照;已有持久快照时同步覆盖,否则只更新内存。
Composer 的 `system` / `system_blocks` 属于基础指令,可选的 `context_system_blocks` 每步重新生成。`snapshot()` 和 `syncshot()` 都不固化动态摘要。
`system()` 预览与模型请求使用相同顺序:基础快照在前,最新动态上下文在后。Agent instruction 更新不会自动改写已有基础快照;checkpoint 摘要更新无需刷新基础指令。
## Message 与持久化
持久 Session 位于 City 提供的 Agent 存储作用域中;没有 City 时默认使用内存存储。默认本地 Session 包含:
```text
~/.downcity/agents//sessions///
├─ session.db
└─ attachments/
```
- `session_state.system_snapshot` 保存显式持久化的基础 system 文本。
- `messages` 与 `message_parts` 保存 canonical history。
- Composer 自己的派生表保存 checkpoint 摘要与边界。
压缩只改变模型请求的历史视图,不删除或改写 canonical history。恢复时分别读取基础快照与当前 checkpoint,历史视图从 canonical Parts 组装;没有基础快照时,从 Agent 当前 instruction 与 Power 重新生成基础指令。
模型流的普通 chunk 用于实时展示与内存组装;完整模型 Step、Tool 状态和 Message 收口等稳定语义检查点提交到 SQLite。调用方通过 `session.messages()`、`get_info()` 和 `system()` 读取结构化状态。
## 实时观察
`subscribe()` 只发送订阅后发生的 Mutation:
```ts
const unsubscribe = session.subscribe((mutation) => {
if (mutation.variant === "delta" && mutation.type === "text") {
process.stdout.write(mutation.delta);
}
});
```
Mutation 包括完整 Message、Assistant Part、文本/推理增量、Turn 状态和 Session 状态。断线后应先用 `messages()` 重新加载 canonical 快照,再建立新订阅。
## Power runtime
Power 属于 City,不属于 Agent 或 Workspace。City 按 Power ID 持有唯一实例,并向每个 Agent/Workspace 执行入口投影 Action、System、Hook、Resolve Point 与 HTTP 路由。
PowerRegistry 的投影变化在 Session 检查点生效。单个 Power 初始化失败只隔离自身,不阻断其他 Power。Agent 关闭时停止 Session 与 ActionSchedule;Power 的 `initialize/dispose` 生命周期由 City 收口。
ActionSchedule 是 Agent 持有的本地延迟 Power Action 调度器。事件存放在 Agent 的存储作用域中,Agent 重启时会把遗留的 running 状态恢复为 pending。它不是分布式调度系统,也不提供跨机器选主。
## City Power
每个 Agent 都会获得三个 City 自有 Power。它们既是「harness 自己知道、模型无法从文件或命令读到」那类运行时事实的出口,也承载 City 自己持有的生成能力。
```jsonc
{ "action": "sandbox.explain_path", "args": { "path": "~/.downcity/powers/messenger" } }
```
| Power | 动作组 | 回答什么 |
| --- | --- | --- |
| `context` | `env`、`sandbox`、`workspaces`、`usage` | 本轮跑在哪个 Agent、Session、Workspace、模型、时区与本地日期下;这个 Session 跑在哪个沙箱后端与实例里、挂了哪些宿主目录、某个路径为什么被拦;当前 City 中登记的全部 Workspace;user 级 token 用量 |
| `ai` | `image`、`sound` | 生成图片;转写音频与合成语音 |
| `agent` | `agent` | 当前 City 中登记的全部 Agent |
动作 id 是 `组名.动作名`,与所属 Power 名无关:`env.get` 属于 `context`,`image.*` 与 `sound.*` 同属 `ai`。不带参数调用一个 Power 会列出它的全部动作;这里不会返回凭据的值,而且每个动作都声明了 `read` 或 `write`,因此调用前就能看出哪些会消耗额度或改变状态。
可用性与 Power 同一口径:City 注册了什么,每个 Agent 就都能用,没有 per-agent 门控,也没有配置文件。
### Image 与 Sound
两者都使用你的 Federation 账号可用的模型,因此没有单独配置,也不需要设置。因为没有预设默认模型,
要么显式传 `model`,要么让模型从 `image.models` / `sound.models` 里选;`asr` 与 `tts` 在未指定时
会取第一个可用模型。
生图是两步式任务:`create` 返回 `job_id`,`result` 读取它。生图会消耗额度,所以模型必须先与你确认。
`result` 把生成的图片写入 Power 私有目录并返回本地路径,在回复里用 `` 引用即可。
入站语音消息的自动转写属于 Messenger Power:当渠道送来语音或音频附件时,由它调用 `ai` Power 的 `sound.asr`。
单个附件转写失败不影响消息送达。
## 安全模型
安全边界分为两层:
| 能力 | 强制边界 | 权限语义 |
| --- | --- | --- |
| File/Search Tools | Rooted LocalFileSystem | 只能主动访问 Workspace |
| Sandbox Shell | Workspace Sandbox | 命令在当前 Workspace 独享、持久的隔离环境中执行 |
| Host Shell | 审批网关 | 用户基于已记录的原因显式授权一次宿主命令 |
| Power | Power 自身业务授权 | Workspace 不替 Power 负责全部资源访问 |
| City Power | 按动作声明区分 | 只读事实查询与已声明 `read` 的动作;`write` 动作会消耗额度或在 Agent 目录下写文件 |
| Custom Tool | 注册它的宿主 | Agent Core 不猜测业务权限 |
显式附件可以使用宿主选择的绝对路径,因为附件已经是本次 Prompt 的明确输入。这不会扩大模型 File/Search Tools 主动遍历文件系统的范围。
## 跨平台策略
Node.js 已经统一文件、路径、网络、JSON、Timer、AbortController 和普通子进程能力,所以 Agent、Session、Store 与 Workspace 不写操作系统分支。
隔离实现差异统一收敛在中立的 Sandbox Provider 协议内。每个 Shell 显式接收 Provider,并持有绑定 Workspace 时创建的独立、持久 Sandbox。City 只管理 Workspace 资源,不理解其 Shell 使用本地容器、microVM、远程主机还是其他后端。默认实现使用 microsandbox microVM。
## 生命周期
```mermaid
flowchart LR
Agent["new Agent"] --> Register["City 注册 Agent"]
Power["City 注册 Power"] --> Initialize["Power initialize"]
Register --> Running["执行 Session"]
Initialize --> Running
Running --> Close["city.close()"]
Close --> Sessions["停止 Agent Sessions"]
Sessions --> Dispose["Power dispose"]
Dispose --> Workspace["释放 Workspace / Shell"]
```
Session 执行前会等待 Agent 的 City 执行绑定就绪。`agent.dispose()` 不停止 City Power 实例;`city.close()` 统一关闭 Transport、Agent、Power、Workspace 与 Shell,并保证活跃 Hook/Action lease 先收口。
继续阅读:[Agent 生命周期](/zh/docs/agent/lifecycle)。
### Agent 生命周期
Source: https://downcity.ai/zh/docs/agent/lifecycle/
`new Agent(options)` 只创建 Agent 身份、模型、指令、自定义 Tool、Session 集合与 ActionSchedule。Power 不属于 Agent;City 注册 Agent 后,把自己持有的 Power 能力投影到 Agent 的执行入口。
同一个 Agent ID 在同一物理 Workspace 中只能运行一个活动 runtime。ActionSchedule 是本地调度器,不负责协调重复启动的 Agent 进程。
```ts
import { Agent } from "@downcity/agent";
import { City, Shell, Workspace } from "@downcity/city";
import { MicrosandboxProvider } from "@downcity/sandbox-microsandbox";
const shell = new Shell({ sandbox_provider: new MicrosandboxProvider() });
const agent = new Agent({
id: "my-agent",
model,
});
const workspace = new Workspace({
id: "project",
path: process.cwd(),
shell,
});
const city = new City({ agents: [agent], workspaces: [workspace] });
const session = await agent.sessions.create({ workspace });
const turn = await session.prompt({ query: "开始" });
await turn.finished;
await city.close();
```
Session 会在执行前自动等待 Agent 的 City 执行绑定就绪。`agent.dispose()` 只释放 Agent 自身的 Session、ActionSchedule 与执行绑定;`city.close()` 会先停止 Agent Session,随后停止 City 持有的唯一 Power 实例,并关闭 Workspace、Shell 与 Transport。
继续阅读:[Agent SDK](/zh/agent-sdk-docs)。
### Power
Source: https://downcity.ai/zh/docs/power/overview/
**Power(Power)** 是 Downcity 唯一的扩展产品单元。它由 City 提供和维护,可以向 Agent/Session 作用域投影运行能力,也可以带上宿主管理逻辑、Sidebar + Mainview 业务工作区和 Config。
```text
Power
├── main 可选:City 运行实例、生命周期、管理逻辑与 actions
└── renderer 可选:Sidebar + Mainview 和/或 Config
```
## Power 能做什么
- 向 Agent 暴露可调用的工具
- 接入 City Power 生命周期(initialize、dispose)
- 管理自己的状态、连接和后台任务
- 提供 Sidebar + Mainview 工作区,并在 Catalog 详情的独立 Config 中管理配置
- 在 City 进程边界内运行,不作为独立服务
一个 City 中每个 Power ID 只有一个实例和一份配置。配置由宿主持久化,并在每次执行时作为
`PowerContext.config` 快照提供给 Power;Agent 不持有 Power、配置或生命周期。多账号由
Power 自己的配置结构表达,不存在通用命名配置层。
## 内置 Power
Downcity 内置了多个 Power,覆盖常见的 Agent 需求:
- **Chat** — 连接聊天渠道(Telegram、飞书、QQ 等)
- **Task** — 调度和运行后台任务
- **Memory** — 持久化会话历史和上下文
- **Shell** — 在沙箱环境中执行本地命令
- **Schedule** — 类 Cron 的作业调度
- **Web** — 浏览网页并提取内容
- **Skill** — 组合可复用的工具链
## 编写 Power
SDK 中可以直接向 City 提供 Power 实例,不需要经过安装协议:
```ts
const city = new City({ powers: [github_power], workspaces: [workspace] });
city.agents.add(agent);
```
需要被 CLI 或 Desktop 安装和管理时,再通过 `power.json` 声明统一 `main` 与可选 `renderer` 入口。
## 继续阅读
- [Agent Powers Docs](/zh/powers-docs) — 内置 Power 手册和示例
- [Agent SDK](/zh/agent-sdk-docs) — 如何在代码中注册和使用 Power
- [自定义 Power](/zh/docs/power/custom) — 可安装 Power 的统一 main 协议
### Messenger Power
Source: https://downcity.ai/zh/docs/power/messenger/
Messenger Power 是 City 持有的渠道运行时。它不属于某个 Agent,也不通过 `context.agent.chat` 暴露长期状态。
## Desktop 使用
打开 Messengers 后,左侧 Sidebar 会列出全部 Bot Account。点击 Sidebar 标题栏中的加号,从下拉菜单选择 Telegram、飞书/Lark 或 QQ 后创建对应的 Bot Account。可以添加多个同平台 Bot Account。选择飞书/Lark 时默认使用扫码创建,不需要手动填写 App ID 与 App Secret。
点击一个 Account 可以管理:
- 启用状态、平台凭据与连接测试
- 新 Conversation 默认绑定的 Agent
- 外部身份的 Access 申请与授权
- 每个 Conversation 的 Agent、Channel Session 与暂停状态
- 达到自动重试上限的 Inbox/Outbox 任务
- 不包含消息正文和密钥的 Activity
在 Desktop 保存 Account 后立即应用,只重启该 Account 的 Connector,不需要重启 Desktop 或 City,其他 Bot 连接不受影响。密钥可以直接在 Settings 中写入;已保存的密钥不会回显,编辑时留空表示保留原值。
:::callout
Telegram 等平台在部分网络环境下需要代理才能访问。只要在系统或 Desktop 中开启代理,Channel 会自动使用,无需额外配置。
:::
### 网络与连接
Telegram、飞书与 QQ 的请求都经过 Power 统一出站层,行为一致:
- 每个请求都有整体超时,不会无限挂起。连接失败时 Account 会进入 `错误` 并直接展示原因。
- 代理优先级:Desktop 网络代理设置 → 操作系统系统代理 → `Global / Env` 中的 `HTTPS_PROXY` 等变量。macOS 开启系统代理后 Power 会自动继承,系统例外列表会转换为 `NO_PROXY`。
- 代理变化(包括开系统代理 / 连 VPN)后,Desktop 会在 30 秒内自动重新解析并重连已启用的 Channel,无需重启。
- 只支持 `http://` 或 `https://` 代理地址;`socks5://` 会直接报错并提示改用 http 地址。`NO_PROXY` 支持主机名、`.example.com`、`*.example.com` 与 IPv4 CIDR。
- 连接意外失败后会自动按退避重连(最长 5 分钟一次),成功后退避重置。Account `未连接` 时 Outbox 只延后发送,不消耗重试次数。
如果 Account 一直停在 `连接中`,先点一次“测试连接”;仍失败时,界面上的错误文本会给出具体原因(例如代理不可用或目标不可达)。
### Agent 附件展示
Agent 使用 `reports/daily.md` 输出附件,标签内填写当前 Workspace 的相对文件路径。Desktop 聊天会按正文顺序展示附件:文档显示文件入口,`photo` 显示图片,`audio`、`voice` 和 `video` 显示播放控件。本地媒体通过 Desktop 受控文件协议加载,点击文件入口沿用聊天文件导航。
代码块、行内代码和转义的标签保留为示例文本。流式输出中的标签尚未闭合时保持可读,闭合后转换为附件。标签内不要写 Markdown 链接或 `http://文件名`;这类内容会显示格式错误并保留原始标签。媒体无法预览时保留文件入口。附件使用统一卡片展示文件类型与名称,长文件名悬停可查看完整路径;格式错误的原始标签收在“查看详情”中。
## Account 配置
Account 定义与密钥以 City Power Config 为唯一事实源。示例:
```json
{
"accounts": [
{
"account_id": "support-telegram",
"name": "Support Bot",
"provider": "telegram",
"enabled": true,
"agent_id": "support",
"bot_token": ""
}
]
}
```
飞书/Lark 使用 `app_id`、`app_secret` 和可选 `domain`;QQ 使用 `app_id`、`app_secret` 和可选 `sandbox`。
在 Desktop 中添加飞书/Lark Channel 时默认走扫码创建:点“扫码创建”,用飞书扫描二维码并在手机上确认,App ID 与 App Secret 会自动写入并立即启动,不需要到开放平台手动复制。确认页会预填应用名称与描述,并勾选本渠道需要的权限点和 `im.message.receive_v1` 事件。
扫码基于 OAuth 2.0 Device Authorization Grant(RFC 8628),只允许创建新应用,不会覆盖已有应用的配置。二维码有效期以平台返回为准(当前约 1 小时),过期后可以重新生成。无法扫码时(例如企业未开启开发者权限,或需要复用已有应用),在同一页面切换到“手动填写凭据”即可。
## 消息与 Session
允许访问的外部消息先写入 Inbox,再由 Conversation 路由到独立的 Channel Session(`category = "chat"`,`type = "channel"`)。每个 Bot Account 下的聊天及 Thread 各有一条 Session,同一聊天后续消息复用它。不同聊天的历史彼此独立,也与 Agent 主对话分开。Session Messages 是完整对话的唯一事实源。
IM 只绑定 Agent,不需要选择 Workspace。Desktop 中 Channel Session 与 Agent 主对话默认共享该 Agent 的主 Workspace(`agents//main`),具备相同的 Workspace 工具、Power、Agent 自定义工具和 Session 管理工具。对话历史分别保存,文件与 Shell 使用当前 Workspace。可通过 Session 管理工具创建项目 Work Session。SDK 宿主通过 Agent 的 `workspace` 提供默认主上下文。账号未配置 Agent 时,仅在 City 中 Agent 唯一时自动选用。
切换 Conversation 的 Agent 或重置对话会创建新的 Channel Session,原 Session 保留。升级前的 IM Work Session 也保留,升级后聊天从新建的 Channel Session 继续。附件接收保存到 Messenger 自有目录;发送时可使用该目录及 Session 当前项目目录。
可靠链路为:
```text
Platform → Access → Inbox → Conversation → Channel Session
→ Outbox → Platform
```
Inbox 使用平台消息 ID 去重,并以稳定 `request_id` 调用 Session。进程在 User Message 落盘后退出,恢复时不会追加第二条用户消息。Agent 结果以稳定 Delivery ID 写入 Outbox,避免恢复时重复建单。
Outbox 提供持久化、lease、有限重试和人工恢复。平台本身不支持幂等发送时,对外语义是 at-least-once:平台已接收但本地尚未记录确认的瞬间退出,恢复后可能再次发送。
## Agent Actions
Agent 只看到自己拥有的 Conversation,并使用严格输入的 Action:
- `context`:读取当前 Chat Session 路由
- `list`:列出当前 Agent 的 Conversation
- `history`:读取 Agent Session 的 canonical messages
- `send`:将文本写入可靠 Outbox
- `react`:为 Telegram 消息写入可靠 Reaction 操作
## SDK 装配
```ts
import { MessengerPower } from "@downcity/powers/messenger";
const city = new City({
powers: [new MessengerPower()],
workspaces: [workspace],
power_host,
});
```
Messenger Power 需要 City 宿主提供 Power Config、生命周期 Storage 和 Agent Session 能力。Bot Connector 在 `initialize()` 中主动恢复,在 `dispose()` 中统一关闭。
## 飞书依赖
启用飞书/Lark Account 的宿主需要安装:
```bash
npm install @larksuiteoapi/node-sdk@^1.73.3
```
扫码创建依赖 SDK 的 `registerApp`,需要 `^1.67.0` 及以上版本;低于该版本时扫码入口会提示升级,手动填写凭据仍然可用。
## 相关文档
- [Power Lifecycle](/zh/agent-sdk-docs/powers/lifecycle)
- [Built-ins Overview](/zh/powers-docs/builtins/overview)
### Task Power
Source: https://downcity.ai/zh/docs/power/task/
{/* 用户文档:区分 Todo 与 Schedule 外壳,执行仍由 City 中的 TaskPower 负责。 */}
进入 Desktop 的任务页面,在 Sidebar 切换**备忘录、需要我处理、列表、看板、日历、时间线**;下方保留需要关注的任务。主区域顶栏统一提供集合操作。宽屏选中任务后,在集合旁打开详情,可以连续选择其他任务;窄内容区自动进入详情,返回后保留集合位置。详情支持主动展开与关闭,搜索、筛选、排序和日期位置继续保留。
四种视图共用搜索与完成状态筛选,切换视图时保持同一集合;列表和看板另支持字段排序。侧栏关注队列优先显示待验收、失败、整理中和执行中的任务,并保留当前选中任务。查找完整任务集合使用主区域搜索。
Sidebar 的“备忘录”直接使用 Tiptap 编辑器和官方 TaskList、TaskItem,空文档默认从 Todo 开始。正常书写、Enter、退格、嵌套与粘贴遵循编辑器本身的行为,可以退出列表写段落、标题或代码,不把内容主动拆成业务任务。整篇文档自动保存,复选框仅属于文档;录入、选择和勾选都不会调用模型或启动 Agent。
备忘录自动保存到当前 Desktop 的本机浏览器存储,切换视图或刷新后可恢复,不等于云端同步。保存失败时显示错误并保留当前页面内容,可复制备份并重试;无法读取的损坏存储不会被空文档覆盖。
选中文字后,选区旁显示“想怎么处理?”;直接输入“整理一下”“解释这段”“记成待办”或具体委派要求,再发送,无需离开文档选模式或重看原文。“整理”“改写”和“提取待办清单”等文字处理只返回选区附近的预览,不创建业务任务;用户明确点击“替换选中文字”才写回,并支持撤销。处理期间原文被编辑或删除后会禁止替换,结果仍可复制,避免覆盖其他文字。
只有明确要求创建、记录、排期或委派工作,才将原选区与用户要求一起交给现有任务流程。任务在选区附近显示关联入口,不自动跳页;备忘录原文保留。文字处理使用设置中的默认文本模型,不具备工具执行权限。选区原文与处理要求合计最多 24,000 字符,超限提示缩小范围,不静默截断。
左侧圆点支持个人一次性任务的完成与未完成切换;Agent 交付需先查看结果再验收,循环启停不等于工作完成。右侧 `···` 菜单按当前状态提供在录入窗口调整要求、开始或重试执行、查看详情、重新打开、循环启停与删除。运行中限制编辑、删除和重复执行;删除会要求确认。字段保存失败保留修改,成功后直接应用执行目标或安排变更。
默认排序将未完成任务放在前面,按最近执行或计划时间排列,无时间项放后面,已完成或取消任务置后。点击名称、类型、状态、执行者、时间表头切换升序/降序,箭头表示当前方向;时间按实际时刻比较,循环使用下次可计算触发时间,暂停或无法预测的循环在时间排序中置后。相同值以创建时间和任务 ID 稳定排序。列表和看板共用排序工具行,可选择默认排序、字段及升降序,列表表头与工具行同步。
## 界面层次
所有 Mainview 共用窗口顶栏、内容边距、局部工具行高度和正文起点。列表与看板的工具行展示集合信息和排序;日历与时间线使用同一日期导航组件,日历的周/月属于局部日期范围控制。工作台使用中性背景、统一字体层级、细分隔线和控件规格组织信息,颜色集中在状态点、窄状态条与异常提示。列表分为“未完成”和“已完成”,各有数量与表头;看板以列标题、数量和浅底卡片呈现工作阶段。日历和时间线使用细网格、今日标记与明确时间位置。任务录入按需打开,让主视图获得完整空间。深浅主题共用语义令牌,交互保留悬停、选中与键盘聚焦反馈;浮层使用不透明主题底色。
## 展示方式
Sidebar 是任务视图导航的唯一入口,切换时关闭选中详情并显示对应视图。主区域顶栏统一提供集合操作,下方工具行负责日期或排序。集合和详情各自滚动;宽屏展开正文时暂时隐藏集合,收起或关闭可回到原位置。侧栏关注队列帮助定位需要处理的任务。
“需要我处理”展示任务中未解决的待验收交付、提醒、失败、错过安排和整理问题。选择事项打开对应任务或具体交付,不完成、不验收,也不清除它。普通通知列为更新,明确点击“标为已读”只清除通知,不改变任务。事项已经阅读但尚未解决,仍会保留在队列中。当前 Task 接口尚未提供运行中的问题答复与恢复通道,工具审批仍通过原执行会话处理。
看板按待开始、进行中、待处理和已完成展示;循环任务同时显示启停状态,不把启用规则当成执行中。卡片名称打开详情,时间字段原位编辑,右侧菜单与列表共用快捷操作;循环卡单独标明启停,本次完成不结束循环。当前不提供拖拽跨列修改。
日历默认使用月视图,可切换周视图。页面使用中性底色、细日期网格,任务只展示时间与标题,今天以日期圆点标记;月视图按本月实际跨度显示完整周,周末任务同样保留。月格先展示三条日程,“另 N 项”原位展开,其余任务不会被隐藏。周视图显示完整日程,按真实开始时间排列,不用条目高度表示执行时长。
点击日程打开轻量预览,在预览中查看执行者、状态和完整起止时间,可修改时间或明确打开完整任务正文;关闭预览保留日历位置。循环状态按对应发生记录读取,未来安排不会继承历史完成状态。一次性计划可拖到其他日期,保留原时刻与时长;循环和截止不提供拖拽编辑。顶栏“记一条”跳转备忘录,日期内的加号或双击空白区域带入该日;该日期仅在之后明确记录为任务或交给 Agent 时应用,不因写备忘就触发提醒或执行;加号在悬停、键盘聚焦或触屏设备上可见。日历按本机时区显示,跨日范围按实际占用日期列出,不为时间点补造时长;未安排、范围外或无法展开循环的任务可从底部返回列表查看。
时间线展示两周范围,可前后翻页;任务名称列和日期表头固定,今天以竖线标记,范围外任务可点击方向提示定位。计划时间段显示横条,时间点显示独立菱形标记;循环任务展示下次可计算的触发时间。无时间、暂停循环或无法预测的高级规则列在下方,可打开详情处理。时间线当前用于查看,不提供拖动编辑或依赖连线。
## 待办
备忘录中的 Todo 就是 Tiptap 文档里的复选项,没有独立任务身份、行内菜单或任务状态联动。用户明确处理所选内容后,才产生可跟踪任务;来源文字与任务链接放在文档外记录。编辑或勾选文档不改变已生成任务,验收仍在任务详情完成。
Todo 是一次性工作,可没有时间、指定一个时间点,或设置计划起止时间段。时间点可以按用户要求提醒或执行一次;只有计划时间段时不会自动持续运行。截止日期不自动启动 Agent。自己的待办可以从列表完成并撤销;Agent 返回结果后可以“完成待办”或提出修改要求。
如果保存成功但开始失败,窗口会提示“待办已保存,尚未开始”。再次开始使用原对象,不重新创建待办。
## 定时安排
Schedule 用于循环工作,基于 Cron 规则与时区。选中备忘内容并明确要求 Agent 安排“每周一让研究员整理动态”可以生成循环任务;“明天九点提醒我”可以生成一次性提醒。只把这些句子写在备忘录里不会启用任何安排。
循环任务详情显示时间摘要和启停开关,详细设置收在“更多”。暂停不停止正在执行的工作;本次成功不会结束循环。
个人提醒到时产生待处理提醒,不运行 Agent。时间段由 planned_at 与 planned_end_at 保存,结束必须晚于开始,不代表重复或持续执行。自动触发需要 City 保持运行;错过的一次性 Todo 需要用户处理,离线周期不会集中补跑。
## 创建接口
保留 `task.create()` 与 `task.generate()` 两个入口。Agent 已掌握标题、正文和时间等结构化字段时优先使用 `create`,直接校验保存,跳过内部模型。Task 页面输入自然语言时使用 `generate`,Agent 也可按需调用。页面与 Agent 共用同一个生成动作。
`generate` 传入 `text` 新建,传入 `task_id` 与补充内容调整原任务;调用等待整理完成并返回完整任务。新提交重试复用 `submission_id`。成功后直接保存并生效,无需确认;仅记录任务不会启动,明确要求立即执行才开始,定时和循环工作按规则触发。`create` 的手动任务通过 `run` 启动。模型失败保留任务身份和原因,可在原任务上重试。时间校验统一处理格式、时区和过去时间;相对日期按本次生成时间解析。
## 直接输入与保存
备忘录按“写下来 → 自动保存 → 明确处理所选内容 → 查看关联任务”组织。记录和勾选不触发任务或 Agent。处理面板中只有用户明确的动作才创建任务;已生成任务保留原文关联,即使后续整理或调度失败,也可进入原任务调整。
已有任务的“调整要求”仍在原任务或调整浮层中继续,不与自由书写的备忘录混用。调整窗口的“直接写入任务”只替换原任务正文,保留标题、执行者和排期,不启动执行;AI 方式解读补充要求。备忘录中的处理结果留有任务入口,关联任务与交付不随本地原文的编辑而删除。
系统根据完整输入区分待办与循环安排,当前列表筛选不限制生成类型。截止日期不自动触发执行。任务保持同一身份,标题可修改和重复。
## 任务正文与历史
点击侧栏任务行或集合中的任务名称,在当前任务工作区打开详情。宽屏保留集合,窄屏使用带返回的详情;详情可主动展开。任务要求默认可读;已有结果优先在本任务内展示,并可在原处验收、提出修改或查看失败原因。工具日志与错误细节按需展开,运行结束不自动代表任务完成。
列表不再按内部状态或类型拆成多个区块。旧任务也保留在同一列表中,底层身份和历史不变。查看通知不等于完成或验收。
执行历史先显示最新一页,点击“加载更多历史”查看更早记录;数量表示已加载次数。刷新进度时保留已加载历史和当前选择。从事项打开较早执行时,直接在任务详情定位该次交付,无需先加载此前所有历史。
## 结果、修改与失败
引用在输入框、队列和已发送消息中使用统一紧凑 Block。任务交付显示任务名称与结果摘要;聊天消息、文件内容、代码选区使用各自的图标和来源信息。点击引用可展开完整正文,编辑中的删除按钮位于右侧,只读消息不显示删除按钮。样式无阴影或装饰边框,展开与摘要不改变实际发送的完整上下文。
交付结果提供两个操作:“复制任务引用”同时复制结构化 HTML 与可读纯文本;粘贴到 ChatInput 恢复任务引用 Block,粘贴到外部应用可读取任务来源与完整正文。引用 Block 自身也有“复制引用”,编辑器选中引用后可用系统复制;纯文本粘贴或代码块内粘贴按普通文字处理;“继续任务”使用任务的 Agent 与 Workspace 打开工作区新对话,并将当前交付作为结构化引用带入 ChatInput,无需预先打开会话,也不自动发送。对应新对话已有草稿会保留并追加引用;新 Session 按应用原有新对话流程在发送时建立。执行者或工作区不可用时在原处提示修正,不任意换目标。
执行结果和历史保留在原对象。一次性 Agent 工作需要人工接受;周期结果遵循逐次验收设置。
明确验收和带反馈的修订会随工作状态原子保存为可重放事实,保留对应结果、原 Agent/Workspace 与有界来源快照。执行成功、打开结果和普通完成操作不产生验收事实。官方 Power 组合允许 Memory 读取这些事实,后台整理默认关闭,需在 Memory 中按范围启用;Task 材料默认保持原 Agent 私有。删除任务前会归档已发布的命令事实,再删除任务定义与执行目录;删除任务不等于清除所有来源副本。
在任务内交付区点击“需要修改”填写反馈,再点击“提交并开始修改”,保存反馈并启动属于同一任务的后续执行。若保存成功但启动失败,反馈仍保留,可从“开始修改”重试,无需再次提交反馈。旧结果和反馈保留;循环任务的本次反馈不自动改写固定要求。
执行失败可以重试,AI 整理失败则重试整理。内容已保存但自动安排同步失败时,显示“安排尚未生效”,可重试同步,不重新调用模型。
Agent 任务的执行会话是 Work Main,可把独立工作派给多个 Work Child,并在原执行内汇总结果;Child 与模拟评审器不能继续派发。Main 等待期间仍可接收补充,并向 Child 传达要求。Child 的公开问题会通知 Main,待处理状态保留在 Child 原交互中;Main 可向用户询问并转交真实回答。审批和 secret 问题只在原受信入口处理,Main 不能代批准或搬运私密答案。
City 重启发现中断工作时会保留历史并提示处理,不自动重放执行。Shell 长任务开启 `auto_notify_on_exit` 后会自动回投原执行;原执行停止后,迟到结果不再唤醒它。重启只恢复已保存完成结果的投递,不能接管的进程报告中断或状态未知,不自动重跑命令。运行中的任务暂时需要等待结束后再编辑定义或删除。
从聊天创建时,结果交付位置由来源会话捕获;更换执行者不会移动交付目标。原 Chat Turn 正常结束或被停止后,结果仍可排队返回该 Chat 异步处理。停止 Chat 当前回复不会取消后台 Main;显式停止 Main 才会级联停止其 Child。任务需要发送外部消息时,应明确要求执行 Agent 使用 Messenger。
继续阅读:[Messenger Power](/zh/docs/power/messenger)、[Agent Powers Docs](/zh/powers-docs)。
### Memory Power
Source: https://downcity.ai/zh/docs/power/memory/
一份 Downcity 平台数据根对应一个本地 User,独立于 Federation 登录账号。City 管理基础资料,MemoryPower 管理用户记忆和 Agent 记忆。
## 每轮上下文
首次组装或 syncshot → 读取两级 Profile → 与 Instruction 一起冻结完整 system → Agent 处理消息并按需调用工具。
User Profile 跨本地 Agent、跨 Session 生效;Agent Profile 仅对指定 Agent 生效。Identity 与 Instruction 合并为 Agent system,Agent Profile 紧随其后;User Profile 作为另一条 system 放在 Session 信息之前,不混入 User 原文,参与完整 system 快照。新 Session 和 syncshot 读取完整最新 Profile;已有 Session 的 system 保持冻结,核心版本变化通过本轮有界参考更正提供。更正会明确停用该范围的旧快照;正文过长时只提供有界内容,未展示部分须重新读取或刷新完整快照。Profile 是历史约定,不能定义本轮任务或覆盖当前请求和权限。
## 保存
```json
{"target":"user","mode":"profile","content":"主回答前提醒我使用英语,我写英语时简要纠正表达。"}
```
remember 的 target 为 user、agent、current_workspace;mode 为 profile 或 knowledge,默认 knowledge。Profile 支持 User/Agent;Workspace 仅支持 knowledge。User 写入无需登录或身份回调。Agent 自己判断何时调用工具,只有成功后才能确认已保存。
## 文档与维护
`user/user.json` 保存本地用户资料;`user/PROFILE.md` 保存全局持续约定;`agents//PROFILE.md` 保存 Agent 专属约定。长期知识由各范围已发布的 manifest 管理,search/read/list 只读取当前有效集合;User 知识保存一次供本地 Agent 共享。Profile 使用独立文件、范围锁和 pending 恢复,不属于知识 manifest,也不与知识提交构成同一原子事务。
运行时不会自动迁移或回退读取旧 wiki。已有记录需要通过 SDK 级 `create_memory_import_changeset` helper 显式构造导入变更集,再由 Provider 提交;导入前确认来源、范围和备份。
两级 Profile 通过确定性的读取、追加和精确编辑接口维护。写入携带基础版本与可信来源,同一请求重试不会重复追加;版本冲突需重新读取。精确编辑校验唯一匹配、不重叠和来源标记,并在正文变更前保留备份。需要整理时,显式调用 `memory.optimize` 并指定 `target=user` 或 `target=agent`,由 Memory Coordinator 提交专用 Memory Session 的优化 Job。长度读取仅帮助判断是否值得整理,不会自动触发。Profile 文件服务不调用模型,也不运行定时优化。
`digest`、`revise` 与 `optimize` 异步执行,返回 Job ID。从 Session 发起时,会为原调用 Session 与 Turn 订阅最终结果,反馈成功、无需变更或失败。`digest` 的接收方是调用 Session,可以与被提炼的来源 Session 不同。原轮次可接收时注入反馈;原轮次已结束则保留处理记录供查询,不自动新开轮次。完成反馈持久化并幂等处理:`delivery_status=delivered` 表示已注入,`delivery_status=saved` 表示仅保留结果并结束投递。投递失败会退避重试,不改变记忆提交状态。管理页请求没有聊天接收方。需要时通过处理记录查询结果,不要反复轮询,也不要重复确认同一 Job 已经反馈过的保存结果。
使用 `memory.jobs` 查看当前 Agent 与 Workspace 的分页处理记录,`memory.job_status` 查询具体请求,`memory.retry` 重试失败记录。列表和状态不包含来源正文。查看差异与依据时,调用 `memory.job_detail`,输入 `{"job_id":""}`;详情端点按当前 Job 的 Agent/Workspace 范围校验,返回 `{job, changes}`,其中包含该请求持久化的授权来源摘录;列表和状态不含来源正文。管理页的「处理记录」展示固定的变更前后正文、本次实际读取版本和原始来源摘录;Profile 只展示精确编辑区域。快照描述本次操作,不代表当前最新正文;未保存快照的记录返回空变更列表。
只有 `succeeded` 确认提交完成,`skipped` 表示无需变更。详情中的待处理或失败差异不能视为已经生效。同一请求范围内,对同一 Profile 版本重复整理使用稳定来源标识;相同来源快照与提炼策略的 digest 复用处理请求,无关知识变化不会产生另一份 digest 请求。
不会逐轮复制聊天或自动采集每轮消息。遗忘知识使其退出当前有效集合,并以规范化正文的精确指纹抑制相同内容重新提交;不保证阻止同一事实的语义改写。删除 Profile 会停止使用当前正文,备份、原始 Session 和 Job 中的来源正文副本仍保留;这些操作不代表清除所有历史副本。切换服务账号不会切换用户记忆;外部渠道访问权限由宿主控制。
## 后台整理
Memory 的「后台整理」页提供按 Agent、Workspace 和知识归属控制的开关,默认关闭。可信输入仅为直接填写的明确纠错,以及官方 Power 组合接入的 Task accept 和带反馈的 revise 命令事实。执行成功和 Turn 结束不表示验收,也不会自动导入私人 Session 历史。Task 事实与验收状态原子保存,删除任务前归档固定来源;不因此清除所有来源副本。
维护检查每五分钟运行,空队列不调用模型。每批固定一个 Agent 和一个目标,最多 4 个事实、16 个来源、32,000 字符;每个范围按 UTC 日期最多预留 2 次自动计算,重试也计入,两次至少间隔 10 分钟。显式请求在每个 Job 边界优先。关闭阻止新自动计算,已开始的有界工作可完成。
自动结果只写 Agent/Workspace 知识;Task 材料默认保持 Agent 私有,项目共享需要明确允许。不自动修改 Profile 或写 User 知识。页面可查看积压、接收与连续处理水位、延期、错误、来源边界、批次和对应 Job。只有核对提交回执的 succeeded 或明确 skipped 才标记输入已处理,失败和预算延期继续保留。自动批次从此页重试;普通 memory.retry 处理显式请求的失败。后台没有聊天接收方,提交成功不代表摘要已投递。
- [完整 Memory Power 文档](/zh/powers-docs/builtins/memory)
### MCP Server
Source: https://downcity.ai/zh/docs/power/mcp/
MCP 由内建 Skill Power 统一管理。Sidebar 按 Skills 与 MCP 列出具体资源,选择 Server 后查看状态、工具与错误。Server 定义在 Skill Config 中管理。已有 Server 定义与 OAuth 凭据仍保存在全局 MCP 存储目录,由所有 Agent 和 Workspace 共享。
在 **Agent Profile → Skills** 中为 Agent 启用 Server。访问必须经过明确分配,分配关系以 Server ID 的 JSON 数组保存在 `~/.downcity/agents//mcp-servers.json`。文件不存在时没有访问权限;仅全局启用 Server 不会授予权限。移除分配不会删除共享定义和凭据。宿主动作 `skill.mcp.assign` 与 `skill.mcp.unassign` 接受 `{ agent_id, server_id }`,不暴露给模型。
## 配置 Server
每个 Server 默认使用一个 `~/.downcity/powers/mcp/servers/.toml` 文件,文件名就是 Server ID。如果宿主使用其他 MCP 配置路径,`servers` 位于该配置文件的同级目录:`dirname(config.path)/servers`。
已安装的本地 stdio Server 示例:
```toml
title = "Filesystem"
enabled = true
command = "mcp-server-filesystem"
args = ["/absolute/allowed/directory"]
cwd = "/absolute/working/directory"
env = { LOG_LEVEL = "info" }
request_timeout_ms = 60000
max_result_chars = 100000
```
命令和参数需要替换为实际 Server 要求的值。Streamable HTTP Server 示例:
```toml
title = "Remote MCP"
url = "https://mcp.example.com/mcp"
headers = { "X-Client" = "downcity" }
```
`command` 和 `url` 必须且只能填写一个非空值。本地程序使用可选的 `args`、`cwd`、`env`,HTTP 端点使用可选的 `headers`。配置没有 `source`、`install`、`transport` 分层。`title` 可省略;`enabled` 默认 `true`;可选的 `request_timeout_ms` 和 `max_result_chars` 默认分别为 `60000` 毫秒和 `100000` 字符。需要项目目录的 Server 应明确填写 `cwd`,共享连接不会继承调用者的 Workspace。参数、工作目录、URL 和请求头中的 `${NAME}` 从宿主环境读取变量。
Desktop 编辑器直接读写每个 Server 的真实 TOML 文件,每个 Server 都需要明确点击保存或删除。文件修改会以读取时的原文(`expected_content`)检查冲突;若文件已被其他编辑修改,会拒绝本次操作,防止过期内容覆盖新内容。此时应重新读取文件后再保存。
初始化、定义读取和单文件保存都只扫描、校验定义,不启动或连接 Server。普通手动文件编辑可通过 Config 重新读取发现,不执行 Server。显式测试、Mainview 刷新连接或首次 `tools`/`call` 请求才会连接 Server。资源详情中的刷新只重新连接当前选中的 Server;Config 的全局刷新会重新连接所有已启用的 Server。stdio 与 HTTP 连接的工具发现都会读取工具列表的全部分页。校验错误会指向对应文件,其他合法 Server 仍然可用。定义变更、停用或删除时释放对应连接,City 关闭时释放全部连接。
加载、编辑定义不会安装程序。已知的 `npx`、`bunx`、`uvx` 等隐式安装运行器,以及包管理器的安装执行入口会被拒绝;应先通过已有审批流程安装程序,再配置已安装的可执行程序。旧 `config.servers` 集合不再读取,也不会自动迁移,需要明确创建独立 Server 文件。
## HTTP OAuth 授权
支持 MCP 标准 OAuth 的 HTTPS Server 收到 401 后会自动进入授权:Downcity 使用 MCP SDK 发现资源与授权服务器元数据,动态注册客户端,生成 PKCE,并通过系统浏览器打开登录页。完成登录后,授权码返回本机 `127.0.0.1` 回调,当前连接自动恢复。只有测试、刷新连接、工具发现/调用或点击重新授权才可能打开浏览器;读取状态和保存配置不会打开浏览器。
```toml
title = "OAuth MCP"
url = "https://mcp.example.com/mcp"
auth = "oauth"
# 授权服务器不提供动态客户端注册时填写预注册的公共客户端 ID
# client_id = "your-client-id"
# client_name = "Downcity"
```
OAuth 配置与 `url` 一样位于 TOML 顶层。`auth` 可省略,标准 401 会自动触发发现。预注册客户端需要支持本地回环地址与动态端口。授权元数据、issuer、注册及 token 端点必须使用 HTTPS。静态 `headers` 仍然适用于 API key 等鉴权方式;OAuth token 可用时使用 Bearer token。
MCP Server 详情展示 `none`、`authorizing`、`authorized`、`expired` 授权状态,提供“重新授权”和“取消授权”。不同 Server 的连接和授权独立;同一 Server 的请求串行执行,避免重复弹出授权窗口。授权最长等待五分钟,并受调用取消和 City 关闭控制。工具请求仍使用 `request_timeout_ms`,因此调用期间需要重新登录时,剩余调用时限可能更短。
凭据保存在 `dirname(config.path)/auth/`,按 Server ID、完整 endpoint 与 issuer 生成隔离文件名,文件权限为 `0600`,目录为 `0700`。保存的是明文 client/token 与过期时间,不保存授权码、state 或 PKCE verifier,也不向 Agent 状态或日志返回 token。有效 refresh token 由 SDK 刷新,刷新失败可重新登录。HTTP session ID、协议协商和 SSE 由 SDK 管理;明确收到 404 时最多重建一次会话并重试,网络结果不明的调用不会自动重放。
实际 Server 必须提供符合协议的发现与授权接口。Twinkle Cloud 的实际协议兼容性和首登、刷新、重启免登录尚未联调验证。
## Agent 如何使用
Agent 使用 Skill Power 的 `servers`、`tools`、`call` 三个动作。Server 不会变成独立 Power,外部工具按需发现。Skill 的 `list` 与 `lookup` 继续用于技能发现和读取。
```ts
skill({ action: "servers" });
skill({ action: "tools", args: { server_id: "filesystem" } });
skill({ action: "call", args: {
server_id: "filesystem",
tool_name: "read_file",
arguments: { path: "/allowed/example.txt" },
} });
```
先通过 `servers` 查看分配给当前 Agent 的 Server 及其状态,包括已停用或定义无效的 Server,再用 `tools` 读取原始工具名称和输入 JSON Schema,最后调用 `call`。示例中的工具名和路径需要替换为实际 Server 提供且允许使用的值。调用前会在 MCP 模块内校验参数;未分配、停用或定义无效的 Server 不能调用。`tools` 与 `call` 都会检查 Agent 分配关系。
这是结构化的发现和调用接口,没有独立 Shell 命令行程序。Server 文件通过 Desktop 管理,Agent 通过 `skill` 的 `servers`、`tools`、`call` 使用 MCP。
## 审批与边界
`call` 的访问元数据为 write,且 `approval: false`;调用已启用且分配给当前 Agent 的 Server 时不追加 MCP 审批。MCP 不提供安装、卸载工具,程序安装和卸载通过已有审批执行流程完成。Server 描述和返回值作为外部数据处理,不作为 Agent 指令。请求支持取消和配置的调用超时,过长结果返回截断标记。
stdio Server 会执行本地程序,应由用户明确配置可信 Server。凭据应在所属环境配置中维护,避免在聊天里提交明文。当前不支持 MCP 交互式输入往返。
Server 文件变化后,三个 Agent 动作保持不变,无需重建或同步 Server Power。
### Shell
Source: https://downcity.ai/zh/docs/power/shell/
Shell 是 Workspace 能力,不是 Power。它持有 Sandbox Provider、当前 Workspace 的隔离 Sandbox 与可复用的 Shell Session。
## 功能
- 默认在 Workspace Sandbox 中执行命令
- 在不同 Chat Session 之间保留已安装工具和 HOME 状态
- 捕获 stdout、stderr 和退出码
- 支持超时和取消
## 长任务与完成通知
短命令使用 `shell` 的 `exec` 动作;长任务和交互进程使用 `session_start`。设置 `auto_notify_on_exit: true` 后,命令结束会把成功、失败或主动停止的完成信息自动送回原 Session,无需轮询,同一完成信息只处理一次。
通知在执行检查点处理,不保证立即打断模型请求或同步工具。原执行已停止、关闭或被替代时,结果保留,迟到通知不会重新唤醒它。常驻服务可设为 `auto_notify_on_exit: false`。重启只恢复已保存完成结果的投递;无法接管的原进程报告中断或状态未知,不自动重跑命令。
具体调用见 [Shell 与 Sandbox](/zh/agent-sdk-docs/local-agent/shell-reference)。
## 安全
Shell 只有 `sandbox` 和 `host` 两个执行目标。默认使用 Sandbox,且不能看到任意宿主路径;host 执行必须提供明确原因并经过宿主审批。Sandbox 失败时不会回退到宿主执行。
## 使用场景
- 运行构建脚本
- 文件系统操作
- 查询系统状态
- 执行项目特定工具
继续阅读:
- [Messenger Power](/zh/docs/power/messenger)
- [Task Power](/zh/docs/power/task)
- [Agent Powers Docs](/zh/powers-docs)
### 自定义 Power
Source: https://downcity.ai/zh/docs/power/custom/
一个目录只定义一个 Power。Power ID 同时是安装目录名、City catalog 键和运行时身份,不需要再声明 Extension。
## 两个可选入口
```text
Power
├── main 提供 City 执行实例、生命周期、管理逻辑与 actions
└── renderer 声明 Sidebar + Mainview 业务工作区和/或 Config
```
两个入口都可选,但至少提供一个。一个 Power 可以只提供 City 运行能力、只提供 Sidebar + Mainview 业务工作区、只提供 Config,或同时提供完整体验。
推荐的开发目录:
```text
github-power/
├── power.json
├── package.json
├── README.md
├── assets/icon.svg
├── src/
│ ├── power.ts
│ ├── main.ts
│ └── renderer.tsx
└── dist/
├── main.js
└── renderer.js
```
两个入口都使用 ESM。`main.js` 必须自包含;`renderer.js` 是单文件浏览器 bundle,默认导出一个 Renderer 定义,其中可以声明成对的 `sidebar + mainview` 与独立的 `config`。Downcity 不安装依赖或运行构建脚本。
## 直接用于 SDK
SDK 用户可以直接构造 `CityPowerRegistration`,不经过 `power.json`:
```ts
const registration = {
id: "github",
title: "GitHub",
description: "GitHub integration",
readme: "/absolute/path/README.md",
has_config: false,
has_sidebar: false,
has_mainview: false,
power: new GithubPower(),
};
const city = new City({
powers: [registration],
workspaces: [workspace],
});
city.agents.add(agent);
```
只有需要被 CLI 或 Desktop 安装、发现和管理时,才需要下面的入口协议。
## Power 定义
```json
{
"schema_version": 1,
"id": "github",
"version": "1.0.0",
"title": "GitHub",
"description": "GitHub 集成",
"readme": "./README.md",
"icon": "./assets/icon.svg",
"main": "./dist/main.js",
"renderer": {
"entry": "./dist/renderer.js",
"sidebar": true,
"mainview": true,
"config": true
}
}
```
`renderer.sidebar` 与 `renderer.mainview` 必须同时为 `true` 或 `false`,`renderer.config` 可以独立声明;默认导出的实际组件必须与这三个静态能力完全一致。`package.json` 必须声明 `"type": "module"`。`readme` 必须声明 Power 根目录内的 `.md` 用户文档,Desktop 会在 Power Overview 中安全渲染它;文件名和子目录可自行组织,应写清用途、配置方式和必要凭据。图标可以是 HTTP(S) 地址或 Power 根目录内的相对文件,并会用于 Power 导航与 Overview。
## 统一 Power 入口
`main` 文件默认导出唯一 Power 实例;不再存在独立 `agent` 入口或第二个 main 生命周期。
Power 在 `initialize()` 中通过 `power.action()` 注册 Sidebar/Mainview 动作,通过
`power.config_action()` 注册 Config 动作:
```ts
import { Power, type PowerLifecycleContext } from "@downcity/city/power";
class GithubPower extends Power {
readonly name = "github";
readonly title = "GitHub";
readonly description = "GitHub 集成";
initialize({ power, notifications }: PowerLifecycleContext) {
power.config_action({
id: "config.read",
run: async (_input, context) => {
const config = context.config.get();
return { api_url: config.api_url, token_configured: Boolean(config.token) };
},
});
power.config_action({
id: "config.save",
run: async (input, context) => {
const current = context.config.get();
const config = validate_and_restore_secret(input, current);
await context.config.set(config);
return { saved: true };
},
});
void notifications.publish({
topic_key: "sync:repository",
title: "仓库同步完成",
route: { repository: "downcity", view: "activity" },
});
}
}
export default new GithubPower();
```
一个 Power ID 在 City 中只对应一个实例、一套生命周期和一份配置。Config action 调用时由 City
注入唯一 Config store,执行实例从 `PowerContext.config` 读取该配置的当前快照。
`notifications.publish()` 与 `notifications.dismiss()` 始终绑定当前 Power。宿主会把 `topic_key` 放入 Power 命名空间,并把 `route` 解释为当前 Power 工作区路由,因此 Power 不能代表其他 Power 或跳转到任意 Desktop 页面。相同 `topic_key` 只保留最新一条未读通知。
`PowerLifecycleContext.system` 只提供明确授权的 City 宿主能力。需要把后台结果写回既有 Session 时,使用 `append_agent_session_message({ agent_id, workspace_id, session_id, category, text })`;四个身份字段必须来自已持久化的明确目标,不能扫描或猜测 Session。
需要实现类似 Skill 管理器的功能主页时,可以通过 `system.list_workspaces()` 读取宿主已经登记的 Workspace 摘要。Power 是受信任本地 Node.js 代码;它负责验证 action 输入,并自行拥有文件、网络和长期资源的业务行为。
## Renderer 入口
Renderer 入口在同一个 bundle 中声明 UI 插槽。`sidebar` 与 `mainview` 共同构成 Power 工作区,必须成对出现,并共享宿主持有的 JSON route;宿主会为它动态增加一级导航入口。`config` 与功能工作区无关,只在 Power Catalog 详情中渲染。可选的 `agent_config` 向 Agent Profile 贡献一个页签。这些界面使用宿主 UI Components:
```tsx
import { useEffect, useState } from "react";
import { define_power_renderer } from "@downcity/city/power/react";
export default define_power_renderer({ config: function GithubConfig({ config, ui }) {
const { Button, Group, Input, LoadingState, Page, Row, Toolbar } = ui.components;
const [config_state, set_config_state] = useState<{ api_url: string }>();
useEffect(() => {
void config.invoke<{ api_url: string }>("config.read").then(set_config_state);
}, [config]);
if (!config_state) return ;
return
void config.invoke("config.save", config_state).then(() => ui.toast({ type: "success", message: "已保存" }))}>保存} />
set_config_state({ ...config_state, api_url })} />} />
;
} });
```
Renderer bundle 必须把 `react` 与 `react/jsx-runtime` 保留为宿主外部依赖,并分别映射到 `downcity-power://runtime/react` 与 `downcity-power://runtime/react/jsx-runtime`。其他前端依赖应打包进同一个 `renderer.js`。
Desktop 在宿主 React 树中加载 Renderer。Sidebar 与 Mainview 通过 `power.invoke()` 调用 Power 级动作,并通过 `navigation` 协同导航;Config 通过 `config.invoke()` 调用当前 Power 的配置动作。每个插槽都只获得所需 gateway 与宿主 UI,不会获得 Desktop controller。Renderer 属于受信任本地 UI 代码;只安装可信来源。
Sidebar 与 Mainview 还会获得当前 Power 的只读 `notifications` 数组。每项包含 Power 本地 `topic_key`、文案、route 和产生时间,可用于在对应导航对象旁显示未读状态。Renderer 通过导航到通知的完整 route 触发宿主已读收口,但没有发布或修改通知的权限。
需要在 Sidebar 标题栏提供创建入口时,可以向 `Sidebar` 的 `actions` 传入宿主提供的 `SidebarCreateMenu`。宿主负责标题栏、加号与下拉菜单的统一视觉,Power 只声明创建类型以及选择后的业务导航。
需要树状 Sidebar 时使用 `SidebarTreeItem`:`depth` 表达层级,`kind` 区分 `branch` 与 `leaf`,父节点通过 `expanded` 与 `on_toggle` 管理展开,`on_select` 通过共享 `navigation` 更新 Mainview。省略 `leading` 时宿主会为分支和叶子节点提供统一默认图标;没有子项的分支可以省略 `on_toggle`,此时不会显示折叠按钮。历史记录等多级导航也应继续放在 Power Sidebar 的树中,不占用 Mainview。行级操作使用 `ItemMenu`,Markdown 正文使用宿主安全的 `Markdown`。写操作完成后调用 `ui.invalidate()`,宿主会推进同一 Power 在 Sidebar、Mainview、Config 与 Agent Profile 页签间共享的 `ui.revision`。后台刷新应就地更新快照,保留已有数据与打开的阅读器;`agent_id` 变化时重置 Agent 专属状态。刷新状态不写入 route。
### Agent Profile 页签
通过 `agent_config: { id, label, component }` 贡献一个 Agent Profile 页签。`id` 与 `label` 必须是非空字符串。宿主收集已启用 Power 的声明,并为页签 ID 添加 Power 命名空间。Catalog 刷新时,只要同一 Renderer 注册仍然可用,宿主会保留当前页签选择与已挂载的组件。不需要额外的 `power.json` 能力标记,此插槽可以独立于 Sidebar、Mainview 和 Config 声明。
```tsx
import { define_power_renderer } from "@downcity/city/power/react";
import type { PowerAgentConfigComponentProps } from "@downcity/city/power/react";
function AgentSettings({ agent_id, ui }: PowerAgentConfigComponentProps) {
const { Page, Row } = ui.components;
return
;
}
export default define_power_renderer({
agent_config: { id: "settings", label: "设置", component: AgentSettings },
});
```
组件只接收 `{ agent_id, power, ui }`。`agent_id` 标识当前配置的 Agent。`power.invoke(action_id, input)` 与 Mainview 一样使用所属 Power 的业务 action gateway,不使用 Config gateway。Power 负责校验目标 Agent 与动作输入。此插槽不接收 `navigation` 或 `notifications`。
`PowerAgentConfigDefinition`、`PowerAgentConfigComponent`、`PowerAgentConfigComponentProps` 均从 `@downcity/city/power/react` 导出。布局使用 `ui.components`,写操作后调用 `ui.invalidate()`;宿主推进该 Power 的 `ui.revision`,供各界面重新读取数据。内建 Skill Power 通过此通用插槽提供 **Agent Profile → Skills**,管理技能关联与 MCP 分配。
## Config 交互
```text
进入 Powers Catalog 并选择 Power
→ 在 Config 中编辑 Power 的唯一配置
→ 保存后由 Power 刷新受影响的长期资源
```
每个 Power ID 只有一份 Config,与 Sidebar/Mainview 无关。宿主只负责持久化,不解释字段,也不根据 JSON Schema 生成表单。内容结构、校验、默认值、Secret 行为和保存后的资源刷新都属于 Power。
配置保存在 `~/.downcity/powers//config.toml`,目录权限为 `0700`,文件权限为 `0600`。当前存储使用 TOML,因此配置必须是 TOML 可表达的 JSON object。Agent 的 `agent.json` 不保存 Power 引用;City 自动把全部 Power 和同一份配置提供给所有 Agent。
## 安装
```bash
city power install ./github-power
# 在 Desktop Powers Catalog 的 GitHub 详情中配置
city power config github --set '{"api_url":"https://api.github.com"}'
city power update github
city power uninstall github
```
安装器只复制 `power.json`、`package.json`、`readme` 声明的 Markdown 文件、运行入口和可选本地图标,不执行依赖安装、构建脚本或任何入口。所有本地路径都不能逃逸 Power 根目录或使用 symlink,安装制品会生成 SHA-256 完整性摘要。只安装可信来源。
继续阅读:
- [CLI 命令](/zh/docs/cli/commands)
- [Agent Powers Docs](/zh/powers-docs)
### City
Source: https://downcity.ai/zh/docs/city/overview/
**City** 是 Downcity 的本地 Agent 宿主容器。它在内存中持有多个 Agent,并把 HTTP/RPC 请求转发到指定 Agent。
## City 负责什么
- **Agent 集合** — `city.agents.add(agent)` 接纳已创建的 Agent,`city.agents.get(agent_id)` 按 ID 读取,`city.agents.list()` 列出全部实例。
- **HTTP/RPC 转发** — City 统一提供两个端口,通过 `agent_id` 把请求转发到对应 Agent。
- **宿主生命周期** — CLI/Desktop 负责创建和释放 City、Agent、Workspace 与平台资源;City 负责自己的 Server 生命周期。
## City 不负责什么
- 模型目录、身份认证、用量和计费,这些属于 Federation/Embassy。
- Agent 配置的数据库适配和 Workspace 创建,这些属于宿主的组合根。
- Power 的具体存储实现,这些属于对应 Power Provider/Adapter。
这些属于 Agent 运行时。
## Agent 如何连接 City
当你运行 `city on` 时,CLI 从全局 DB 读取配置,显式创建全部 Agent,再注册到一个 `City`,最后启动 City 的 HTTP/RPC Server。
当你直接使用 SDK 时,可以直接创建 `Agent`;需要统一 HTTP/RPC 转发时,再把 Agent 注册到 `City`。
## 继续阅读
- [City SDK](/zh/city-sdk-docs) — 构建在 City 基础设施上的 SDK
- [Payments](/zh/payments) — 账号、余额、用量和支付 API
- [Agent SDK](/zh/agent-sdk-docs) — Agent 如何在运行时消费 City 服务
### 模型池
Source: https://downcity.ai/zh/docs/city/model-pool/
City 通过 Federation AIService 拥有模型目录。Agent 不直接嵌入提供商密钥或模型定义。相反,它们通过 ID 绑定模型,City 在运行时将 ID 解析为实时模型实例。
## 工作原理
1. City 注册模型提供商(OpenAI、Anthropic、Google、本地模型等)
2. 每个提供商暴露能力和模型 ID
3. Federation AIService 维护统一目录
4. Agent 绑定到类似 `"default"` 或 `"quality"` 的模型 ID
5. 运行时,ID 被解析为实时模型实例
## 模型绑定
对于 Desktop 或 CLI 管理的 Agent,绑定保存在用户级 Agent 配置中:
```json
{
"execution": {
"type": "api",
"model_id": "quality",
"reasoning_effort": "high"
}
}
```
在 Desktop 的 Agent 配置中打开 **Model**,选择默认模型及其思考强度。档位由该模型公开的能力决定;不支持配置思考强度的模型不显示该选项。选择“跟随模型默认”会移除 `execution.reasoning_effort`。
`reasoning_effort` 是可选字段,示例中的 `high` 必须是模型支持的档位。会话或执行时显式指定的思考配置优先,其次是 Agent 默认档位,最后是模型默认值。新会话、后台任务与委派执行使用 Agent 默认模型时会继承该档位。切换到其他模型时,仅保留该模型支持的档位;否则恢复模型默认值。Agent 默认档位仅作用于它绑定的默认模型。
Desktop 保存后影响后续执行,正在执行的轮次保持原配置;已有会话的独立设置继续优先。CLI 修改配置后在下次装配 Agent 时生效。
对于 SDK 项目,模型直接传入构造函数或 session。
## 提供商管理
City 处理:
- 提供商注册和认证
- 模型能力发现
- 按提供商的用量计量
- 提供商间故障转移
继续阅读:
- [City 身份](/zh/docs/city/identity)
- [用量与计费](/zh/docs/city/usage-billing)
### 身份
Source: https://downcity.ai/zh/docs/city/identity/
Federation 统一签发用户身份并保存账户数据。客户端通过 Embassy 直接访问
Federation;产品需要自己的后端能力时,再配置对应 Bureau 的可信业务入口。
## 身份边界
- **Federation**:服务端运行容器,签发 `user_token`,管理账户、Service 和 Bureau 记录。
- **Embassy User**:保存当前 `user_token`,执行用户登录和业务请求。
- **Embassy Admin**:使用管理员 Session 管理 Federation,包括授权 Federation 签发 Bureau Token。
- **Bureau**:由 `bureau_id` 区分的产品业务分区;产品后端使用独立 Bureau 客户端证明机器身份。
Embassy 只有 `user` 和 `admin` 两个身份子域:
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: "https://fed.example.com",
});
```
Embassy 本身不绑定 Bureau。登录流程需要产品分区时,才在本次登录中传入 `bureau_id`。
## 用户身份
账户流程统一位于 `embassy.user.account`。登录成功后,同一个 Embassy 实例会立即使用
新的 User Token:
```ts
const providers = await embassy.user.account.providers();
await embassy.user.account.login({
provider: "email",
client_type: "cli",
bureau_id: "product-web",
input: {
email: "user@example.com",
password: "password",
},
});
const current_user = await embassy.user.current();
const user_token = embassy.user.account.token();
```
邮箱须完成验证后才能登录,SDK 自动交换已完成流程的 Token。`await embassy.user.account.logout()` 先撤销当前 Token 再清理本地凭证,失败保留凭证以便重试。Bureau 对新的受保护请求向 Federation 在线验证,检查不可用时拒绝访问;已开始的流式请求继续运行。
User Token 是 Federation 使用 Ed25519 私钥签发的 JWT。它包含 `user_id`、
`bureau_id`、issuer、audience 和有效期;公开验签密钥由以下接口发布:
```text
/.well-known/downcity.json
/.well-known/jwks.json
```
用户侧 AI、Payment 和普通 Service 请求直接发送到 Federation:
```ts
const models = await embassy.user.ai.catalog();
const accounts = embassy.user.service("accounts");
const services = await embassy.user.list_services();
```
当当前 Bureau 配置了可信 `server_url` 时,相对路径请求会发送到该 origin,并自动携带
当前 User Token。Embassy 不会把 Token 转发到其他 origin:
```ts
const result = await embassy.user.post(
"/reports/summary",
{ range: "today" },
);
```
## 管理员身份
管理员使用 ID 和密码换取有期限的 Admin Session。不存在 Root Admin Token:
```ts
await embassy.admin.login({
admin_id: "owner",
password: "password",
});
const current_admin = await embassy.admin.current();
const bureaus = await embassy.admin.bureaus.list();
```
密码遗失时,由拥有部署权限的人运行 `fed deploy --admin-reset` 重设管理员凭证。
## Bureau Token
登录后的 Federation Admin 可以签发 Bureau Token:
```bash
fed bureau token
```
CLI 请求 Federation 生成高熵 Token。Federation 只保存 `token_id`、用途、hash 和生命周期状态,
明文只返回一次,应写入业务服务的部署环境:
```bash
DOWNCITY_FEDERATION_URL=https://fed.example.com
DOWNCITY_BUREAU_TOKEN=fb_br_xxx.secret
```
业务服务通过独立的 `Bureau` 客户端验证收到的 Federation User Token:
```ts
import { Bureau } from "@downcity/federation";
const bureau = new Bureau({
federation_url: process.env.DOWNCITY_FEDERATION_URL!,
bureau_token: process.env.DOWNCITY_BUREAU_TOKEN!,
});
const identity = await bureau.identify(request);
```
`bureau_token` 是长期、可撤销的不透明 Bearer 凭证,不是 JWT,也不能签发 User Token。
它在创建时绑定 `bureau_id`;`identify()` 会验证签名、issuer、audience、有效期和该
`bureau_id`。发生泄露时,使用 `fed bureau token revoke ` 立即撤销。
User Token 的签发权威始终是 Federation。账户登录或 Admin 管理接口都只是进入 Federation
签发流程的入口,Bureau Token 无权调用 User Token 签发接口。
| 凭证 | 持有者 | 用途 | 验证方式 |
| --- | --- | --- | --- |
| `user_token` | 用户客户端 | 访问 Federation 与 Bureau 业务 | Federation JWKS 验签 |
| `admin_token` | 管理员 Embassy | Federation 控制面 | Federation Admin Session |
| `bureau_token` | Bureau 业务服务 | 证明机器身份并执行 `identify()` | Federation 比较凭证 hash |
继续阅读:
- [Federation SDK](/zh/city-sdk-docs/packages/federation)
- [模型池](/zh/docs/city/model-pool)
- [用量与计费](/zh/docs/city/usage-billing)
### 用量与计费
Source: https://downcity.ai/zh/docs/city/usage-billing/
City 计量每次模型调用并追踪所有已连接 Agent 和产品的用量。这是计费、配额和成本管理的基础。
## 用量追踪
- 每次模型请求都会被计量(输入 token、输出 token)
- 用量按用户、按项目和按模型聚合
- 控制台中提供实时用量仪表板
持有有效 Admin Session 的 Federation 管理员可以读取服务端聚合结果:
```text
GET /v1/usage/admin/overview?from=2026-07-07&to=2026-08-05&timezone=Asia/Shanghai
GET /v1/usage/admin/users?from=2026-07-07&to=2026-08-05&timezone=Asia/Shanghai
GET /v1/usage/admin/retention?from=2026-07-07&to=2026-08-05&timezone=Asia/Shanghai
```
`overview` 返回范围活跃、真实去重的 DAU/WAU/MAU 日序列、调用结果、Token 构成、
Credits、模型与 Action 分布、当地小时分布,以及平均/P50/P95 执行耗时。`users` 按用户
返回调用次数、Input/Output/Total Token、成功率、Top Model、Credits、耗时与最后活跃时间。
`retention` 使用 Accounts 注册时间和真实 AI Usage 活跃日计算 D1、D3、D7、D14、D30
注册 Cohort 留存。活跃用户定义为统计窗口内至少产生一次 AI Usage Record 的用户;失败和
取消调用仍表达真实产品使用,因此计入活跃,并单独进入结果与成功率。
## 余额
- 用户在 City 中维护余额账户
- 余额随着用量产生而消耗
- 余额低时触发提醒
- 可以配置自动充值
## 计费
City 与 Stripe 集成,支持:
- 一次性支付
- 订阅计划
- 基于用量的计费
- 发票生成
## 配额
- 软配额在达到限制前发出警告
- 硬配额在超出时阻止请求
- 配额可以按用户、按项目或按模型配置
继续阅读:
- [模型池](/zh/docs/city/model-pool)
- [City 身份](/zh/docs/city/identity)
### Federation & Service
Source: https://downcity.ai/zh/docs/federation/overview/
**Federation** 是 City 连接的共享服务端运行容器。它负责用户身份、City 隔离、Service 路由、模型目录、用量和支付,并通过统一接口连接多个 AI 提供商。
## Federation AIService
Federation AIService 是 City 的一个组件,负责:
- 注册模型提供商及其能力
- 无论后端是什么,都暴露统一的模型 API
- 追踪用量并将请求路由到合适的提供商
- 处理故障转移和速率限制
Agent 通过类似 `"default"` 或 `"quality"` 的 ID 绑定模型。Federation AIService 在运行时将该 ID 解析为实时模型实例。
## Service / Action 基础设施
City 还提供了一个通用的 **Service** 和 **Action** 层,用于构建 Agent 可调用的后端能力:
- **Service** — 长期运行的后端能力(例如知识库、搜索引擎、数据库)
- **Action** — Agent 可调用的离散操作(例如发送邮件、查询数据库、调用外部 API)
Service 和 Action 向 City 注册,可被任何已连接的 Agent 发现和调用。
## 与 City 的关系
`Federation` 是服务端,`City` 是携带 `user_token` 的用户客户端。当你使用 City SDK 时,你在交互的是:
- City 身份与认证
- Federation AIService(模型目录和路由)
- Service/Action 基础设施(后端能力)
- 用量、余额和计费(City Services)
Federation 首次启动会自动生成 Ed25519 Key Ring,并通过 `/.well-known/jwks.json` 发布公开验签密钥。Embassy 可以直接访问 Federation;产品需要自有后端能力时,再使用 Bureau Token 和独立 Bureau 客户端本地验证用户 Token。Federation 启动不会默认创建 Bureau Token。
## 本地服务运行
本地 Federation 使用 macOS 用户级 launchd 或 Linux 用户级 systemd 管理。`[deployment.process]` 默认 `auto_start = false`、`restart_on_failure = true`;异常退出后每隔 10 秒尝试恢复,60 秒内最多 5 次。`fed stop` 禁用自动启动并停止服务,系统重启后仍保持停止,直到用户显式 deploy/restart。
自动启动需显式开启;macOS 在用户登录后启动,Linux 需要用户 manager 已存在并可用,CLI 不自动开启 linger。系统服务定义不包含 secret,运行配置独立保存。配置示例及 `status`、`logs` 语义见 [CLI 快速开始](/zh/city-sdk-docs/packages/cli/quickstart)。
## 管理员登录与恢复
首次运行 `fed deploy` 时,CLI 会交互式要求设置 Federation 管理员 ID、密码和确认密码。密码至少 12 个字符,Federation 数据库仅保存加盐密码摘要。用 `fed web --id fed_x` 指定已保存连接并启动后,在登录页输入这组凭证;浏览器不会接触远端管理 Session Token,Token 只存在于本机 BFF 进程内。
普通部署不会修改管理员。密码遗失时,只有拥有 Local 主机权限或 Cloudflare Worker/D1 部署权限的人可以执行:
```bash
fed deploy --admin-reset
```
非交互环境还必须显式添加 `--yes`;该参数只确认重置,不跳过管理员凭证输入。恢复由 CLI 使用本地 SQLite 事务或 Wrangler 远程 D1 权限直接写入管理员数据库,不需要在 Worker 中接收恢复环境变量,也不会把明文密码传给数据库。恢复成功会撤销全部旧管理员会话。Federation 不提供匿名密码重置 API。
`fed deploy` 会在交互终端持续显示当前步骤与耗时,包括构建、类型检查、Cloudflare 账号检查、D1 / Queue / R2 准备、Worker 发布、健康检查和管理员验证;CI 与重定向输出使用稳定的逐行阶段日志。
Fed 没有全局 active/default 连接。目标选择使用互斥且精确匹配的 `--id ` 或 `--name `;省略参数时,TTY 列表选择只用于本次操作,非交互环境报错。名称重名时,TTY 继续选择,非 TTY 报错。
`fed bureau token --id fed_x` 会打开该连接的交互式管理界面。选择参数也可放在 `token` 父命令上,例如 `fed bureau token --id fed_x list`。选择签发或运行 `fed bureau token --id fed_x issue `
后,CLI 会要求输入用途并使用 Admin Session 请求 Federation 签发。Federation 生成明文,
数据库只保存用途、hash 与生命周期状态。明文只返回一次,由运维写入 Bureau 服务器的
`DOWNCITY_BUREAU_TOKEN`;Federation 和 Bureau 不需要部署在同一台服务器。Bureau Token
只证明机器身份,不能签发 User Token。
## 继续阅读
- [City SDK](/zh/city-sdk-docs) — 构建在 City 和 Federation 之上
- [Payments](/zh/payments) — 用量、余额和计费 API
### Organizations
Source: https://downcity.ai/zh/docs/federation/organizations/
`OrganizationsService` 管理 Organization、Membership、Join Request 和组织治理角色。Federation 是这些关系的唯一权威来源。
Organization 不保存产品后端地址,也不管理 Space、文档、Repository 等产品资源。Bureau 从产品可信配置取得 Bureau 地址,并携带当前 `user_token` 请求 Bureau。Bureau 验证用户身份、查询 Membership,再执行自己的资源权限。
- 客户端和产品后端 API:[Organizations Federation API](./organizations-api)
- 产品后端接入:[Bureau 接入 Organizations](./organizations-bureau)
## 安装
```ts
import { Federation } from "@downcity/federation";
import { OrganizationsService } from "@downcity/services";
const federation = new Federation({ database });
federation.use(new OrganizationsService({
max_organizations_per_user: 3,
}));
```
额度统计用户作为 Owner 持有的全部 active Organization,不按 Bureau 重复计算。归档会释放额度,Owner 转移会把额度交给新 Owner。
## Organization 作用域
创建 Federation 全局 Organization:
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: process.env.DOWNCITY_FEDERATION_URL!,
user_token,
});
await embassy.user.service("organizations").action("create").invoke({
name: "Genesis Research",
scope_type: "federation",
});
```
创建当前 Bureau Organization:
```ts
await embassy.user.service("organizations").action("create").invoke({
name: "Genesis Research",
scope_type: "bureau",
});
```
`federation` Organization 可以由同一 Federation 下任意 Bureau Token 中的成员访问。`bureau` Organization 只接受 `user_token.bureau_id` 与 `scope_bureau_id` 相同的请求。Bureau 作用域从已验证 Token 写入,客户端不能提交或覆盖 `scope_bureau_id`。
全局不等于公开。Organizations Service 不提供公开搜索;用户仍需通过邀请链接、二维码或产品流程取得 `organization_id`。
## Membership
Membership 表示一个 User 与 Organization 之间的一段成员关系。每次成功加入都会生成新的 `membership_id`。退出或被移除后,旧记录永久保持 `removed`;重新加入会创建另一条 Membership。
```ts
await embassy.user.service("organizations").action("join-requests/create").invoke({
organization_id: "org_01J...",
});
```
Owner、Admin、Member 只表达 Organization 治理角色,不代表产品中的 editor、viewer 或 repository push 权限。
## 调用产品 Bureau
Bureau 把同一个 `user_token` 发送给产品预先配置的 HTTPS Bureau:
```ts
await embassy.user.post("/v1/projects", {
organization_id: "org_01J...",
});
```
Bureau 使用 Federation JWKS 验证 Token,并通过 `membership/get` 查询当前 Membership。Organizations Service 不再签发 `organization_token`,也不向用户提供的 URL 投递撤权事件。
## 数据库与归档
Organizations Service 支持 better-sqlite3、PostgreSQL 与 Cloudflare D1。三种 Runtime 统一使用 `context.transaction()`;Service 不判断数据库类型。
Organization 归档不可恢复。归档会停止治理写入并释放 Owner 额度。产品资源是否保留、归档或删除,由 Bureau 决定。
### Organizations Federation API
Source: https://downcity.ai/zh/docs/federation/organizations-api/
这篇文档描述客户端和 Bureau 可以调用的 Organizations Action。产品后端的身份和权限接入见 [Bureau 接入 Organizations](./organizations-bureau)。
## 安装
```ts
import { Federation } from "@downcity/federation";
import { OrganizationsService } from "@downcity/services";
const federation = new Federation({ database });
federation.use(new OrganizationsService({
max_organizations_per_user: 3,
}));
```
| 选项 | 必填 | 说明 |
| --- | --- | --- |
| `max_organizations_per_user` | 是 | 一个用户在 Federation 中最多拥有的 active Organization 总数 |
Service 支持 better-sqlite3、PostgreSQL 和 Cloudflare D1,并统一使用 `context.transaction()`。
## 地址与鉴权
```text
{federation_origin}/v1/organizations/{action}
```
所有 Action 都需要 Federation `user_token`:
```http
Authorization: Bearer ub_
```
Federation 从已验证 Token 读取 `user_id` 和 `bureau_id`。GET Action 使用 Query,POST Action 使用 JSON。
## 类型
```ts
type Organization = {
organization_id: string;
name: string;
scope_type: "federation" | "bureau";
scope_bureau_id: string;
state: "active" | "archived";
created_by: string;
created_at: string;
updated_at: string;
archived_at: string;
};
type Membership = {
membership_id: string;
organization_id: string;
user_id: string;
role: "owner" | "admin" | "member";
state: "active" | "removed";
created_at: string;
updated_at: string;
removed_at: string;
removed_by: string;
};
type JoinRequest = {
request_id: string;
organization_id: string;
user_id: string;
state: "pending" | "approved" | "rejected" | "canceled";
requested_at: string;
decided_at: string;
decided_by: string;
};
```
`scope_type = federation` 时 `scope_bureau_id` 为空字符串。`scope_type = bureau` 时,`scope_bureau_id` 来自创建请求的 `user_token.bureau_id`。
## 权限
| 操作 | Owner | Admin | Member |
| --- | --- | --- | --- |
| 读取 Organization 和成员 | ✓ | ✓ | ✓ |
| 修改名称 | ✓ | ✓ | |
| 审批 Join Request | ✓ | ✓ | |
| 移除 Member | ✓ | ✓ | |
| 移除 Admin | ✓ | | |
| 任命或撤销 Admin | ✓ | | |
| 转移 Owner | ✓ | | |
| 归档 | ✓ | | |
| 主动退出 | 转移后 | ✓ | ✓ |
## Action
| Method | Action | 权限 | 说明 |
| --- | --- | --- | --- |
| `GET` | `my` | User | 列出当前用户可见的 Organization |
| `GET` | `get` | Member | 读取 Organization 与当前 Membership |
| `POST` | `create` | User | 创建 Organization 并成为 Owner |
| `POST` | `update` | Owner/Admin | 修改名称 |
| `POST` | `archive` | Owner | 归档 Organization |
| `GET` | `membership/get` | Member | 读取当前 Membership |
| `GET` | `members/list` | Member | 列出 active Membership |
| `POST` | `members/role` | Owner | 设置 Admin 或 Member |
| `POST` | `members/remove` | Owner/Admin | 移除可管理的成员 |
| `POST` | `members/leave` | Admin/Member | 主动退出 |
| `POST` | `owner/transfer` | Owner | 转移唯一 Owner |
| `POST` | `join-requests/create` | User | 申请加入 |
| `POST` | `join-requests/cancel` | Applicant | 取消 pending 申请 |
| `GET` | `join-requests/list` | Owner/Admin | 列出 pending 申请 |
| `POST` | `join-requests/decide` | Owner/Admin | 批准或拒绝申请 |
## Organization Action
### `GET my`
```http
GET /v1/organizations/my
```
默认只返回 active Organization。包含归档记录:
```http
GET /v1/organizations/my?include_archived=true
```
返回 `{ "items": UserOrganization[] }`。Federation Organization 在任意 Token Bureau 可见;Bureau Organization 只在当前 Token Bureau 匹配时可见。
### `GET get`
```http
GET /v1/organizations/get?organization_id=org_01J...
```
要求 active Membership,返回 `{ organization, membership }`。成员可以读取 archived Organization,但不能继续治理写入。
### `POST create`
创建全局 Organization:
```json
{
"name": "Genesis Research",
"scope_type": "federation"
}
```
创建当前 Bureau Organization:
```json
{
"name": "Genesis Research",
"scope_type": "bureau"
}
```
Service 返回 `{ organization, membership }`,Membership 是唯一 Owner。名称去除首尾空白后必须为 1–120 个字符。
### `POST update`
```json
{
"organization_id": "org_01J...",
"name": "New Name"
}
```
Owner/Admin 可修改名称。Organization 作用域创建后不能修改。
### `POST archive`
```json
{ "organization_id": "org_01J..." }
```
Owner 可执行。归档不可恢复,会停止治理写入并释放 Owner 额度。Membership 和 Join Request 历史保留。
## Membership Action
### `GET membership/get`
```http
GET /v1/organizations/membership/get?organization_id=org_01J...
```
返回 `{ organization, membership }`。Bureau 可以携带用户提交的同一个 `user_token` 调用此接口。被移除的用户返回 `403 NOT_AN_ORGANIZATION_MEMBER`。
### `GET members/list`
```http
GET /v1/organizations/members/list?organization_id=org_01J...
```
返回 `{ "items": Membership[] }`,只包含 active Membership。
### `POST members/role`
```json
{
"organization_id": "org_01J...",
"membership_id": "mem_01J...",
"role": "admin"
}
```
Owner 可将非 Owner 成员设置为 `admin` 或 `member`。转移 Owner 使用 `owner/transfer`。
### `POST members/remove`
```json
{
"organization_id": "org_01J...",
"membership_id": "mem_01J..."
}
```
Owner 可以移除 Admin 或 Member;Admin 只能移除 Member。唯一 Owner 不能被移除。
### `POST members/leave`
```json
{ "organization_id": "org_01J..." }
```
Admin 和 Member 可以退出。Owner 必须先转移所有权。
### `POST owner/transfer`
```json
{
"organization_id": "org_01J...",
"membership_id": "mem_new_owner"
}
```
目标必须是 active Member,并且还有 Owner 额度。原 Owner 变为 Admin。
## Join Request Action
### `POST join-requests/create`
```json
{ "organization_id": "org_01J..." }
```
用户通过已知 ID 申请加入。重复申请返回同一个 pending 记录。已有 active Membership 时返回 `{ state: "joined", organization, membership }`。
### `POST join-requests/cancel`
```json
{ "request_id": "join_01J..." }
```
申请人可以取消自己的 pending 申请。
### `GET join-requests/list`
```http
GET /v1/organizations/join-requests/list?organization_id=org_01J...
```
Owner/Admin 调用,返回 pending Join Request。
### `POST join-requests/decide`
```json
{
"request_id": "join_01J...",
"decision": "approved"
}
```
`decision` 接受 `approved` 或 `rejected`。批准时,Service 在同一事务中创建新的 Member Membership。
## 错误
| HTTP | Code | 含义 |
| --- | --- | --- |
| `400` | `ORGANIZATION_INPUT_INVALID` | 名称、ID、角色或决策无效 |
| `400` | `ORGANIZATION_SCOPE_INVALID` | `scope_type` 无效 |
| `401` | `AUTH_REQUIRED` | 缺少有效用户身份 |
| `403` | `ORGANIZATION_BUREAU_MISMATCH` | Token Bureau 不能访问该 Bureau Organization |
| `403` | `NOT_AN_ORGANIZATION_MEMBER` | 当前用户没有 active Membership |
| `403` | `ORGANIZATION_ROLE_DENIED` | 治理角色不允许操作 |
| `404` | `ORGANIZATION_NOT_FOUND` | Organization 不存在 |
| `404` | `ORGANIZATION_MEMBERSHIP_NOT_FOUND` | Membership 不存在或已失效 |
| `404` | `JOIN_REQUEST_NOT_FOUND` | Join Request 不存在或不可操作 |
| `409` | `ORGANIZATION_LIMIT_REACHED` | Owner 额度已满 |
| `409` | `OWNER_TRANSFER_REQUIRED` | 必须先转移 Owner |
| `410` | `ORGANIZATION_ARCHIVED` | Organization 已归档 |
客户端应按 `error.code` 分支,不要依赖错误文本。
### Bureau 接入 Organizations
Source: https://downcity.ai/zh/docs/federation/organizations-bureau/
Bureau 是可信产品后端。Bureau 向产品预先配置的 HTTPS Bureau 发送 Federation `user_token`,Bureau 先验证用户和 Bureau,再查询 Organization Membership。
## 授权顺序
```text
Bureau
-> user_token + 产品请求
-> Bureau 验证 Federation JWT 和 bureau_id
-> Bureau 从资源记录读取 organization_id
-> Bureau 查询 Federation Membership
-> Bureau 执行产品角色与资源权限
```
Membership 通过只代表用户属于 Organization。它不代表用户可以访问 Organization 下的每个产品资源。
## 验证 `user_token`
Bureau 使用预先配置的 Federation issuer 和 JWKS 校验:
- JWT 算法与签名;
- `iss` 和 `aud`;
- `exp`、`nbf`;
- `user_id` 和 `bureau_id`;
- `bureau_id` 是否属于当前产品允许的范围。
Bureau 不应记录 Authorization Header,也不能把 Token 转发给产品配置之外的服务。
## 查询 Membership
Bureau 可以携带用户提交的同一个 Token 查询 Federation:
```http
GET /v1/organizations/membership/get?organization_id=org_01J...
Authorization: Bearer ub_...
```
成功响应包含当前 Organization 与 active Membership。用户退出或被移除后,接口返回 `403 NOT_AN_ORGANIZATION_MEMBER`。
## 检查资源归属
产品资源表保存 `organization_id`:
```sql
CREATE TABLE projects (
project_id TEXT PRIMARY KEY,
organization_id TEXT NOT NULL,
name TEXT NOT NULL
);
```
处理 `/v1/projects/:project_id` 时,Bureau 先读取 Project,再用 `project.organization_id` 查询 Membership。不能相信客户端额外提交的 Organization ID 来决定资源归属。
## 产品权限
Bureau 在 Membership 通过后执行自己的权限模型:
```text
Federation Membership
-> 用户属于 Organization
Product Role / ACL
-> 用户能否读取、编辑或管理具体资源
```
Organization Owner/Admin/Member 只负责 Federation 中的组织治理。产品需要的 editor、viewer、billing_admin 等角色由 Bureau 保存。
## 缓存与撤权
要求即时撤权的写入、管理或敏感读取应在线查询 Federation。低风险读取可以使用短时缓存,最长撤权延迟等于缓存 TTL。
缓存键至少包含 Federation issuer、`user_id` 和 `organization_id`。Bureau 必须为缓存 TTL 做出明确选择,Organizations Service 不再维护跨服务器撤权 Outbox。
## 检查清单
- [ ] Bureau URL 来自可信产品配置
- [ ] 只通过 HTTPS 接收 `user_token`
- [ ] 校验 issuer、audience、签名、时间和 `bureau_id`
- [ ] 不记录或转发 Authorization Header
- [ ] 从资源记录读取 `organization_id`
- [ ] 对敏感操作在线查询 Membership
- [ ] Membership 通过后继续执行产品权限
### 模型提供商
Source: https://downcity.ai/zh/docs/federation/model-provider/
Federation AIService 抽象了多个 AI 模型提供商。模型提供商是任何能够服务模型请求的后端 —— OpenAI、Anthropic、Google 或本地推理服务器。
## 注册
提供商向 City 注册,暴露:
- 可用模型 ID
- 能力标志(流式、工具使用、视觉等)
- 认证要求
## 统一 API
无论后端是什么,Federation AIService 向 Agent 暴露统一的 API。这意味着:
- Agent 不需要提供商专属代码
- 切换提供商是配置变更,不是代码变更
- 可以添加新提供商而不修改 Agent
## 能力发现
当 Agent 绑定到模型 ID 时,City 报告:
- 模型是否支持流式
- 模型是否支持工具使用
- 最大上下文长度
- 每 token 定价
继续阅读:
- [Service](/zh/docs/federation/service)
- [Action](/zh/docs/federation/action)
### 本地代理
Source: https://downcity.ai/zh/docs/federation/local-proxy/
当你需要一个本地 Federation 服务,只暴露 Codex 或 Claude Code 的模型能力,而不注册到已有 Fed server 时,可以使用 Downcity local proxy skill。
生成的项目会启动:
- `127.0.0.1:8317` 上的 CLIProxyAPI
- `127.0.0.1:3000` 上的 Downcity 本地 Federation
- `/v1/ai/models` 和 `/v1/ai/chat/completions` 模型接口
## 安装 skill
在包含 `private` 仓库的联合工作区根目录,使用 Vercel Labs `skills` CLI 从本地资源安装:
```bash
npx skills add ./private/apps/homepage/resources/downcity-local-proxy-skill \
--skill downcity-local-proxy \
--agent codex \
--global \
--yes
```
## 让 Codex 创建本地服务
安装后,对 Codex 发送这个 prompt:
```text
Use downcity-local-proxy to create ./downcity/local-proxy with Codex and Claude Code enabled, then install dependencies and start the local Federation service.
```
## 手动启动
skill 会创建一个独立项目。进入生成目录后运行:
```bash
cd ./downcity/local-proxy
pnpm install
pnpm start --codex
pnpm start --claude-code
pnpm start --codex --claude-code
```
当 CLIProxyAPI 需要 OAuth 登录或刷新时,添加 `--login`:
```bash
pnpm start --codex --login
pnpm start --claude-code --login
```
本地代理只会在生成项目内的 `.downcity/` 写入运行时文件,不会修改全局 Downcity CLI 状态,也不会把自己注册到已有 Fed server。
继续阅读:
- [模型提供商](/zh/docs/federation/model-provider)
- [Service](/zh/docs/federation/service)
### Service
Source: https://downcity.ai/zh/docs/federation/service/
**Service** 是 Agent 可以调用的长期运行后端能力。与工具(在 Agent 进程内运行)不同,Service 作为独立后端运行,通过 City 网络访问。
## 示例
- 知识库(文档的语义搜索)
- 搜索引擎(网页搜索、内部搜索)
- 数据库(结构化数据存储和查询)
- 文件存储(文档上传和检索)
## 注册
Service 向 City 注册,通过:
1. 声明其 API schema
2. 暴露健康和能力的端点
3. 接收一个 service ID
## 发现
Agent 通过 City 发现 Service。当 Agent 需要某种能力时,它向 City 询问可用的 Service,然后将请求路由到合适的那个。
继续阅读:
- [模型提供商](/zh/docs/federation/model-provider)
- [Action](/zh/docs/federation/action)
### Action
Source: https://downcity.ai/zh/docs/federation/action/
**Action** 是 Agent 可以调用的离散操作。它是 Service/Action 层中的工作单元。Action 由 Service 暴露,可以组合成工作流。
## 示例
- `send_email` — 向收件人发送邮件
- `query_database` — 运行 SQL 查询
- `call_api` — 调用外部 HTTP API
- `upload_file` — 将文件存储到文件存储
## Schema
每个 Action 声明:
- 输入 schema(接受的参数)
- 输出 schema(返回的内容)
- 错误条件
- 所需权限
## 调用
Agent 通过 City 层调用 Action。City 将请求路由到拥有该 Action 的 Service,然后将结果返回给 Agent。
## 组合
Action 可以组合成更高级的工作流。例如,"用户入职"工作流可能按顺序调用 `create_account`、`send_welcome_email` 和 `add_to_crm`。
继续阅读:
- [模型提供商](/zh/docs/federation/model-provider)
- [Service](/zh/docs/federation/service)
### 路由
Source: https://downcity.ai/zh/docs/federation/routing/
Federation AIService 处理模型提供商和 Service 之间的请求路由和故障转移。这确保即使个别后端宕机,Agent 仍然可用。
## 模型路由
当 Agent 发送模型请求时:
1. Federation AIService 查找模型 ID
2. 选择健康和延迟最低的提供商
3. 转发请求
4. 如果提供商失败,用下一个可用提供商重试
## Service 路由
当 Agent 调用 Action 时:
1. City 将 Action 解析到拥有它的 Service
2. 检查 Service 的健康和负载
3. 将请求路由到最佳实例
4. 如果 Service 不可用,返回错误或排队请求
## 故障转移
- 持续监控提供商健康
- 失败的请求以指数退避重试
- 断路器防止级联故障
- 负载均衡将流量分布到健康实例
继续阅读:
- [模型提供商](/zh/docs/federation/model-provider)
- [Service](/zh/docs/federation/service)
### 架构
Source: https://downcity.ai/zh/docs/concepts/architecture/
当前 Downcity 最好通过五层来理解:
1. `console`
2. `agent`
3. `execution context`
4. `session`
5. `power runtime`
## 分层
### `console`
- 全局控制面
- 进程 registry
- city 级配置与观测
### `agent`
- 拥有一个项目 runtime
- 持有模型访问、session store、Power registry 与 runtime host 状态
### `execution context`
- 执行期间暴露出来的统一能力面
- Power 读取稳定运行时能力的地方
### `session`
- 拥有一条执行线程与其 prompt / run 状态
- 真正跑 model + tool flow 的执行单元
### `power runtime`
- 当前所有能力模块统一建模成 Power
- 有些是本地 action-first Power
- 有些是托管 lifecycle-owned Power
## 托管 Power 与本地 Power
### 本地 Power
- 通常直接挂到一个 SDK `Agent` 上
- 例如:`skill`、`web`、`sound`
### 长期运行 Power
- 由 `Agent` 在构造时装配,并在 `agent.dispose()` 时释放
- 例如:`chat`、`task`、`memory`、`shell`、`schedule`
## 最重要的结论
不要再用旧的“双层拆分”语言理解当前系统。
现在的真实模型是:
- session 负责执行
- Power 负责暴露能力
- 托管 Power 负责长期运行模块
### Project Logic Overview
Source: https://downcity.ai/zh/docs/concepts/project-logic-overview/
理解 Downcity 最好先从产品问题开始:AI builders 不应该为每个产品、工作流或客户 Demo 都重复搭一遍 Agent 后端。
核心关系是:
- 产品表层负责用户体验
- Agent 在明确运行边界里执行任务
- Downcity runtime services 负责模型、env、auth、service routing、usage、balance、payment 等重复基础设施
- Console、Chrome Extension、SDK 和 UI 组件把这套 runtime 暴露给 builders 和团队
## Runtime 名词
- `downcity`:整体 runtime 与 CLI 表面
- `console`:全局控制面
- `agent`:一个项目 runtime
- `session`:一条执行线程
- `power`:一个能力边界
- `city`:当前 Downcity runtime 的 package / runtime 名称
## 最短模型
- 产品负责体验
- agent 负责运行工作
- session 负责执行轮次
- Powers 负责暴露能力
- City 负责把重复后端能力从每个产品里抽出来
## Power 的两类
### 本地 Power
- 直接挂到一个 SDK `Agent`
- 通常是 action-first 或 hook-oriented
### 托管 Power
- 归属于目标 agent runtime
- 可以持有 lifecycle-owned runtime state
## 为什么这很重要
读当前代码或文档时,优先看产品边界:
- 需要产品操作,看 `downcity`、`console` 和产品文档
- 需要执行拥有者,看 `agent` 与 `session`
- 需要找能力拥有者,看 `power`
- 需要可复用后端能力,看 City SDK 和 services 文档
### 安全与权限总览
Source: https://downcity.ai/zh/docs/security/overview/
Downcity 的安全模型分为 3 层:
1. Agent 隔离:一个运行中的 agent 绑定一个 `projectRoot`,默认不会跨项目串上下文。
2. Chat Access:按 Agent、Chat 账号和平台用户身份决定消息能否进入 Agent。
3. 本地配置:模型、Workspace、Agent 和 Power 配置保存在本机文件中,主要依靠文件权限隔离。
## 你需要重点关注
1. 不要在终端残留错误的 `DC_CITY_HOST/DC_CITY_PORT`,避免把命令路由到错误 runtime。
2. 新用户默认不会进入 Agent,启用聊天渠道后先处理待批准的 Access Request。
3. 本地配置以明文保存,不要把 `~/.downcity`、Agent 配置或 Power 配置复制到不受信任的位置。
## 推荐阅读顺序
1. [API 认证](/zh/docs/security/api-authentication)
2. [权限配置](/zh/docs/security/permissions)
3. [数据存储与权限](/zh/docs/security/data-security)
4. [调用路由与环境隔离](/zh/docs/concepts/invocation-routing-and-isolation)
### API 认证
Source: https://downcity.ai/zh/docs/security/api-authentication/
Downcity 现在只保留一种对外认证模型:
- 不再提供用户名 + 密码登录
- 不再提供浏览器 session
- 统一使用 Bearer Token
- token 只由本机终端里的 CLI 管理
当前已经落地的接口是:
- `GET /api/auth/status`
- `GET /api/auth/me`
- `GET /api/auth/token/list`
- `POST /api/auth/token/create`
- `POST /api/auth/token/delete`
## Token 归属
Token 由拥有本地 runtime 的同一台机器创建和保存。Token 名称只用于人工识别和管理,不代表不同权限或不同渠道类型。
## 用 Token 调用接口
拿到 token 后,统一放进 `Authorization` 头:
如果 token 有效,接口会返回当前主体、角色和权限。
## 管理 Token
Token 创建、列出和删除都是本机操作。HTTP token 管理接口需要先持有 Bearer Token,所以外部调用者不能在没有权限的情况下静默签发新权限。
## `DC_AUTH_TOKEN`
先说结论:
- 只有对外 HTTP 调用才需要 Bearer Token
- 本地托管命令现在默认也是通过本地 agent daemon 的 HTTP 端点访问
对于直接调用 API 的用户,只需要记住一条:
- 对外调用统一使用 `Authorization: Bearer `
但在 CLI/runtime 里,真正需要关心的环境变量只有一个:
| 变量 | 面向谁 | 作用 |
| --- | --- | --- |
| `DC_AUTH_TOKEN` | 用户、脚本、CI | 显式指定“这次 CLI/API 调用用哪个 token” |
只有当前 HTTP 端点需要鉴权时,CLI 才会进入下面的 token 解析顺序:
1. `--token`
2. `DC_AUTH_TOKEN`
所以:
- `DC_AUTH_TOKEN` 是显式覆盖
- 受保护的 HTTP 调用最终会把 `DC_AUTH_TOKEN` 归一化为 Bearer Token 请求头
如果你看到 `Missing bearer token`:
- 不要先怀疑 `sessionId`
- 先确认目标 HTTP 端点当前是不是启用了鉴权
- 再检查当前进程有没有可用 token 来源
- 如果是在 agent/Bash/ACP 子进程里,先确认这条命令是否需要显式传入 token
具体 token 工作流放在 [Downcity CLI 产品文档](/zh/docs/reference/cli)。
## 当前边界
当前模型就是 token-only:
- 已移除用户名 + 密码登录
- 已移除 `bootstrap-admin`
- 已移除 `login`
- 已移除 `password/update`
- Console UI、Chrome Extension、外部脚本统一使用显式签发的 Bearer Token
后续如果增加新的接入面,也会继续沿用这套 Bearer Token 模型,而不是再引入单独的登录 session。
### Chat Access
Source: https://downcity.ai/zh/docs/security/permissions/
Chat Access 是 Messenger Power 的准入能力,只回答一个问题:某个外部 Chat 用户的私聊或群聊消息,是否可以进入指定 Agent。
它不是 Agent Core 权限,也不是通用 Role/Permission 系统。用户通过准入后,Messenger Power 只把消息交给 Agent,不会向 Session 或其他 Power 传播角色和权限。
## 核心规则
- 默认拒绝:没有明确 `allow` Grant 时,消息不会进入 Agent。
- 按 Agent 隔离:访问 Agent A 的批准不会自动允许访问 Agent B。
- 按 Chat 账号隔离:身份键由 `channel + issuer + subject_id` 组成,同一用户通过两个 Bot 访问时是两个 Principal。
- 范围明确:持久化 Grant 只有 `direct` 和 `group`;管理命令中的 `all` 会展开为两条 Grant。
- `deny` 和 `revoke` 不同:拒绝后不再生成请求;撤销后用户可以再次请求。
## 批准流程
未批准用户发送私聊消息时,Messenger Power 会创建或复用一个 pending Request,并返回类似命令:
```bash
city power action chat access-approve assistant --input '{"request_id":"req_xxx"}' --token
```
管理员也可以先查看请求:
```bash
city power action chat access-snapshot assistant --input '{}' --token
```
群聊中的未批准消息默认静默拒绝,pending Request 仍会进入同一个管理列表。
## 数据保存位置
每个 Agent 独立保存:
```text
~/.downcity/agents//powers/messenger/messenger/access.db
```
Chat Access 数据库包含 Principal、Request、Allow/Deny Grant 和审计事件,不包含 Bot Token、App Secret 或消息正文。Messenger 渠道凭据属于 `~/.downcity/powers/messenger/config.toml` 中的唯一明文配置;Messenger Config UI 读取时不会返回凭据原文。
## 与 City Auth 的区别
Agent Token 负责 HTTP 控制面认证。一个 Token 只属于一个 Agent,并拥有该 Agent API 的完整能力,不包含 User、Role 或 Permission。Chat Access 负责外部 Telegram、飞书或 QQ 用户能否向某个 Agent 发送消息。两者数据、身份和判定路径互不混用。
## 相关文档
- [CLI 命令](/zh/docs/cli/commands)
- [Messenger Power](/zh/docs/power/messenger)
- [`.downcity` 目录](/zh/docs/reference/dot-downcity)
### 数据存储与权限
Source: https://downcity.ai/zh/docs/security/data-security/
本地 CLI 与 Desktop 状态采用明文 SQLite/JSON 文件存储:
1. Workspace 索引、平台设置与本地 Token:`~/.downcity/downcity.db`
2. Agent 定义与主体指令:`~/.downcity/agents//agent.json`、`SOUL.md`
3. Power 定义与唯一配置:`~/.downcity/powers//power.json`、`config.toml`
## 文件权限与边界
数据库文件、Agent 配置目录与 Power 配置文件默认限制为当前用户可读写(数据库和配置文件为 `0600`,目录为 `0700`)。这不是加密存储;能够读取本机用户文件的进程也能够读取这些配置。
`city env` 是显式的文件配置能力:Global Env 以明文写入 `~/.downcity/.env`,Workspace Env
以明文写入项目 `.env`。Global 文件权限限制为仅当前用户可读写;项目 `.env` 默认加入
`.gitignore`。如需更强的密钥保护,应通过启动进程或密钥管理系统注入环境变量。
## 用户侧最佳实践
1. 不要提交 `~/.downcity` 或任何本地配置文件到版本库。
2. 不要提交 Workspace `.env`,并限制 `~/.downcity/.env` 的文件访问权限。
3. 需要更强的密钥保护时,通过启动进程或操作系统密钥管理系统注入环境变量。
## 相关文档
- [Model 绑定](/zh/docs/configuration/model)
- [Model 配置](/zh/docs/configuration/model)
### CLI
Source: https://downcity.ai/zh/docs/cli/overview/
Downcity 安装包提供两个独立工具:
- `city`(别名 `downcity`)是本机 City 容器,管理 Agent、Power、环境变量和 Federation 连接。
- `fed`(别名 `downfed`)是 Federation Server Manager;TUI 管理已注册 Server,`fed web` 启动本地 Web 控制面,项目命令读取当前目录的 `federation.toml`。Federation 项目配置只支持 TOML,不兼容 JSON 配置。
本地部署未设置 `deployment.port` 时固定使用默认端口 `12314`,在 `[deployment]` 中显式设置 `port` 可覆盖默认值。选定端口被占用时部署直接报错,不扫描其他端口,也不从部署历史推断端口。
## City 数据模型
Agent 与 Workspace 是两个独立的全局实体。Agent 由 `agent_id` 标识,结构化定义位于 `~/.downcity/agents//agent.json`,稳定主体指令位于同目录的 `SOUL.md`。Workspace 由 `workspace_id` 标识并指向项目目录。一个 Agent 可以进入多个 Workspace,双方都不保存持久化绑定。CLI 与 Desktop 分别拥有独立的 City,但共享同一套用户级文件和 Workspace 索引。
Federation Admin 配置与 Embassy User Session 也统一保存在 `~/.downcity/downcity.db`。升级后,旧 `~/.downcity/federation.db` 中的管理配置会被一次性迁入;旧文件保留用于人工恢复,但运行时不再读取。
每个 Power 使用稳定 ID 对应 `~/.downcity/powers//`,唯一明文配置位于 `config.toml`。第三方 Power 的安装目录包含唯一 `power.json`、建立 ESM 边界的 `package.json`,以及清单声明的可选 `main`、`renderer` 自包含入口,不包含源码和构建配置。City 会把已登记的 Power 和同一份配置提供给全部 Agent;`agent.json` 不保存 Power 引用。`downcity.db` 只保存 Workspace 索引、Token 和平台状态,不保存 Agent 或 Power 配置。
## City 命令
| 命令 | 说明 |
|---|---|
| `city agent` | 管理全局 Agent |
| `city power` | 管理 Power 制品、唯一配置与 Action |
| `city env` | 管理 City 注入的环境变量 |
| `city federation` | 管理 Federation 连接 |
自动化脚本可以用 `DOWNCITY_FEDERATION_URL` 和 `DOWNCITY_USER_TOKEN` 覆盖当前 Embassy 用户身份。旧的 `DOWNCITY_CITY_URL`、`DOWNCITY_CITY_USER_TOKEN`、`CITY_URL` 与 `CITY_USER_TOKEN` 不再解析。
`city init`、`city update` 和 `city config` 不再提供。全局更新使用 `npm i -g downcity@latest`。
所有操作单个 Agent 的命令都以 `agent_id` 为目标。TTY 中省略 ID 时打开全局 Agent 选择器;非交互环境会返回 `Agent ID is required`,不会根据当前目录推断。
## 平台支持
CLI 架构天然跨平台。macOS 与 Linux 是稳定支持目标;Windows Adapter 当前为 preview。
继续阅读:[CLI 命令](/zh/docs/cli/commands)。
### CLI 命令
Source: https://downcity.ai/zh/docs/cli/commands/
## City 生命周期
```bash
city on # 启动唯一 CLI City daemon
city on --port 5314 --rpc-port 15314
city status
city restart
city off
city reset # 确认后重置本地配置数据库
city reset --yes # 跳过确认
```
CLI City 使用一个 HTTP 端口和一个原生 TCP RPC 端口,并在两个协议内按 `agent_id` 路由全部 Agent。
`city reset` 会先停止 CLI City daemon,再删除 `downcity.db`、`downcity.db-wal` 和 `downcity.db-shm`。它不会删除 `.env`、Agent/Power 配置或 Workspace 中的 Session 文件。
## Agent
```bash
city # 直接打开 Agent 列表
city agent # 打开同一个 Agent 列表
city agent create [path] # 不传路径:当前目录或系统文件夹选择窗口
city agent list
city agent model [agent_id]
city agent chat [agent_id]
```
裸 `city` 命令直接打开 Agent 列表,不展示 Agent runtime 状态。`city agent list` 以 `名称 · agent_id` 展示每个 Agent。Federation、全局 Powers、语言和命令帮助直接位于同一列表末尾的“设置”分组。
City 装配的 Agent 默认启用 `ask_user` Tool。在
`city agent` 面板选择 Agent 后会直接进入最近一次对话,并跟随该 Session 所属 Workspace;该 Agent 还没有历史时,在入口 Workspace 新建 Session。模型需要关键补充信息时会显示文本、单选或多选面板;CLI 将完整答案
提交给当前 Session,并继续同一个 Turn。按 Esc 可停止当前 Turn。
密码、API Key 和 Token 使用 `ask_user` 的 `type: "secret"`,并提供 snake_case 格式的
`name`。本地 Session 以遮蔽输入收集私密值,提交前要求确认数量、变量名以及可能覆盖已有同名值。
模型只接收 Session 私密引用;明文仅存在当前 Session 内存中,释放或重启后丢失。
缺少专用私密提交接口的 CLI 传输会在收集输入前拒绝私密表单,请使用 Desktop 或本地 Session。
不要在普通聊天或文本问题里粘贴凭据。
Agent 与 Workspace 独立登记。Agent 每次执行时进入所选 Workspace,不保存持久化 Workspace 绑定。Agent 没有独立启动状态;`city agent chat --session-id ` 必须指向已存在的 Session,并进入该 Session 所属 Workspace;`--workspace ` 会把 Chat 限定在该 Workspace:只在其中查找 Session、必须与所选 `--session-id` 的 Workspace 一致,新 Session 也会创建在那里。Chat 内使用 `/new` 创建新 Session、`/session` 选择已有 Session 或新建 Session、`/config` 打开 Agent 配置,配置完成后会回到原对话。City 运行时 Chat 走 RPC,脚本化的一次性调用在 City 关闭时仍可使用本地装配路径。
在输入框中可以使用 slash command 打开系统文件选择器并添加本地附件:
```text
/attach
```
附件会加入下一条消息;也可以使用 `/file` 别名。Unix 终端的 `Ctrl-V`(Windows 为 `Alt-V`)会优先尝试粘贴剪贴板中的图片或文件,无法识别时仍按普通文本粘贴处理。
审批请求在专用面板中完成,不再使用 `/approve` 或 `/deny` slash 命令。
## City Token
Token 由 City 管理,授权访问指定的 Agents,或明确允许全部现有及未来 Agents。`city` 就是命令入口,`downcity` 是别名,不需要 `downcity city`。
```bash
city token # 交互式创建、查看、修改和撤销
city token create # 按步骤填写并确认
city token list
city token create --name chrome --agents researcher,programmer --never-expires
city token create --name automation --all-agents --expires-at 2027-01-01T00:00:00Z
city token update --agents researcher
city token update --expires-at 2027-02-01T00:00:00Z
city token delete
```
创建时名称、授权范围和有效期必须明确:不完整参数在终端中交互补齐,在脚本或管道中报错。交互支持 Agent 多选、30/90 天、永不过期及自定义日期,提交前显示配置供确认。`update` 或 `delete` 不传 ID 时交互选择;参数完整时直接执行。命令支持 `--json`。
明文只在创建成功时显示一次,列表和详情只含摘要。把明文填入 Chrome 的访问凭据,不要发送到聊天。丢失后重新签发。删除或缩小授权范围会拒绝后续访问,并在约一秒的权限复查周期内关闭受影响 HTTP 长连接;取消不能撤销已经发生的外部副作用。
旧的 `city agent token` 命令和 Agent Token 不再用于认证,请通过 `city token create` 重新签发。已有旧表不自动迁移或扩权。凭据管理只通过本机 CLI;连接 Token 不自动获得创建或撤销其他 Token 的权限。
## Power
`city power list` 会展示每个 Power 的标题、稳定 ID、用途、来源和是否提供 Config。
```bash
city power list
city power install
city power update
city power uninstall
city power inspect
city power config
city power config --set '{"key":"value"}'
city power action [agent_id] --input '{"key":"value"}' --token
```
一个第三方来源目录只定义一个 Power。`power.json` 声明 `schema_version: 1`、全局唯一 `id`、版本、必填的 `.md` `readme` 相对路径,以及可选的 `main`、`renderer`。`main` 是自包含的统一 City Power ESM;`renderer` 对象声明单文件 ESM 入口以及 `sidebar`、`mainview`、`config` 三项静态能力,Sidebar 与 Mainview 必须成对出现。两个运行入口至少提供一个。`package.json` 必须声明 `"type": "module"`。安装目录只保留声明制品、文档、可选图标与本地 `config.toml`;安装过程不会执行依赖安装、构建脚本或任何第三方入口。
声明 Config 的 Power 在 `powers//config.toml` 中保存唯一配置。具体结构、校验、Secret
投影和 Config UI 都由 Power 自己管理。CLI 的 `config --set` 仅用于显式替换完整 JSON,不生成
通用表单,也不会输出凭据原文;无 `--set` 时只显示是否已配置和字段名。
City 自动把全部已注册 Power 提供给全部 Agent;`agent.json` 不保存 Power 引用或配置。需要多账号
时,由 Power 在自己的配置结构中表达账号集合和选择规则。配置保存后,Power 负责刷新受影响的长期资源。
CLI、Agent 的 Power 工具、HTTP 与定时任务统一调用 Power Action。不存在 `power command`,Chat 也不再是顶层命令特例。
## Env 与 Federation
```bash
city env # 打开 Env TUI
city env list --global
city env list --agent
city env set --global
city env set --agent
city env delete --global
city env delete --agent
city federation
```
Global Env 写入 `~/.downcity/.env`;Workspace Env 写入项目根目录的 `.env`。也可以从
`city agent` 的“配置 Env”入口选择 Agent 所使用的 Workspace。修改完成后,CLI City 会更新受影响的 runtime
Agent,并通过 Workspace 将新快照广播给已有 Session;未被该 City 持有的 Agent
会在下一次被 City 装配时读取新配置。
多个 Agent 在同一 Workspace 运行时共享同一个项目 `.env`。运行时优先级为:Global `.env`
低于 Workspace `.env`,启动进程显式环境变量最高。`list` 不显示明文值;`copy` 只允许从
本机 CLI 显式执行。
Federation 用户请求统一通过 Embassy。交互登录态保存在 `~/.downcity/downcity.db`;自动化脚本可以用
`DOWNCITY_FEDERATION_URL` 与 `DOWNCITY_USER_TOKEN` 显式覆盖当前登录态。这两个身份变量不会从
Global `.env` 注入 Workspace 进程。
## Fed
```bash
fed # Federation Server 管理 TUI
fed web --id fed_x # 启动本次指定 Federation 的本地 Web 管理 UI
fed web --name my-fed --no-open --port 43128
fed server add
fed server --id fed_x
fed manage --id fed_x
fed server manage --id fed_x
fed bureau token --id fed_x # 打开 Bureau Token 管理 TUI
fed bureau token --id fed_x issue
fed bureau token --id fed_x list
fed bureau token --id fed_x revoke
fed query GET /health --id fed_x
fed status --id fed_x
fed logs --id fed_x
fed stop --id fed_x
fed restart --id fed_x
fed clean --id fed_x --dry-run # 只预览
fed clean --name my-fed # 预览后交互确认
fed clean --id fed_x --yes # 非交互显式确认
fed backup --id fed_x # 在线 SQLite 快照,包含 WAL
fed restore --id fed_x --path /path/to/backup_id --dry-run
fed restore --id fed_x --path /path/to/backup_id --yes
fed create # --path 默认是 .
fed create --path ./my-fed
fed deploy # --path 默认是 .
fed deploy --path ./my-fed
```
`fed create` 和 `fed deploy` 使用显式的 `--path `,默认是 `.`,不接受位置路径参数。
Fed 没有全局 active/default Federation,也不保存 `active_server_url`。`stop`、`restart`、`clean`、`backup`、`restore`、`status`、`logs`、`query`、`web`、`server`、`manage` 与 `server manage` 支持互斥的 `--id ` 或 `--name `,ID 和名称均精确匹配。省略选择参数时,TTY 显示列表,选择只用于本次操作;非交互环境缺少参数时报错。名称重名时,TTY 继续选择,非 TTY 报错。列表没有表示全局当前连接的星标。`fed manage --id fed_x` 直接打开目标管理工作区,不接受 action 位置参数;`fed server manage` 支持同样的选择参数。
Bureau Token 命令遵循相同的目标选择规则。选择参数也可放在 `token` 父命令上,例如 `fed bureau token --id fed_x list`;签发、列表与撤销保留既有命令结构。
`fed status` 可查询任意已保存连接,展示 registry record 和 `/health` 实时探测结果;本地实例还单独显示 launchd/systemd manager 状态。登记记录、系统服务状态和健康探测是独立信息。本地 release 的健康响应必须为 `ok: true`,且 `fed_id`、`release_id`、`instance_id` 全部匹配受管实例。`fed logs`、`fed stop` 和 `fed restart` 仅支持 CLI 管理的 local 实例。日志读取现有 `service.log`。`stop` 禁用自动启动并停止服务,停止状态跨系统重启保留,直到用户显式执行 `fed deploy` 或 `fed restart`;这些操作按持久配置恢复自动启动策略。重启只使用已安装 release 和持久运行配置,不读取或构建源码;原项目删除后仍可重启。显式指定的数据库使用绝对路径,删除项目时应保留该数据库。管理界面的 Remove connection 只移除已保存连接,不停止服务。
`fed clean` 仅清理本地已登记 Fed 的 release;省略互斥的 `--id` / `--name` 时,TTY 列表选择只用于本次操作,非 TTY 报错。先预览 release ID、大小和删除或保留原因,再确认删除。`--dry-run` 只预览;非交互删除必须显式传入 `--yes`,仍须通过保护检查。默认始终保留最近 3 个成功 release,不开放 `--keep` 参数。
`current.json`、registry、服务 `launch.json`(含恢复待运行)及进行中尝试引用的 release,以及候选清理结果无法确认的 release 均受保护。未知、损坏或没有可信发布记录的 release 保留并解释原因。运行器不可验证等保护信息错误直接拒绝清理。同一 Fed 的锁在目标选择后覆盖预览、确认和删除,阻止并发切换。失败产物仅通过手动 `fed clean` 删除,CLI 不自动清理 release;`clean` 不删除 data、config、logs、staging 或部署历史。发布尝试保存在 `~/.downcity/federation/deployments//attempts/.json`,用于识别成功与失败历史,release 删除后历史仍保留。详见[清理本地 release](/zh/city-sdk-docs/packages/cli/quickstart#清理本地-release)。
`fed backup` 为本地受管部署创建一致性 SQLite 在线快照。`fed restore --path ` 要求服务已明确停止,校验备份归属、SHA-256 和 SQLite 完整性,先保全当前数据库,再确认并原子替换;完成后不启动服务。`--dry-run` 只读预检,非交互覆盖必须明确传入 `--yes`。备份文件权限为 `0600`,可能包含账号、会话和密钥,不进入 Git 或 release。恢复不切换应用版本,也不保证跨版本 schema 兼容。详见 [SQLite 备份与恢复](/zh/city-sdk-docs/packages/cli/backup-and-restore)。
本地发布的安装目录、运行配置、Node 环境要求与 dry-run 边界见[本地独立 Node 发布](/zh/city-sdk-docs/packages/cli/quickstart#本地独立-node-发布)。本地保留 `deployment.scripts.build`,拒绝 `deployment.scripts.deploy`。
本地服务由 macOS 用户级 launchd 或 Linux 用户级 systemd 管理。`federation.toml` 的 `[deployment.process]` 支持 `auto_start = false`(默认)和 `restart_on_failure = true`(默认),仅接受布尔值,未知字段报错;Workers 配置此表时报错。异常恢复间隔固定为 10 秒,60 秒内最多 5 次。只有显式设置 `auto_start = true` 才持久安装到 macOS `~/Library/LaunchAgents` 或启用 Linux 用户级 `default.target.wants`;macOS 在用户登录后启动,Linux 需要用户 manager 可用,CLI 不自动开启 linger,也不保证 Linux 开机即可启动。系统服务定义不包含 secret,运行配置独立保存。配置示例见 [CLI 快速开始](/zh/city-sdk-docs/packages/cli/quickstart)。
`fed web` 默认在 `http://127.0.0.1:43128` 启动本地控制面,目标来自
`--id` / `--name` 或本次 TTY 列表选择。管理员会话 Token 只由本地 CLI
进程持有,不会发送到浏览器;为避免把 Federation 管理控制面暴露到网络,该命令只允许监听
`127.0.0.1`、`localhost` 或 `::1`。页面包含 Dashboard、用户、Bureau、模型、Env、
Credits、Usage、支付、Service 目录与调试器。分析区进一步分为数据概览、用户活跃、
Usage 消耗、用户留存、调用质量和用户明细。
Usage Dashboard 以浏览器所在 IANA 时区统计:日活是今日产生至少一次 AI Usage 的去重
用户,周活和月活分别是滚动 7 天与 30 天去重用户。用户用量页展示所有注册用户,包括
零用量用户;默认按 Total Tokens 降序排列,与总览的 Token 消耗排行使用相同口径,也可按
调用数、Credits、P95 耗时与最后活跃时间排序。每个用户同时展示 Input、
Output、Total Token、成功率、Top Model、平均/P95 耗时和已入账 Credits 消耗。图表包含
DAU/WAU/MAU 折线、24 小时活跃柱状图、Token 堆叠图、模型与 Action 分布、执行结果与
耗时趋势,以及 D1/D3/D7/D14/D30 Cohort 留存表和漏斗。
### 项目初始化
Source: https://downcity.ai/zh/docs/cli/init/
`city agent create` 会独立登记 Workspace,并创建 Agent 的用户级 `agent.json` 与 `SOUL.md`。它不会在 Workspace 中生成 Agent 声明,也不会保存 Agent-Workspace 绑定。
```bash
city agent create
```
不传路径时,交互流程可以直接使用当前目录,或者打开操作系统原生文件夹选择窗口。传入相对路径或绝对路径则直接使用该路径,不进入目录选择流程:
```bash
city agent create .
city agent create ./my-project
city agent create /absolute/path/to/my-project
```
生成结构:
```text
my-project/
├── .env
├── .agents/
│ └── skills/
└── .downcity/
```
Agent 定义写入 `~/.downcity/agents//agent.json`,主体指令写入同目录的 `SOUL.md`;Workspace 登记仍保存在 `downcity.db`。项目 `.env` 会覆盖 `~/.downcity/.env` 中的 Global Env;启动进程显式环境变量拥有最高优先级。
```bash
# 允许覆盖现有 Agent 文件定义
city agent create ./my-project --force
```
初始化后,可在 `.agents/skills` 添加项目 Skills,通过 `city agent list` 查看生成的 `agent_id`,直接运行 `city agent chat `,或执行 `city on` 启动长期 City 宿主。
继续阅读:
- [项目结构](/zh/docs/cli/project)
### 项目结构
Source: https://downcity.ai/zh/docs/cli/project/
Agent 定义、Power 配置与运行数据都使用用户级文件。项目目录只作为 Workspace,保留项目环境、Skills 和业务源码。
## 目录布局
```text
my-project/
├── .env # 项目环境变量
├── .agents/
│ └── skills/ # 用户管理、可进入版本控制的 Skills
└── src/ # 业务代码(可选)
```
## 全局配置
用户级配置结构为:
```text
~/.downcity/
├── agents//
│ ├── agent.json
│ ├── SOUL.md
│ └── sessions/
│ ├── /
│ ├── archived-sessions/
│ └── logs/
├── powers//config.toml
├── runtimes/city/
└── downcity.db
```
`downcity.db` 保存 Workspace ID 与路径、Token 和平台状态,不保存 Agent 定义、Power 配置或 Agent-Workspace 绑定。CLI 与 Desktop 读取同一套文件与数据库。
`agent_id` 与 `workspace_id` 是彼此独立的全局身份。Session 只在一次具体执行时接收 Workspace。CLI City 的 daemon 状态记录在 `~/.downcity/runtimes/city/`;Session 保存在 `~/.downcity/agents//sessions/` 下。只有传入 Workspace 时,Session 的 `meta.json` 才记录 `workspace_id`。
## 项目资产
Global Env 单独保存在 `~/.downcity/.env`。项目 `.env` 覆盖 Global Env,启动进程显式环境变量拥有最高优先级;项目 `.env` 默认加入 `.gitignore`。`.agents/skills` 是项目中唯一由用户管理并进入版本控制的 Agent 能力资产。
## 运行数据
Downcity 不再创建 `/.downcity/`。Agent 运行数据统一保存在 City 提供的 `agents//` 存储作用域;没有 City 时保存在内存中。Power 自有数据使用 PowerContext 提供的 Agent 级存储作用域。
继续阅读:
- [项目初始化](/zh/docs/cli/init)
- [Agent SDK](/zh/docs/agent/sdk)
### Agent CLI
Source: https://downcity.ai/zh/docs/cli/cli/
`city` CLI 是本地 City 宿主。它读取 Agent 与 Power 配置,分别创建 Agent、Workspace 和唯一 Power 实例,再由 City 统一管理组合关系与长期运行生命周期。
## 项目初始化
```bash
city agent create
```
不传路径时,可以选择当前目录或通过系统原生窗口选择其他文件夹;也可以显式传入相对路径或绝对路径,例如 `city agent create .`、`city agent create ./my-project`。
这会生成:
- `.agents/skills/`
- `.downcity/`
- `.env`
- CLI 全局 DB 中的 Agent 配置
## 项目目录结构
```text
my-project/
├── .env
├── .agents/skills/
├── .downcity/ # 仅运行数据
└── 你的业务代码
```
## 关键命令
- `city` — 直接打开 Agent 列表;Federation 与全局 Power 操作位于同页的“设置”分组
- `city on` — 启动 CLI City,并恢复全部已绑定 Agent
- `city status` — 查看 City、HTTP/RPC 端口与已配置 Agent
- `city restart` — 重启 City 并重新加载配置
- `city off` — 停止 CLI City
- `city agent chat [agent_id]` — 与 Agent 对话;City 未开启时也可使用
## Chat TUI 安全策略
从 Agent 列表直接进入最近对话后,使用 `/security` 打开当前 Session 的安全策略选择器:
- `Default` — 对应 Session 的 `ask` 模式;每次 host Shell 操作都需要明确审批。
- `Always Allow` — 对应 `always-allow` 模式;当前 Session 后续的 host Shell 操作会自动批准。
当前策略展示在 Chat Header 中。策略只影响当前 Session 的后续 Shell 请求;已经等待审批的请求仍需单独处理。`Always Allow` 不会绕过危险命令拒绝、Workspace 边界或其他运行时安全检查。
## CLI 做了什么
1. 从 CLI 全局 DB 读取 Agent 配置
2. 通过已连接的 Federation AIService 解析 `execution.modelId`
3. 将解析后的配置传给 `new Agent(...)`
4. CLI 从 Repository 读取配置并显式创建 Agent,再注册到 `new City(agents)`
5. 在一个 HTTP 端口和一个 RPC 端口上按 `agent_id` 暴露 Agent
## CLI vs SDK
CLI 用于日常项目管理。SDK 用于将 Agent 能力嵌入自己的应用。两者使用相同的执行核心。
继续阅读:
- [Agent SDK](/zh/docs/agent/sdk)
- [Agent 生命周期](/zh/docs/agent/lifecycle)
### CLI 命令
Source: https://downcity.ai/zh/docs/reference/cli/
Downcity docs 解释设计模型、运行边界和配置语义。
`downcity` / `city` 是基于 `City()` 与 Agent SDK 的本机 City 容器,负责全局 Agent 管理、运行控制与控制台。`fed` / `downfed` 是 Federation Server Manager,TUI 管理已注册 Server,项目命令读取当前目录的 `federation.toml`,项目配置只支持 TOML,不兼容 JSON 配置;精确参数以本机安装的 CLI help 为准。
本地部署未设置 `deployment.port` 时固定使用默认端口 `12314`,在 `[deployment]` 中显式设置 `port` 可覆盖默认值。选定端口被占用时部署直接报错,不扫描其他端口,也不从部署历史推断端口。
- [CLI:fed 与 city](/zh/city-sdk-docs/packages/cli)
## 本地帮助
精确参数以本机安装的 CLI help 为准。产品文档负责说明命令组和常见工作流。
## 交互式 TUI
不带子命令运行 `city` 或 `downcity` 时,现在默认进入交互式 TUI。`city` 侧聚焦本机 Agent 与 Federation 连接状态;`fed` 侧聚焦 Federation 管理与部署。两个 CLI 都保持同一套稳定布局:左侧 sidebar 承载菜单层级,顶部显示 breadcrumb,loading、输入表单、表格、JSON、消息与选择详情都在右侧 section 内完成,直到你主动退出 TUI。
## CLI 语言切换
`city` 和 `downcity` 现在都支持中文与英文。
- 通过 `--lang zh` 或 `--lang en` 显式切换当前命令语言。
- 如果没有传 `--lang`,CLI 会优先读取最近一次在交互菜单中保存的默认语言,然后再依次读取 `DC_CLI_LANG`、`LC_ALL`、`LC_MESSAGES`、`LANG`。
- 在交互模式下,`city` 和 `downcity` 都可以直接从菜单切换语言,并把该选择持久化到本地。
示例:
```bash
downcity --lang en --help
city --lang zh
DC_CLI_LANG=zh downcity agent --help
```
### .downcity 目录
Source: https://downcity.ai/zh/docs/reference/dot-downcity/
`~/.downcity/` 是 Downcity 的用户级配置与运行数据目录。Downcity 不会在每个项目中创建 `.downcity/` 目录。
## 常见结构
```text
~/.downcity/
├── agents//
│ ├── agent.json
│ ├── SOUL.md
│ ├── sessions///
│ ├── archived-sessions///
│ └── logs/
├── powers//
│ └── config.toml
├── runtimes/city/
└── downcity.db
```
## 重点目录
### `agents//logs/`
每日 JSONL 日志:`.jsonl`。
### `agents//sessions///messages/`
会话消息事实源:`active.jsonl`、`agent_message.json` 与按 sequence 命名的 `segments/*.jsonl`。
`category` 只有 `chat` 与 `work` 两个值,是唯一进入目录名的字段;角色 `type` 记录在
Session 元数据里。
### Memory
长期 Memory 不属于 Workspace `.downcity/` 协议。Agent 私有内容位于 `agents//powers/memory/`;City 共享的 User/Workspace 内容位于 `memory/`,并由 `MemoryPower` 按 Subject 隔离。City 只提供共享根路径,不实现 Memory 数据逻辑。
### Power 运行数据
Power 自有运行数据使用 PowerContext 提供的 Agent 级存储作用域。Power 定义与唯一配置保存在 `~/.downcity/powers//`。
### Skills 目录位置
`SkillPower` 默认扫描 `.agents/skills`(项目级)。如果在构造函数中启用 `use: ["home"]`,也会扫描 `~/.agents/skills`(用户级)。
## 安全建议
- `~/.downcity/` 可能包含敏感配置、对话、Token 与执行痕迹。
- 不要把该目录提交到版本库或复制到不受信任的位置。
### HTTP API 参考
Source: https://downcity.ai/zh/docs/reference/api/
> 面向用户的 Agent API。更多细粒度命令建议优先使用 CLI(`downcity ...`)。
## 基础接口
### `GET /health`
```json
{ "status": "ok", "timestamp": "2026-03-08T12:00:00.000Z" }
```
### `GET /api/status`
```json
{ "name": "downcity", "status": "running", "timestamp": "..." }
```
### `POST /api/execute`
请求体:
```json
{
"instructions": "帮我总结今天的改动",
"chatId": "default"
}
```
## 托管 Power API
### `GET /api/powers/list`
列出托管 Power 运行状态。
## Power API
### `GET /api/powers/catalog`
列出已注册的 Power。
### `POST /api/powers/availability`
```json
{ "power_name": "sound" }
```
### `POST /api/powers/action`
```json
{
"power_name": "sound",
"action_name": "models",
"payload": { "capability": "asr" }
}
```
## Console UI API(摘要)
### `GET /api/ui/powers`
返回 Power 摘要与可用性信息(适用于 Console UI 面板)。
返回字段示例:
```json
{
"success": true,
"powers": [
{
"name": "sound",
"actions": ["models", "asr", "tts"],
"pipelines": ["chat.augmentInbound"],
"guards": [],
"effects": [],
"resolves": [],
"hasSystem": true,
"hasAvailability": true,
"availability": {
"enabled": true,
"available": true,
"reasons": []
},
"config": {
"actions": [
{
"name": "models",
"supportsCommand": false,
"supportsApi": false,
"apiMethod": "",
"apiPath": ""
}
]
}
}
]
}
```
### `POST /api/dashboard/sessions/:sessionId/execute`
在指定会话执行一轮(例如你在 UI 里选中的 chatKey)。
带附件请求示例:
```json
{
"instructions": "请阅读附件 markdown,并给出可执行摘要。",
"attachments": [
{
"type": "document",
"fileName": "page.md",
"contentType": "text/markdown; charset=utf-8",
"content": "# Captured Web Page\n\n..."
}
]
}
```
说明:
- `sessionId` 应传 runtime 返回的目标会话 ID。聊天场景下该 ID 由 chat Power 维护映射(不再要求可由平台字段直接拼接)。
- 附件会先被 runtime 落盘,再以 `` 标签自动注入到用户消息前部。
- 当 `sessionId` 映射到 chat 会话时,会复用 chat Power 的同一条执行队列(与平台入站消息一致),并在执行前写入 chat history。
- chat 上下文调用会立即返回排队结果(`queued=true`、`queueItemId`、`queuePosition`)。
## Action 路由
Power Action 使用这些入口:
- `/api/powers/action`
除 `GET /health` 外,Agent HTTP API 需要该 Agent 自己的 Bearer Token。Token 不包含 User、Role 或 Permission;它只允许访问所属 Agent。
## 调试建议
先确认 runtime 已启动。启动流程见 [Agent start 工作流](/zh/docs/reference/cli);health endpoint 属于已运行的 Agent HTTP 表层。
### 贡献指南
Source: https://downcity.ai/zh/docs/community/contributing/
感谢您有兴趣为 Downcity 做贡献!本指南将帮助您开始。
## 贡献方式
### 🐛 报告错误
发现了 bug?报告它:
1. 先搜索现有问题
2. 创建 bug 报告,包含:
- 清晰的标题和描述
- 重现步骤
- 预期 vs 实际行为
- 环境详情(操作系统、Node 版本等)
- 相关截图(如适用)
### 💡 建议功能
有好主意?提议它:
1. 检查路线图和现有讨论
2. 创建功能请求,包含:
- 问题陈述
- 建议的解决方案
- 用例
- 潜在的实现
### 📖 改进文档
文档也是代码!您可以:
- 修正拼写和语法
- 添加示例
- 澄清混淆的部分
- 翻译成其他语言
- 添加新指南
### 🔧 代码贡献
准备编码?太好了!
1. 从标记为 `good-first-issue` 的问题开始
2. 遵循下面的贡献指南
3. 提交拉取请求
---
## 开发设置
### 前提条件
- Node.js >= 18
- pnpm(推荐)或 npm
- Git
### Fork 和克隆
```bash
# 在 GitHub 上 fork 仓库
# 克隆您的 fork
git clone https://github.com/YOUR_USERNAME/downcity.git
cd downcity
# 添加 upstream 远程
git remote add upstream https://github.com/genesiscosmos/downcity.git
```
### 安装依赖
```bash
# 安装依赖
pnpm install
# 设置开发环境
pnpm dev:setup
```
### 构建和测试
```bash
# 构建项目
pnpm build
# 运行测试
pnpm test
# 运行 linter
pnpm lint
# 类型检查
pnpm typecheck
```
---
## 项目结构
```
downcity/
├── packages/
│ ├── cli/ # CLI 工具
│ ├── core/ # 核心 agent 逻辑
│ ├── llm/ # LLM 提供商实现
│ └── tools/ # 内置工具
├── private/apps/homepage/ # 文档站点
└── examples/ # 示例配置
```
---
## 进行更改
### 分支策略
```bash
# 创建功能分支
git checkout -b feature/my-feature
# 或修复 bug
git checkout -b fix/issue-123
# 或文档
git checkout -b docs/update-guide
```
### 提交消息
遵循约定式提交:
```
feat: 添加对自定义工具的支持
fix: 解决任务调度器中的竞态条件
docs: 更新安装指南
chore: 升级依赖
test: 为权限系统添加测试
refactor: 改进 LLM 提供商抽象
```
### 代码风格
遵循项目的代码风格:
```bash
# 运行格式化工具
pnpm format
# 运行 linter
pnpm lint:fix
# 类型检查
pnpm typecheck
```
---
## 拉取请求流程
### 提交之前
1. **运行测试**:`pnpm test`
2. **格式化代码**:`pnpm format`
3. **检查类型**:`pnpm typecheck`
4. **更新文档**:如适用
5. **添加测试**:针对新功能
### 提交 PR
1. 推送到您的 fork
2. 创建拉取请求到 `genesiscosmos/downcity:main`
3. 填写 PR 模板:
- 更改描述
- 相关问题
- 测试步骤
- 破坏性更改(如有)
### 审查流程
维护者将审查您的 PR 并提供反馈。解决审查意见并更新您的分支。
### 合并
一旦批准,您的 PR 将被合并。维护者将:
- 如需要则压缩提交
- 更新更新日志
- 部署到生产环境
---
## 编码标准
### TypeScript
- 使用严格模式
- 避免 `any` 类型
- 优先使用 `const`/`let` 而不是 `var`
- 回调使用箭头函数
- 为公共 API 编写文档
- 在 `cli/city/src` 内可使用 `@/` 路径别名(映射到 `src`),`pnpm build` 会自动回写为 `bin` 中可运行的相对路径
### 测试
- 为新功能编写单元测试
- 目标是 >80% 的代码覆盖率
- 模拟外部依赖
- 测试边缘情况
### 文档
- 为公共 API 编写文档
- 添加 JSDoc 注释
- 包含使用示例
- 如果行为更改,更新指南
---
## 开发工作流程
### 功能开发示例
```bash
# 1. 创建分支
git checkout -b feature/add-discord-power
# 2. 进行更改
# ... 编辑文件 ...
# 3. 提交更改
git add .
git commit -m "feat: 添加 Discord bot 集成"
# 4. 测试
pnpm test
# 5. 推送到 fork
git push origin feature/add-discord-power
# 6. 在 GitHub 上创建 PR
# 访问您的 fork 并创建拉取请求
```
### 与上游同步
保持您的 fork 最新:
```bash
# 获取上游更新
git fetch upstream
# 合并上游 main
git checkout main
git merge upstream/main
# 推送到您的 fork
git push origin main
```
---
## 社区准则
### 行为准则
- 保持尊重和包容
- 提供建设性反馈
- 优雅地接受反馈
- 关注什么对社区最有利
### 获取帮助
- 在 Discord 中提问
- 为复杂主题开始讨论
- 尽早请求审查(WIP PR)
---
## 开发者起源证书
通过贡献,您同意 DCO:
```
开发者起源证书
版本 1.1
1. 开发者和利益相关者通过贡献和补丁与项目的合作
是项目的预期合作和协作方法。
2. 开发者保证:
(a) 贡献全部或部分由我创建,我有权在文件中
指示的开源许可证下提交;或
(b) 贡献基于先前的工作,据我所知,涵盖在适当的
开源许可证下,我有权在该许可证下提交该工作,
包括对其进行的修改,无论是全部或部分由我创建,
与该项目相关的同一开源许可证(除非被允许
在不同许可证下提交),如文件中所示;或
(c) 贡献直接由我提供的其他一些创建、认证 (a)、(b)
或 (c) 且我未修改它的人。
(d) 我理解并同意该项目和贡献是公开的,贡献记录
(包括我提交的所有个人信息,包括我的签名)
将无限期维护,并根据该项目或所涉及的开源许可证
一致地重新分发。
```
添加到您的提交:
```bash
git commit -s -m "feat: 添加新功能"
```
---
## 项目特定指南
### 核心包更改
对于 `packages/agent` 的更改:
- 为新功能添加测试
- 如需要更新架构文档
- 考虑向后兼容性
### CLI 更改
对于 `cli/city` 的更改:
- 更新 CLI 帮助文本
- 添加使用示例
- 为新命令编写文档
### 文档更改
对于 `private/apps/homepage/` 的更改:
- 本地测试:`pnpm dev`
- 检查损坏的链接
- 如需要更新导航
---
## 资源
### 文档
- [架构](/zh/docs/concepts/architecture) - 系统架构
- [Power 命令](/zh/docs/reference/cli) - 用户侧 Power 命令文档
- [API 参考](/zh/docs/reference/api) - Runtime HTTP API 文档
### 社区
- [Discord](https://discord.gg/downcity) - 实时聊天
- [Telegram 社区群组](https://t.me/+iozIHyXr-BJhNjE1) - 问答
- [GitHub Issues](https://github.com/genesiscosmos/downcity/issues) - Bug 报告
---
## 认可
感谢您的贡献!您的帮助让 Downcity 对每个人都更好。
贡献者在以下地方得到认可:
- [贡献者](https://github.com/genesiscosmos/downcity/graphs/contributors)
- 发布说明
- 年度亮点
---
## 下一步
准备贡献?
1. 查找 [good first issues](https://github.com/genesiscosmos/downcity/labels/good-first-issue)
2. 加入 [Discord 社区](https://discord.gg/downcity)
3. 开始编码!🚀
## City SDK
### City SDK
Source: https://downcity.ai/en/city-sdk-docs/
Downcity's City SDK is the way AI builders create, deploy, and call City. A Federation can serve multiple web apps, extensions, desktop tools, client demos, and internal tools without making each product rebuild the same AI backend.
City exposes a stable **product-facing service boundary** instead of a raw provider API. Inside City, capabilities are organized as `Service`, `Action`, and `AIService`.
- the product client holds `user_token` (which contains `bureau_id`)
- it calls `text()`, `stream()`, `image()`, and other services through `Embassy User`
- City keeps the model catalog, provider routing, hooks, usage, and env behind the boundary
The server-side runtime class is `Federation` (also called the Federation here); product clients use the `City` client to reach it. For the boundary between them, see [Federation and City](/en/city-sdk-docs/concepts/federation).
## Pick your reading path
Start Here
I want to run one full call chain
Deploy a Federation, expose one model, issue a token, and make a product client call `text()` or `stream()` successfully.
Mental Model
I want to understand the boundaries first
Separate the Federation, product clients, your business backend, AI gateways, and real providers before implementation details start leaking together.
Real Scenarios
I am connecting a real city now
Read the practical guides for pure-client products, multi-product reuse, auth, provider env, hooks, and business logic.
Packages
I want to read by package
Jump straight into `@downcity/agent`, client, and CLI docs; official service packages live in Federation Services Docs.
API
I only need the interfaces
Jump straight to City, Embassy User, Embassy Admin, HTTP API, and environment variables.
## One diagram for the full model
Many product clients
Web apps, extensions, apps, desktop tools, client demos, and internal tools.
Embassy User + user_token (which contains bureau_id)
→
Federation
Verifies the token, resolves the model catalog, and dispatches the request to AIService, services, or custom Service actions.
Hooks and usage
Quota, balance, billing, logging, and risk control can plug into the Federation while your own business rules stay in your system.
→
Upstream execution
OpenAI, Claude, Gemini, private models, or your own AI Gateway / proxy.
Product clients see stable Service actions and model IDs. Which provider or gateway City uses internally remains a server-side detail.
## What the City SDK owns
- runtime database and Service-owned tables
- provider keys and runtime env
- `user_token` verification and administrator-session management
- model metadata and runtime through `AIChannel.model()` + `AIService.use()`
- public model catalogs through `city.ai.catalog()`
- usage records and hook extension points
## What it does not own
- your user system
- orders, subscriptions, CRM, or content data
- product-specific pages, interaction, and business UX
- a public “unified provider API” for arbitrary third-party systems
More precisely:
> The City SDK owns the Federation and its Service-facing AI infrastructure.
> Your products still own their users, business logic, interface, and pricing model.
## Recommended order
1. First integration: start at [Quickstart](/en/city-sdk-docs/quickstart)
2. Want the full city model: read [Concepts](/en/city-sdk-docs/concepts)
3. Connecting a real business scenario: read [Guides](/en/city-sdk-docs/guides)
4. Want a package-by-package map: read [Packages](/en/city-sdk-docs/packages)
5. Need concrete interfaces: come back to [Reference](/en/city-sdk-docs/reference)
### Federation, Bureau, Embassy, and City
Source: https://downcity.ai/en/city-sdk-docs/concepts/federation/
These four concepts have independent responsibilities:
- `Federation` is the authority backend and trust root. It owns accounts, Bureau records,
Services, model catalogs, usage, env, and Token issuance.
- `Bureau` is a product or business partition inside Federation. A Bureau Token identifies a
trusted product backend.
- `Embassy` is the window through which users and administrators access Federation. It has only
`user` and `admin` identity domains.
- `City` is the application composition root from `@downcity/city`. It owns Workspaces and can hold an Embassy service client. It is not a Federation
client or a registered Federation identity.
```ts
import { Embassy, Federation } from "@downcity/federation";
import { City } from "@downcity/city";
const federation = new Federation({ database });
const embassy = new Embassy({ federation_url: "https://fed.example.com" });
const city = new City({ embassy, workspaces: [workspace] });
const agent = new Agent({ id: "assistant" });
city.agents.add(agent);
```
## Identity boundaries
User Token, Admin Session Token, and Bureau Token are not interchangeable:
- `embassy.user` holds or obtains a User Token.
- `embassy.admin` holds or obtains an Admin Session Token.
- `new Bureau({ bureau_token })` holds a long-lived Bureau machine credential.
- City does not become one of those identities. An Agent running inside City may use an Embassy
or another client as an ordinary dependency.
## CLI mapping
- `fed` / `downfed` deploys and manages Federation.
- `city` / `downcity` manages the local Agent host.
The two commands may share one distribution, but they own different runtimes and lifecycle state.
### Product Boundary Model
Source: https://downcity.ai/en/city-sdk-docs/concepts/product-model/
The core mental model of Downcity is not "one city, one backend." It is:
> one Federation serving many AI products and workflows.
The reason is simple. What gets rebuilt again and again is usually not your business backend, but the AI call layer:
- provider key storage
- model catalog
- token validation
- usage records
- hooks, quotas, billing, and logs
Once you ship a second or third AI product, these capabilities repeat everywhere.
## Many products, one Federation
Product A
Web tools, content products, workflow utilities.
bureau_id = product_a
Product B
Chrome extensions, desktop tools, mobile entry points.
bureau_id = product_b
Product C
Client demos, internal tools, vertical sites.
bureau_id = product_c
→
Federation
City model catalog, provider env, Service routes, token validation, usage, and hooks.
## What should stay in the Federation
- Model catalog and provider configuration
- `user_token` validation
- AI service calls such as `city.ai.stream()` and `city.ai.image_create()` / `city.ai.image_result()`
- Structured decision calls such as `city.ai.decision()`
- Usage records, logs, quotas, and business hooks
- Call logic reused across multiple products
## What should stay in the product or business system
- User registration, login, and account systems
- Orders, subscriptions, balances, and CRM
- Pages, interactions, workflows, and content data
- Each product's own brand, pricing, and go-to-market strategy
In other words, Downcity centralizes the **AI infrastructure** layer, not your whole business system.
## Why this is more stable than "one backend per project"
If every new product copies a separate AI backend, the same issues appear quickly:
- provider keys scattered across many places
- inconsistent token rules
- inconsistent usage and logging conventions
- every new provider, model, or quota strategy requires edits in many repos
Once the AI call layer is centralized into the Federation, a new product usually only needs two steps:
1. create a new `bureau_id`
2. connect `Embassy User` in the product client
## What `bureau_id` means in this model
`bureau_id` is not a model name, and it is not the full abstraction of your tenant system.
It is the runtime's stable primary key for the product boundary. It answers questions like:
- which product started this call
- whether this product is currently `active`
- which product dimension hooks and usage should record against
- whether a user's calls should be separated across different products
If you are building a multi-product portfolio, `bureau_id` is the most stable boundary.
## The role of model at the city layer
In the current implementation, a model is a runtime capability unit registered in Runtime, not something owned by a specific city.
At the product layer, a model is more like a visible capability:
- you can pass it explicitly into `city.ai.stream({ model, call })`
- every AIService call must pass an explicit model id or `CityModel`
This means the product sees stable model IDs, not upstream provider details.
## Model type and modalities
Every catalog entry carries a `model_type`: `language`, `decision`, `image`, `sound`, or `video`. Federation derives it from the capabilities the model actually implements, so it shares a source with `modalities`.
The two answer different questions. `model_type` says what the model is, and is used for display and grouping. `modalities` says what it can do, and is what you read to decide whether a capability is available. A conversation model carries `text` / `stream`; a decision model carries only `decision`, which is why only the former can be passed to an Agent.
### AI Architecture
Source: https://downcity.ai/en/city-sdk-docs/concepts/architecture/
```text
City client / Agent
|
v
CityModel (ModelClient)
|
v
Federation AIService
auth -> model lookup -> fallback -> reasoning -> metering
|
v
AIChannel.stream(AIChannelStreamInput)
|
v
OpenAI-compatible or private Provider Adapter
```
`CityModel` is the client-side executable model. It knows the public `CityModelDescriptor` and the Federation transport, but never knows upstream keys or vendor protocol details.
`AIService` is the server-side orchestrator. It owns route selection, fallback, reasoning validation, usage normalization, and billing.
`AIChannel` is the server-side upstream boundary. It owns connection configuration, upstream model selection, server-side `provider_options`, and delegates conversion into `ModelStreamEvent` to a Provider Adapter.
The OpenAI-compatible endpoint is an adapter, not another execution path:
```text
OpenAI JSON/SSE -> ModelCall -> AIService -> AIChannel.stream -> ModelStreamEvent -> OpenAI JSON/SSE
```
### Token Model
Source: https://downcity.ai/en/city-sdk-docs/concepts/token-model/
Downcity uses an administrator session token to manage Federation, and `user_token` to let end-user clients call services.
Trusted backend
Your backend logs in with an administrator ID and password, then holds a short-lived session token.
Create city / request user_token
→
Downcity
Validates the administrator session token, issues `user_token`, and stores provider keys internally.
→
End-user client
The frontend, extension, or app uses Embassy User with `user_token` and calls services.
No access to administrator credentials
## user_token
`user_token` is the call credential used by the end user or product. Embassy Admin can request it from Federation using `bureau_id + user_id`.
- `bureau_id`
- `user_id`
- `metadata`
- `ttl`
Product configuration supplies `bureau_id` when login starts. After login, service calls only carry
`user_token`; Federation reads `bureau_id` from the verified Token. The client never touches provider
keys or administrator session tokens.
User Tokens use one `downcity:user` audience. Federation and Bureau Servers validate the same audience;
a Bureau Server additionally compares the Token's `bureau_id` with its machine-bound Bureau ID.
`bureau_id` always remains the original product-provided value and is never composed into or normalized
as an audience.
## Administrator session token
Use the administrator ID and password configured by `fed deploy` to sign in through Embassy Admin. The response contains a time-limited administrator session token for creating Bureaus, managing env, and requesting Federation to issue `user_token`.
```ts
const embassy = new Embassy({
federation_url: "https://base.example.com",
admin_token: administrator_session_token,
});
const bureau = await embassy.admin.bureaus.create({
name: "Chrome Extension",
server_url: "https://bureau.example.com",
});
```
## Multi-city reuse
Many clients can belong to the same Bureau. When issuing a token, write `bureau_id` explicitly:
```ts
const user = await embassy.admin.service("accounts").action("tokens/issue").invoke({
bureau_id: bureau.bureau_id,
user_id: "user_123",
metadata: {
plan: "pro",
},
ttl: "7d",
});
console.log(user.user_token);
```
### Trust Boundary
Source: https://downcity.ai/en/city-sdk-docs/concepts/trust-boundary/
The Downcity security model depends on a clear trust boundary.
## Safe to keep in the client
- `Embassy User`
- `federation_url`
- `user_token`
- model IDs
- user input such as prompt, messages, size, and voice
## Must stay in a trusted environment
- provider API keys
- administrator ID, password, and session token
- Runtime env management permissions
- token issuance logic
- plans, balances, billing, and risk-control decisions
## City's boundary
City validates `user_token`, reads Runtime env, and calls the real model through service handlers. The client does not need to know the provider key, and it does not need to know how your internal billing works.
```plaintext
the client can know: which model to call
the client should not know: which provider key powers that model
```
This boundary allows pure-client products to connect directly to the Federation without exposing sensitive configuration.
### Usage and Billing
Source: https://downcity.ai/en/city-sdk-docs/concepts/usage-and-billing/
Downcity does not decide your business model for you. It gives you hooks so you can plug your own plan, balance, quota, logging, and billing systems into the AI call lifecycle.
## before hook
`before` is the right place for pre-call checks:
- whether the user is allowed to call
- whether the current plan allows this model
- whether today's quota is sufficient
- whether risk-control or rate-limiting should block the call
## after hook
`after` is the right place for post-call records:
- record provider usage
- write call logs
- deduct balance
- sync billing
- analyze cost by city
```ts
const ai = new AIService();
ai.hook
.before(async (ctx) => {
await quotaService.check(ctx.user?.user_id, ctx.variant?.id);
})
.after(async (ctx) => {
await usageService.record({
user_id: ctx.user?.user_id,
bureau_id: ctx.bureau?.bureau_id,
model: ctx.variant?.id,
output: ctx.output,
});
});
base.use(ai);
```
This lets many AI products share the same business logic instead of rebuilding it in every project.
### Try It Now
Source: https://downcity.ai/en/city-sdk-docs/quickstart/use-now/
## 1. Start City
```ts
import {
Federation,
AIService,
AIChannel,
type AIChannelStreamInput,
type AIChannelStreamResult,
} from "@downcity/federation";
import { Database } from "@downcity/database-sqlite";
const database = new Database({ filename: "./data.sqlite" });
const base = new Federation({ database });
class EchoChannel extends AIChannel {
constructor() {
super({ id: "echo" });
}
protected async stream(
input: AIChannelStreamInput,
): Promise {
const input_text = input.call.messages
.flatMap((message) => message.content)
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n");
return {
stream: new ReadableStream({
start(controller) {
controller.enqueue({ type: "model_start", request_id: crypto.randomUUID(), model_id: input.model.id });
controller.enqueue({ type: "text_start", content_id: "echo_text" });
controller.enqueue({ type: "text_delta", content_id: "echo_text", delta: `Echo: ${input_text}` });
controller.enqueue({ type: "text_finish", content_id: "echo_text" });
controller.enqueue({
type: "model_usage",
usage: { input_tokens: 0, output_tokens: 0, total_tokens: 0 },
});
controller.enqueue({ type: "model_finish", finish_reason: "stop" });
controller.close();
},
}),
};
}
}
const echo = new EchoChannel();
const ai = new AIService();
ai.use(echo.model({ id: "local-echo", upstream_model: "local-echo", name: "Local Echo" }));
base.use(ai);
await base.health();
serve({ fetch: (request) => base.fetch(request), port: 43127, hostname: "127.0.0.1" });
```
## 2. Create Bureau & Request Token
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: "http://127.0.0.1:43127",
admin_token: administrator_session_token,
});
const token = await embassy.admin.service("accounts").action("tokens/issue").invoke({
bureau_id: "demo",
user_id: "user_123",
ttl: "7d",
});
```
## 3. Client Call
```ts
const user_embassy = new Embassy({
federation_url: "http://127.0.0.1:43127",
user_token: token.user_token,
});
const catalog = await user_embassy.user.ai.catalog();
const model = catalog.require("local-echo");
// SDK pathway
const stream = await model.stream({
messages: [{ role: "user", content: [{ type: "text", text: "Hello" }] }],
});
for await (const event of stream) {
if (event.type === "text_delta") process.stdout.write(event.delta);
}
```
## Next Steps
- [AIChannel & Model Registration](/en/city-sdk-docs/service/ai/provider)
- [Calling AI Service](/en/city-sdk-docs/service/ai/calling)
- [Create City](/en/city-sdk-docs/quickstart/create-city)
### Create Federation
Source: https://downcity.ai/en/city-sdk-docs/quickstart/create-city/
The server-side runtime class is `Federation` (also called the Federation in these docs); product clients use the `City` client to reach it. See [Federation and City](/en/city-sdk-docs/concepts/federation) for the distinction.
The fastest local creation and startup path is:
```bash
fed create --path ./my-fed
cd my-fed
pnpm install
fed deploy
```
`fed create` and `fed deploy` default to `--path .`; another directory must be passed with `--path `, not a positional argument. See [CLI Quickstart](/en/city-sdk-docs/packages/cli/quickstart) for per-operation instance selection with `--id` / `--name`.
The default template uses Node.js and SQLite. `fed deploy` uses the fixed default port `12314` (override it with `deployment.port`; an occupied port prompts to stop its owner, defaulting to No, while non-interactive terminals fail), manages the service through macOS user-level launchd or Linux user-level systemd, and interactively asks you to set an administrator ID and password. The password must be at least 12 characters; only its PBKDF2 digest is stored in the database. `fed` then uses a time-limited administrator Session Token to inspect and manage the Federation from any directory. To replace lost credentials, run `fed deploy --admin-reset`; this revokes existing administrator sessions and asks for the new credentials. The template explicitly sets `auto_start = false` and `restart_on_failure = true` in `[deployment.process]`. Unexpected exits trigger recovery every 10 seconds, limited to 5 attempts within 60 seconds. `fed stop` disables automatic startup and keeps the service stopped across system restarts until an explicit deploy/restart. Automatic startup requires explicit opt-in: macOS starts after user login, and Linux requires an available user manager. The CLI does not enable linger.
Local Node failures before cutover preserve the existing instance and configuration and allow restart when no cutover recovery is pending. A failed or interrupted cutover blocks restart until an explicit deploy succeeds; later build/preflight failures preserve that guard. Candidate start/readiness failures stop the candidate and remove its startup association. Cleanup errors show `unknown` and require manual inspection. Code and data are not automatically rolled back. `fed status` reports registry, manager, health, and deployment history separately; the last successful release is not proof that it is running. See [CLI Quickstart](/en/city-sdk-docs/packages/cli/quickstart) for phase handling and configuration details. The rest of this page shows the SDK path for manually embedding the Federation runtime.
Install the packages:
```bash
pnpm add @downcity/federation @downcity/database-sqlite
```
The database is the only thing you need before boot. `fed deploy` asks for an administrator ID and password; the password is stored as a PBKDF2 digest and later logins receive a session token. `DOWNCITY_FEDERATION_TOKEN_SIGNING_KEY` and `BETTER_AUTH_SECRET` are generated automatically. Provider keys are written later through the Admin API or the `fed` admin workspace:
```bash
OPENAI_API_KEY="..."
OPENAI_BASE_URL="https://api.openai.com/v1"
```
Create Federation:
```ts
import { Federation } from "@downcity/federation";
import { Database } from "@downcity/database-sqlite";
const database = new Database({ filename: "./data.sqlite" });
const base = new Federation({ database });
```
The default database is stored at:
```plaintext
./data.sqlite
```
Use `@downcity/database-sqlite` locally. For production PostgreSQL, switch to `@downcity/database-postgresql`.
For Cloudflare Workers / D1, pass the D1 adapter:
```ts
import { Database } from "@downcity/database-d1";
const database = new Database({ binding: env.DB });
const base = new Federation({ database });
```
Federation initializes itself automatically on the first `health()`, `fetch()`, `table()`, or similar runtime call.
If your Federation needs its own business tables, declare them on a Service or service:
```ts
import { sqliteTable, text } from "drizzle-orm/sqlite-core";
import { Service } from "@downcity/federation";
const notes = sqliteTable("notes", {
id: text("id").primaryKey(),
title: text("title").notNull(),
status: text("status").notNull(),
});
const notesService = new Service({
id: "notes",
tables: { notes },
});
base.use(notesService);
const table = await base.table("notes.notes");
await table.insert({
id: "note_1",
title: "First note",
status: "draft",
});
```
Tables declared by services use the same database connection as Federation. Regular projects do not need manual table creation.
Start the HTTP service:
```ts
import { serve } from "@hono/node-server";
await base.health();
serve({ fetch: (request) => base.fetch(request), port: 3001, hostname: "127.0.0.1" });
```
This service is the shared Federation used by later cities. Management and business data are handled through your own database and city backend for now.
### Add a Model
Source: https://downcity.ai/en/city-sdk-docs/quickstart/add-model/
Create an `AIChannel`, implement its Downcity Model Protocol stream, then register an `AIModelSpec`:
```ts
import {
AIChannel,
AIService,
stream_openai_compatible_model,
type AIChannelStreamInput,
type AIChannelStreamResult,
} from "@downcity/federation";
class DeepSeekChannel extends AIChannel {
constructor() {
super({
id: "deepseek",
env: { DEEPSEEK_API_KEY: "DeepSeek API Key" },
base_url: "https://api.deepseek.com/v1",
});
}
protected async stream(
input: AIChannelStreamInput,
): Promise {
const api_key = input.env("DEEPSEEK_API_KEY");
if (!api_key) throw new Error("DEEPSEEK_API_KEY is required");
return stream_openai_compatible_model(input, {
api_key,
base_url: this.base_url ?? "https://api.deepseek.com/v1",
});
}
}
const channel = new DeepSeekChannel();
const ai = new AIService();
ai.use(channel.model({
id: "deepseek-v4-flash",
upstream_model: "deepseek-chat",
name: "DeepSeek V4 Flash",
context_window: 128_000,
}));
federation.use(ai);
```
This single `stream()` implementation powers `city.ai.stream()`, `CityModel`, and `/v1/ai/chat/completions`.
See [AIChannel and model registration](/en/city-sdk-docs/service/ai/provider) for reasoning, fallback, billing, and `provider_options`.
### Issue a User Token
Source: https://downcity.ai/en/city-sdk-docs/quickstart/issue-token/
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: "https://fed.example.com",
admin_token: administrator_session_token,
});
const issued = await embassy.admin.service("accounts")
.action("tokens/issue")
.invoke({
bureau_id: "product-web",
user_id: "user_123",
metadata: { plan: "pro" },
ttl: "7d",
});
```
Federation performs the issuance. Bureau verifies User Tokens but does not issue them.
### Connect Embassy
Source: https://downcity.ai/en/city-sdk-docs/quickstart/connect-client/
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: "https://fed.example.com",
user_token: "ub_xxx",
});
const catalog = await embassy.user.ai.catalog();
const model = catalog.get("gpt-5.4");
if (!model) throw new Error("model not found");
const result = await embassy.user.ai.text({
model,
prompt: "Write a welcome message",
});
```
Use `embassy.user.service(name)` for custom or official Services. Provider keys, model routing,
and usage accounting remain inside Federation.
### Pure-Client Products
Source: https://downcity.ai/en/city-sdk-docs/guides/pure-client-products/
“Pure-client product” does not mean “no backend at all.” It means you stop rebuilding the AI backend for every product.
Downcity lets a new product start from the frontend, extension, or app and connect to an already deployed Federation. You can validate the product UX first, then decide how much product-specific backend you really need.
## Good fits
- lightweight web tools
- Chrome extensions
- desktop shells
- mobile entries
- client demos
- internal tools
## Recommended boundary
The client owns:
- UI and interaction
- calling Embassy User
- using the product-configured `bureau_id` when login starts
- storing or refreshing `user_token`
The Federation owns:
- provider keys
- model directory
- `user_token` verification
- service routing
- usage records
- hooks and billing logic
## The most common minimum shape
```plaintext
City frontend
↓
Your login / token-issuing endpoint
↓
Federation
```
That product backend can stay very thin at first:
- user login
- requesting a User Token through Embassy Admin
- returning `user_token` to the client
Normal service requests do not submit `bureau_id` again; Federation reads it from the verified
`user_token`.
## Why this fits early products better
- you stop copying provider integrations for every AI idea
- the frontend can ship much earlier
- multiple products share one AI calling, logging, and quota layer
If the product gets more complex later, then add more business backend. Do not duplicate the whole AI infrastructure on day one.
### Many Products, One Federation
Source: https://downcity.ai/en/city-sdk-docs/guides/multi-product-city/
When many products share one runtime, the goal is not “save one server.” The goal is to separate **shared infrastructure** from **product-specific differences**.
What should be shared:
- provider env
- model directory
- service routing
- hooks, usage, and logs
- `user_token` verification
What should stay in each product:
- pages and interaction
- the user system
- plan, order, and balance rules
- product-specific brand, positioning, and pricing
## One diagram for the reuse boundary
Product A
For example, a web tool.
bureau_id = web
Product B
For example, a Chrome extension.
bureau_id = extension
Product C
For example, a client demo or internal tool.
bureau_id = demo
→
Federation
Reuses the model directory, provider env, service logic, usage records, and hooks.
## How to think about `bureau_id`
`bureau_id` is a product boundary, not a model boundary.
It is useful for:
- identifying which product sent the call
- deciding whether a product is still `active`
- telling hooks where usage should be recorded
- separating one user’s activity across different products
A common pattern is one stable `bureau_id` per product:
```ts
const issued = await admin.service("accounts").action("tokens/issue").invoke({
bureau_id: "demo",
user_id: "user_123",
metadata: {
plan: "starter",
channel: "extension",
},
});
```
## What belongs in token metadata
`bureau_id` says *which product this is*. Token metadata is better for *the user’s business state inside that product*.
Common fields:
- `plan`
- `organization_id`
- `channel`
- `feature_flag`
- `team_id`
That lets hooks differentiate behavior with `ctx.bureau` and `ctx.user.metadata` instead of cloning City for each city.
## Recommended layering
### City side
- keeps routes, UI, and business experience
- uses `Embassy User`
- only holds `user_token` (which contains `bureau_id`)
### Business backend
- owns login, orders, balance, subscriptions, and business data
- uses `Embassy Admin` in a trusted environment
- issues `user_token` after a successful login
### City
- owns the model directory
- owns provider calls
- owns usage and hooks
- owns the reusable AI service layer
## When to create a new city
Usually worth creating a new city when:
- it is a separate city or market
- it needs to be paused or activated independently
- it needs independent usage reporting or business strategy
- you need to separate web app, extension, client demo, and other city surfaces
Usually not worth creating a new city when:
- it is only another page in the same city
- it is only a feature flag inside the same city
- it is just another conversation/session for one user
Those are better kept inside your own business system or token metadata.
### Cloudflare Workers
Source: https://downcity.ai/en/city-sdk-docs/guides/cloudflare-workers/
If you want to deploy Downcity on Cloudflare Workers, the recommended path is not a separate edge package. Wire `@downcity/agent` directly into the Workers runtime.
The public repository includes `templates/edgefed` as a developer starter. Downcity's private official Worker implementation lives outside the public repository.
## What this path actually solves
The main difference from Node.js is not the HTTP entry. It is the runtime resource model:
- the database usually comes from a binding such as `env.DB`
- environment values are not just a local `.env` file
- the request origin may need to be synchronized into services on every request
- Worker isolates are reused, so runtime cache behavior must be managed explicitly
That is why this is better explained as a guide than as an empty npm package.
## The minimum shape
Federation needs a D1 Database Adapter:
```ts
import { Federation } from "@downcity/federation";
import { Database } from "@downcity/database-d1";
export interface Env {
DB: D1Database;
}
export default {
async fetch(request: Request, env: Env) {
const database = new Database({ binding: env.DB });
const base = new Federation({ database });
await base.health();
return base.fetch(request);
},
};
```
The adapter owns the D1 runtime differences:
- only `@downcity/database-d1` receives the D1 binding
- the adapter combines Drizzle with snapshot conflict retries and atomic commits
- City and services never receive the raw D1 binding
- the current request origin can be synchronized before calls that need OAuth callback URLs
## Use `templates/edgefed` as a starter
The starter in `templates/edgefed/src/index.ts` keeps only the boundaries required to connect Federation to a Worker:
- wrap `env.DB` with `@downcity/database-d1`
- reuse the Federation instance within a Worker isolate
- delegate the HTTP request to Federation
Product services, models, and providers should be composed by the product and do not belong in the Edge runtime template.
## Boundary with the Node path
Worker and Node use the same mental model: create the appropriate Database Adapter, then pass it to `new Federation({ database })`.
- Node.js local projects use `@downcity/database-sqlite`
- Node.js production deployments can use `@downcity/database-postgresql`
- Workers / D1 use `@downcity/database-d1`
## Next
- If you still need the City mental model first, read [City](/en/city-sdk-docs/packages/federation/federation)
- If you need to manage provider keys, continue with [Provider environment](/en/city-sdk-docs/guides/provider-env)
- For the minimal Worker integration, open `templates/edgefed/src/index.ts`
### Auth and `user_token`
Source: https://downcity.ai/en/city-sdk-docs/guides/auth-and-user-token/
Downcity does not host your user system. It only requires a verifiable `user_token` on product-side requests.
## If you already have login
After a user logs in, use Embassy Admin to request a Downcity token from Federation:
```ts
const user = await embassy.admin.service("accounts").action("tokens/issue").invoke({
bureau_id: "demo",
user_id: session.user.id,
metadata: {
plan: session.user.plan,
},
ttl: "7d",
});
```
Then give the product side two values:
- `bureau_id`
- `user_token`
## If you do not have a heavy backend yet
For new pure-client products, keep token issuance near one Federation instead of building a separate service per product.
## What the token should not do
- Do not put provider keys into the token.
- Do not put private billing rules into the token.
- Do not let the client hold administrator IDs, passwords, or session tokens.
The token only needs to express who the user is and which business metadata should travel with the request.
### AIChannel Environment Variables
Source: https://downcity.ai/en/city-sdk-docs/guides/provider-env/
Declare the key on the Channel:
```ts
class DeepSeekChannel extends AIChannel {
constructor() {
super({
id: "deepseek",
env: { DEEPSEEK_API_KEY: "DeepSeek API Key" },
base_url: "https://api.deepseek.com/v1",
});
}
protected async stream(input: AIChannelStreamInput) {
const api_key = input.env("DEEPSEEK_API_KEY");
if (!api_key) throw new Error("DEEPSEEK_API_KEY is required");
return stream_openai_compatible_model(input, {
api_key,
base_url: this.base_url ?? "https://api.deepseek.com/v1",
});
}
}
```
`env` declares the variables shown in the model catalog's admin view. Add multiple entries when a Channel needs more than one value.
Values are stored in Federation's env table and read at execution time with `input.env(key)`. They never enter `CityModelDescriptor` or the client runtime.
### Model Adapters
Source: https://downcity.ai/en/city-sdk-docs/guides/model-adapters/
Downcity has one core model protocol. OpenAI Chat Completions is adapted only at the HTTP boundary:
```text
City SDK / CityModel ------\
-> ModelCall -> AIService -> AIChannel.stream()
OpenAI Chat Completions ---/ -> ModelStreamEvent
```
Use `stream_openai_compatible_model()` for an OpenAI-compatible upstream. For a private HTTP protocol, provide an Adapter that maps `ModelCall` into the vendor request and returns `AIChannelStreamResult`. AIService does not know the vendor request format.
OpenAI Chat Completions is an HTTP Adapter around the same Model Protocol path. There is no raw passthrough and no second model execution path, so tools, fallback, reasoning, metering, and billing behave consistently across clients.
Keep upstream-specific behavior in the Channel:
- credentials and base URL;
- upstream model factory and protocol selection;
- model-specific `provider_options`;
- usage interpretation and billing;
- conversion from private streams to `ModelStreamEvent`.
Keep Federation behavior in AIService:
- model registry and public catalog;
- authentication and availability;
- media fallback and reasoning validation;
- metering, balance checks, and charge settlement.
### Hooks and Billing Logic
Source: https://downcity.ai/en/city-sdk-docs/guides/hooks-and-billing/
Downcity hooks have three layers: Action -> Service -> Global. Execution order runs from outer to inner layers:
```txt
global.before
-> service.before
-> action.before
-> action.run() <- core logic
-> action.after <- billing
-> service.after
-> global.after
```
## Action-level hooks
Each Action has its own hooks, which makes them a good fit for product-specific logic:
```ts
const zh2en = svc.action("zh2en", async (ctx) => {
return await translate(ctx.input.text, "en");
});
// Check balance before the call
zh2en.before(async (ctx) => {
const bal = await balance.get(ctx.user!.user_id);
if (bal <= 0) throw new Error("Insufficient balance");
});
// Deduct balance after the call (ctx.output is available)
zh2en.after(async (ctx) => {
await deductBalance(ctx.user!.user_id, 10);
await logUsage(ctx);
});
```
## Service-level hooks
All Actions under the same Service share them:
```ts
svc.hook.before(async (ctx) => {
console.log(`${ctx.user?.id} -> ${ctx.service?.id}.${ctx.action?.id}`);
});
svc.hook.after(async (ctx) => {
// aggregate metrics, unified logs
});
```
## Comparison
| | Action hook | Service hook |
|---|---|---|
| Granularity | Single action | All actions in the service |
| Use cases | Balance checks, billing, per-action logs | Shared validation, aggregate metrics |
| Registration | `action.before(fn)` | `svc.hook.before(fn)` |
## Key fields inside ctx
```ts
interface Context {
input: Record // request payload
output?: unknown // Action result, available in after
user?: { user_id, metadata } // current user
bureau?: { bureau_id, status } // verified Bureau identity
service?: { id, name } // current Service
action?: { id } // current Action
}
```
### Account Login
Source: https://downcity.ai/en/city-sdk-docs/packages/federation/client/auth-flows/
Account operations live under `embassy.user.account`.
```ts
const providers = await embassy.user.account.providers();
const login = await embassy.user.account.login({
provider: "email",
client_type: "cli",
bureau_id: "product-web",
input: {
email: "user@example.com",
password: "password",
},
});
```
Email login requires completed email verification. For multi-step providers, use `login_start()` and `continue()`; the same account accessor retains the initiating proof. `status()` only queries status. After completion, `exchange()` obtains and stores the User Token, retaining a stable exchange ID across transport retries. `login()` handles the exchange automatically.
GitHub, Google, and WeChat OAuth return automatically to the initiating product after provider authentication. Every OAuth start supplies `redirect_uri`, random `state`, `code_challenge`, and `code_challenge_method: "S256"`. The product validates callback state, then exchanges `authorization_code`, `code_verifier`, and its private initiating proof. `status()` never delivers authorization codes or tokens. Never put the login secret or verifier in URLs or logs.
CLI and Desktop use a host-managed loopback receiver. Import `create_loopback_login_callback` from `@downcity/federation/node`; this Node-only entry point listens on `127.0.0.1` at a random unprivileged port and validates the random callback path, Host, and state. Pass its parameters to `login_start()` with `client_type: "cli"` or `"desktop"`, open the returned URL in the local system browser, and call `exchange({ authorization_code: callback.authorization_code, code_verifier: callback.code_verifier })` after receiving the callback. Release the listener on cancellation, timeout, or window close. Keep proofs in the host process. The CLI requires a local browser; remote or headless OAuth sign-in is unsupported.
For host-managed `login()` orchestration, `on_authorize: async (url) => ({ authorization_code, code_verifier })` opens the browser, waits for a validated callback, and returns the exchange proof. Cross-page websites use `login_start()` and `exchange()` in their BFF instead.
Website OAuth uses `client_type: "web"`. Its `redirect_uri` must exactly equal the registered Bureau `server.server_url` with `/api/auth/callback` appended. Register separate Bureaus for production and local development URLs; localhost HTTP is permitted for development. The BFF starts login through a same-origin POST, stores state, verifier, and the initiating proof in a short-lived host-only HttpOnly cookie, validates the returning state and browser transaction, exchanges the authorization code, and creates the website session.
Use `exchange({ exchange_id })` to specify a securely retained exchange ID and reuse it on transport retries.
`token()` reads the current User Token. `await embassy.user.account.logout()` revokes that token before clearing local credentials; failure retains it for retry. Bureau validates new protected requests online with Federation and rejects access if validation is unavailable. Existing streams are not forcibly interrupted.
After login, use the same `embassy.user` object for `current()`, AI, payment, and Services.
### User and Admin Services
Source: https://downcity.ai/en/city-sdk-docs/packages/federation/client/service-calls/
User and admin calls share the same Service protocol but use separate identity domains.
```ts
const user_services = await embassy.user.list_services();
const profile = await embassy.user.current();
const result = await embassy.user.service("rewrite")
.action("formal")
.invoke({ text: "hello" });
const admin_services = await embassy.admin.list_services();
const env = await embassy.admin.env.list();
```
Use `embassy.user.ai` for the Federation model catalog and AI execution, and
`embassy.user.payment` for payment methods. Admin-only management stays under
`embassy.admin`; do not pass administrator credentials through the user domain.
### Federation
Source: https://downcity.ai/en/city-sdk-docs/packages/federation/federation/
`@downcity/federation`'s `Federation` is the long-running server container of Downcity. It is where a Database Adapter, services, auth, and the shared `/v1/*` route space come together. Product-side access uses the `City` client; see [Federation and City](/en/city-sdk-docs/concepts/federation) for the distinction.
## What this concept means
A simple way to think about Federation is:
> one reusable AI infrastructure runtime process that many products can keep calling over time.
That process owns:
- the Database Adapter
- the service registry
- service mounting
- the HTTP route surface
- city, token, and env infrastructure
## When this page matters
- you are about to run a real Federation for the first time
- you want to understand why `Federation` only needs a Database Adapter
- you want clarity on `fetch()`, and `serve()`
- you want to mount Federation into Node, Workers, or another HTTP host
## Minimal runnable example
```ts
import { AIService, Federation } from "@downcity/federation";
import { Database } from "@downcity/database-sqlite";
import { serve } from "@hono/node-server";
const database = new Database({ filename: "./.base/downcity.sqlite" });
const base = new Federation({ database });
const ai = new AIService();
ai.use({
id: "local-echo",
name: "Local Echo",
actions: {
text: async (ctx) => ({
id: crypto.randomUUID(),
role: "assistant",
parts: [
{
type: "text",
text: String(ctx.input.prompt ?? ""),
state: "done",
},
],
}),
},
});
base.use(ai);
await base.health();
serve({
fetch: (request) => base.fetch(request),
port: 43127,
hostname: "127.0.0.1",
});
```
The important ideas in that example are:
1. `database` decides which Database Adapter Federation uses.
2. `base.use(...)` decides which capabilities Federation exposes.
3. `base.fetch()` decides how Federation enters your HTTP layer.
## HTTP requests and errors
Every request entering the `Federation.fetch()` HTTP boundary receives a server-generated `req_` before middleware runs; caller-supplied IDs are ignored. Boundary responses within the ordinary HTTP protocol overwrite `x-request-id`, including middleware short circuits, 413, 408, 504, success, business errors, native Responses, streams, and route 404s. The Router, HTTP Action `Context.request_id` and `Context.locals.request_id`, and AI relay share the same ID. Responses handled by the host outside this boundary are outside this scope; HTTP 101 upgrades are neither rewrapped nor managed, and their `x-request-id` response header is not guaranteed.
POST Actions default to `body: "json"`: empty or whitespace-only input becomes `{}`, and non-empty input must be a JSON object. GET uses query parameters. Webhook Actions may explicitly use `body: "raw"`; native `handler: { request }` route bodies also undergo one bounded read at the HTTP boundary before the Request is rebuilt from the original bytes without Action JSON parsing. OAuth forms and redirects retain their native semantics. See [Service and Action](/en/city-sdk-docs/packages/federation/service-and-action#action-body-modes).
Framework-caught errors return `error: { code, message, type, request_id }`. Explicit 4xx `httpError` messages are preserved. An explicit integer `statusCode` in 400–599 preserves a `code` matching `^[A-Za-z][A-Za-z0-9_]{0,63}$`, including `503 async_dispatch_unavailable`; missing or invalid status always becomes `500 INTERNAL_ERROR`. All 5xx messages are generic: 503 uses `Service temporarily unavailable`, 504 uses `Request timed out`, and other 5xx statuses use `Internal server error`.
Directly returned business or native error Responses keep their own bodies; `x-request-id` is still overwritten without consuming the body or buffering SSE. After a stream starts, boundary timeout or cancellation aborts downstream work, cancels the reader, and ends the stream without changing the HTTP status, returning JSON, or synthesizing generic SSE error frames. An `onError` hook failure does not replace the original error.
Framework 5xx structured logs contain only `event`, `request_id`, `status`, and `code`, excluding bodies, tokens, the original Error, and stacks. This does not provide complete access logging or retain original stacks. See [HTTP API](/en/city-sdk-docs/reference/http-api#framework-errors) for status classifications and default codes.
## HTTP policy configuration
`FederationOptions.http` configures the HTTP boundary, enabled by default before middleware and the Router. It counts actual `Uint8Array.byteLength`; missing or falsely small `Content-Length` cannot bypass the body limit. `ordinary` defaults to 1 MiB / 15 seconds to read / 30 seconds to execute. `webhook` matches only `/v1/payment/webhook` and defaults to 2 MiB / 15 seconds / 30 seconds. `model_stream` matches `/v1/ai/stream`. `media` matches `/v1/chat/completions`, `/v1/ai/chat/completions`, and `image/create`, `asr`, `tts`, `embedding`, `rerank`, `video`, `audio`, `decision` under `/v1/ai/`. Both categories default to 40 MiB / 60 seconds / 180 seconds. Lightweight `/v1/ai/image/result` uses `ordinary`.
Each category accepts partial `max_body_bytes`, `body_timeout_ms`, and `execution_timeout_ms` values; omitted fields retain that category's defaults. `routes: [{ path, max_body_bytes?, body_timeout_ms?, execution_timeout_ms? }]` overrides a complete pathname with exact matching and takes priority over category settings. Omitted route limits inherit the path's category. Prefixes, wildcards, query strings, fragments, and duplicate paths are rejected. Limits must be positive safe integers, with at most 256 MiB for body size and 2,147,483,647 for milliseconds. Unknown fields or invalid values fail at construction.
The body deadline covers the entire read and does not reset on new chunks. The execution deadline starts after the request body has been read and covers middleware and business handling. For non-SSE responses, the timer stays active until the response body finishes reading or is cancelled. Expiry before headers returns `504 REQUEST_TIMEOUT`; after headers have been sent, it only ends the stream without changing the status. Bodyless OPTIONS requests also use the ordinary execution deadline. Model and media endpoints wait up to 180 seconds for response headers by default. On receiving an SSE `Response`, the timer switches to `stream_lifetime_ms`, defaulting to `900_000` (15 minutes), measured from the end of request body reading and including the header wait. It must be a positive safe integer no greater than 2,147,483,647. The boundary does not buffer SSE. The model total clock starts at provider execution, independently of the HTTP SSE clock measured from the end of body reading; whichever expires first applies. Synchronous JSON remains subject to the default 180-second HTTP execution deadline.
Invalid lengths return `400 INVALID_CONTENT_LENGTH`. `Content-Encoding` other than absent or `identity` returns `415 UNSUPPORTED_CONTENT_ENCODING`. Body timeout returns `408 REQUEST_BODY_TIMEOUT`, oversized bodies return `413 BODY_TOO_LARGE`, and client cancellation corresponds to `499 REQUEST_CANCELLED`; disconnected clients are not guaranteed to receive a response. See [HTTP API](/en/city-sdk-docs/reference/http-api#http-boundary-and-default-limits) for limits and statuses.
Handlers can read `ServiceRouteContext.abort_signal` and Action `Context.abort_signal`; native routes can use `request.signal`. Adapters should combine the request signal with their own deadlines; shorter upstream deadlines still apply. Cancellation is cooperative: database operations may continue, transactions are not automatically rolled back, and no automatic retry is triggered. Queued image tasks run independently and do not inherit cancellation from foreground creation or result queries.
Edge / local-node link the SDK through workspace dependencies, so development builds use this default policy. Production deployment requires building the SDK and service artifacts containing the feature; running instances do not update automatically.
## Model execution policy
`AIServiceOptions.model_stream?: Partial` configures language model deadlines. Omitted fields use `first_output_timeout_ms: 120_000`, `idle_timeout_ms: 120_000`, and `total_timeout_ms: 900_000`. Native `/v1/ai/stream`, OpenAI-compatible SSE / JSON, and every Relay language model execution share `execute_model_stream`. Clients cannot raise the policy limits in a request.
The first-output budget accumulates provider open and actual read waits before useful output. Idle accumulates actual read waits between useful outputs and resets on useful output. Backpressure consumes neither budget; the total wall clock keeps running. `model_start`, `text_start`, `reasoning_start`, empty deltas, and usage do not renew the budget. Non-empty text / reasoning deltas, tool call start, non-empty input deltas, and tool call finish count as useful output. Values must be safe integers from 1 through 2,147,483,647; unknown fields or invalid values fail at construction. See [Calling models](/en/city-sdk-docs/service/ai/calling#model-execution-deadlines) for a configuration example.
Shorter provider, HTTP, and model deadlines apply together; whichever expires first aborts the same foreground execution without transparent retries. Timeout before provider open returns throws 504, such as `MODEL_FIRST_OUTPUT_TIMEOUT` or `MODEL_EXECUTION_TIMEOUT`. The Router preserves valid domain codes with the safe message `Request timed out`. An already-started native stream emits `model_error` with `provider_timeout`, `status_code: 504`, and `retryable: false`, describing first-output timeout, stalled output, or total execution timeout. If no provider `model_start` was received, a framework `model_start` may precede the error solely for the failure terminal protocol, without fabricating usage. OpenAI SSE sends an error frame without a success `[DONE]` on failure; JSON aggregation returns 504 on timeout. An already-started SSE response keeps its HTTP status.
Trustworthy usage facts are retained; missing usage does not lead to estimated tokens or costs. Existing `bill` callbacks use actual facts, and business charging rules do not promise zero charges in every case without usage. `completion.outcome` distinguishes `succeeded`, `failed`, and `cancelled`. A cancel after the terminal event does not relabel the result as cancellation or timeout, or duplicate settlement or charges. Completion or cancellation releases timers, listeners, and readers without waiting for an upstream cancel that could hang indefinitely. Underlying SQL side effects are not guaranteed to roll back.
## Production startup and database preparation
Local development defaults to `database_initialization: "automatic"`, which prepares tables, indexes and system data during initialization. Production hosts can use `"prepared"` to move that work out of the request startup path.
Before publishing, create a fresh Federation with the complete Service registration and call `await federation.prepare_database()`. This prepares the database, runs Service preparation and validates initialization before writing the preparation version marker. Abort the release if it fails. Request instances use the same Service configuration with `database_initialization: "prepared"`; startup loads configuration and signing keys and rejects an unprepared database.
Call `prepare_database()` before `health()` or request handling on that instance. Never expose it as a public HTTP endpoint. The preparation marker does not replace application migration history or coordinated schema releases.
For a full migration, call `prepare_schema()` on the empty target first. It creates structures without generating Federation identities, configuration or signing keys, and does not run Service data repairs. Import and verify existing data before `prepare_database()` establishes runtime readiness using the original identities and keys.
Use `on_startup_timing: ({ phase, duration_ms, ok }) => console.info({ phase, duration_ms, ok })` to observe startup stages without logging credentials or business data.
Schedule `await federation.maintenance()` to clean expired revocations and Service data. Credential expiry is still checked during requests. Custom Services extend `on_prepare_database()` and `on_maintenance()`; `on_init()` handles instance initialization only. Hosts should rebuild failed containers with backoff rather than repeat route installation on partially initialized objects.
## Scenario 1: Federation is the main service
If you want Federation itself to be the main HTTP entry, `serve()` is the clearest mental model:
```ts
import { serve } from "@hono/node-server";
await base.health();
serve({ fetch: (request) => base.fetch(request), port: 3001, hostname: "127.0.0.1" });
```
## Scenario 2: Federation is mounted into your existing server
If you already have a server framework, handing requests into Federation is often the cleaner pattern:
```ts
export default {
async fetch(request: Request) {
return base.fetch(request);
},
};
```
### Concurrent Cloudflare Worker cold starts
A single Worker deployment can start multiple isolates at the same time. Each isolate has independent memory while sharing the same D1 database, so a module-level Promise only prevents duplicate initialization inside one isolate and is not a global lock.
Federation atomically initializes its system env and Ed25519 user token signing key in the shared database, with a unique constraint that allows only one active signing key. If an older SDK left multiple active keys behind, startup keeps the earliest key and changes the others to retired. Retired keys remain in JWKS so existing tokens can still be verified.
## Scenario 3: Local HTTP
When Federation only needs to be called by trusted processes on the same machine, expose its standard `fetch` handler through your local HTTP server:
```ts
import { Federation } from "@downcity/federation";
import { serve } from "@hono/node-server";
const base = new Federation({ database });
serve({
fetch: (request) => base.fetch(request),
hostname: "127.0.0.1",
port: 15315,
});
const federation_url = "http://127.0.0.1:15315";
```
Then point Embassy at that HTTP URL:
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url,
admin_token: administrator_session_token,
});
await embassy.admin.list_services();
```
Local HTTP uses the same identity model as remote HTTP: Embassy Admin uses an administrator session token, while authenticated user actions require a normal `user_token`.
If `AccountsService` is configured with `local_login: true`, `/v1/accounts/providers` only returns the local login method. Call `POST accounts.login/start` with `provider: "local"`, an explicit `client_type`, and `bureau_id` to receive `login_id` and `login_secret`. Keep the secret in the initiating client. `POST accounts.login/result` accepts both fields and returns status only. Use `POST accounts.login/exchange` with both fields and a stable random `exchange_id` to obtain `user_token`, then recreate or update Embassy User with that token (which contains `bureau_id`). Reuse the exchange ID on transport retries.
### The official local-node boundary
The official `private/services/local-node` enables `local_login` for passwordless user login on a trusted local machine. It accepts only `127.0.0.1`, `::1`, or `localhost` as its listen address. `PUBLIC_URL` must be a canonical HTTP(S) loopback origin with the same port, defaulting to `http://localhost:3000` (with the port determined by `PORT`). Wildcard listen addresses, public addresses, and arbitrary DNS names pointing to the local service are rejected.
Before dispatching login, exchange, native routes, or admin requests, the host checks browser origins. Requests from the target's own origin, `PUBLIC_URL`, or an exact origin in `DOWNCITY_LOCAL_ALLOWED_ORIGINS` may proceed; other origins receive 403. Additional origins are comma-separated, for example `http://localhost:5173,https://client.example.com`, and default to empty. Each must be a canonical HTTP(S) origin without a trailing slash, path, query, fragment, credentials, or explicit default port. `*`, `null`, and inputs requiring URL normalization are rejected. CORS responses for allowed origins reflect only that exact origin.
An allowed page may obtain ordinary user access through the passwordless local login, so explicitly trust each entry. The allowlist grants no identity, and each login flow still enforces its own origin and credential rules. Administrator APIs require a real administrator Session; user and Bureau credentials cannot become administrator credentials. Normal CLI requests without `Origin` remain supported. Browser requests with cross-site Fetch Metadata must provide an allowed Origin. This boundary does not protect against malicious local processes forging requests.
HTTP requests without credentials remain anonymous. Startup provider env and Bureau initialization use in-process `trusted_identity`, which does not attach administrator identity to external HTTP requests. See [Environment Variables](/en/city-sdk-docs/reference/env-vars#official-local-node-configuration) for configuration syntax.
## Why Federation only takes a Database Adapter
`@downcity/federation` owns the logic that should stay stable across runtimes:
- service lifecycle
- action routes
- token auth
- city / env / store infrastructure
The host runtime only needs to create the appropriate adapter:
- Node.js can use `@downcity/database-sqlite` or `@downcity/database-postgresql`
- Cloudflare Workers can use `@downcity/database-d1`
- Federation writes required runtime env into the built-in `env` table on boot
## Default Storage
When a Federation needs to move runtime files into first-party storage, register a default storage backend:
```ts
import { Federation, R2Storage } from "@downcity/federation";
const base = new Federation({ database });
base.storage(R2Storage({
bucket: env.DOWNCITY_STORAGE,
public_url_prefix: env.DOWNCITY_STORAGE_PUBLIC_URL_PREFIX,
}));
```
Services can then access it through `ctx.storage`. Built-in AI image jobs use this storage after `image_fetch` succeeds to move remote file part URLs into your own bucket. If storage fails, the original upstream URL is kept and the image job still succeeds.
## Common API surface
- `new Federation({ database })`
- `base.use(...)`
- `base.storage(...)`
- `base.fetch(request)`
- `base.health()`
- `base.table(name)`
## Common misunderstandings
### Federation is the runtime, not the whole SDK
Federation is the long-running server runtime. Product-side calling uses the `City` client; see [Client SDK](/en/city-sdk-docs/packages/federation/client).
### Federation is not only an HTTP proxy
It also owns built-in tables, token and env infrastructure, service data layers, and hook lifecycle.
### Federation is not one provider
Providers, models, services, and custom services are capabilities mounted into Federation, not the Federation itself.
## Read next
- For what actually gets mounted into Federation, read [Service and Action](/en/city-sdk-docs/packages/federation/service-and-action)
- For hooks and extension points, read [Hooks and Service Mounting](/en/city-sdk-docs/packages/federation/hooks-and-service)
- For persistence and tables, read [Store and Table](/en/city-sdk-docs/packages/federation/store-and-table)
- For lower-level method details, read [Federation API](/en/city-sdk-docs/reference/federation)
### Database Adapters
Source: https://downcity.ai/en/city-sdk-docs/packages/federation/database-adapters/
Federation no longer accepts a raw Drizzle database. It accepts a `Database` instance derived from `@downcity/federation`; the adapter owns the driver, transactions, DDL, and connection lifecycle.
## SQLite
```bash
pnpm add @downcity/federation @downcity/database-sqlite
```
```ts
import { Federation } from "@downcity/federation";
import { Database } from "@downcity/database-sqlite";
const database = new Database({ filename: "./federation.sqlite" });
const federation = new Federation({ database });
```
Use `filename: ":memory:"` in tests. File databases enable WAL by default.
## Cloudflare D1
```ts
import { Federation } from "@downcity/federation";
import { Database } from "@downcity/database-d1";
const database = new Database({ binding: env.DB });
const federation = new Federation({ database });
```
The D1 adapter provides the same `context.transaction()` contract through snapshots, conflict retries, and atomic `batch()` commits. Reads inside a transaction observe its buffered writes.
## PostgreSQL
```ts
import { Federation } from "@downcity/federation";
import { Database } from "@downcity/database-postgresql";
const database = new Database({ url: process.env.DATABASE_URL! });
const federation = new Federation({ database });
```
The PostgreSQL adapter uses postgres-js and native Drizzle transactions.
## Service boundary and lifecycle
Services use `context.table()` and `context.transaction()`. Selected official integrations can use the restricted `context.database.query()` / `atomic()` surface, but never receive the underlying driver client.
`Federation` owns the supplied database. Call `await federation.dispose()` during shutdown to release adapter resources. Disposal is idempotent, and operations after disposal fail.
### Service and Action
Source: https://downcity.ai/en/city-sdk-docs/packages/federation/service-and-action/
`Service` and `Action` are the main business organization units inside `@downcity/federation`.
Keep one sentence in mind:
> a Service is a long-lived group of capabilities, and an Action is the concrete callable entry.
## What this concept means
Every Action is simultaneously:
- a business entry point
- an HTTP route node
- a hook target
- an auth boundary
## When you should write a custom service
- you want city business actions, not raw model inference only
- you want one business entry shared across frontend, app, and internal tools
- you want that capability to participate in hooks, auth, usage, and service governance
Typical examples:
- rewriting content
- generating reports
- running workflows
- processing business data
## When AIService is the better starting point
If you mainly want to expose `text`, `stream`, `image`, or `video`, then `AIService` is usually the cleaner first mental model.
## Minimal custom service example
```ts
import { Federation, Service } from "@downcity/federation";
const base = new Federation({ database });
const translate = new Service({
id: "translate",
name: "Translate",
});
translate.action("zh2en", async (ctx) => {
return {
text: await runTranslate(String(ctx.input.text ?? ""), "en"),
};
});
translate.action("list", async () => {
return {
items: ["zh2en"],
};
}, {
method: "GET",
});
base.use(translate);
```
## How routes are exposed
Those Actions automatically enter the shared route space:
```txt
POST /v1/translate/zh2en
GET /v1/translate/list
```
That is why the product side can stay unified:
```ts
const result = await client
.service("translate")
.action("zh2en")
.invoke<{ text: string }>({
text: "Hello Downcity",
});
const list = await city.service("translate").get("list");
```
## Common scenarios
### Scenario 1: city business action
```ts
const writer = new Service({ id: "writer", name: "Writer" });
writer.action("draft", async (ctx) => {
return {
title: "Draft",
topic: ctx.input.topic,
};
});
```
### Scenario 2: admin-only action
```ts
writer.action("remove", async (ctx) => {
await removeDraft(String(ctx.input.id));
return { ok: true };
}, {
auth: ["admin"],
});
```
### Scenario 3: guest entry
```ts
writer.action("webhook", async (ctx) => {
await verify_webhook(ctx.raw_body ?? "");
return { accepted: true };
}, {
auth: [],
body: "raw",
});
```
## Action body modes
`service.action(name, handler, options?)` accepts optional `body: "json" | "raw"`. POST Actions default to `"json"`: empty or whitespace-only input becomes `{}`, and every non-empty body must be a JSON object. Invalid JSON returns `400 INVALID_JSON`; arrays, `null`, and other JSON primitives return `400 INVALID_INPUT`. A body read failure returns `400 INVALID_BODY`. GET Actions read query parameters.
Use `body: "raw"` for webhook signatures or other text protocols. A regular Action reads the original text from `ctx.raw_body`; its `ctx.input` starts as `{}`. Installable Service `ctx.route({ method, path, body?, handler })` supports the same optional body mode for Action handlers. Inside that route handler, `ctx.text()` returns the original text and `ctx.json()` still strictly parses a JSON object on demand, accepting empty or whitespace-only text as `{}`.
Installable native routes use `handler: { request }`. Their bodies also undergo one bounded read at the HTTP boundary before the Request is rebuilt from the original bytes without Action JSON parsing. `body` is only an Action option. Native OAuth form submissions, callbacks, and redirects use their own protocols. Body size, read deadlines, and encoding validation also apply to native routes; see [HTTP API](/en/city-sdk-docs/reference/http-api#http-boundary-and-default-limits).
## Request context and failures
For HTTP Actions, `ctx.request_id` and `ctx.locals.request_id` contain the server-generated `req_`, assigned at the HTTP boundary before middleware runs. `x-request-id`, the Router, and AI relay share that ID; caller-supplied IDs are ignored. Ordinary HTTP middleware short circuits and 413, 408, 504 responses also carry it. HTTP 101 upgrades are neither rewrapped nor managed, and their `x-request-id` response header is not guaranteed.
Action `Context.abort_signal` and Installable `ServiceRouteContext.abort_signal` are readable; native handlers can use `request.signal`. Adapters should combine request cancellation with their own deadlines; shorter upstream deadlines still apply. Client cancellation corresponds to `499 REQUEST_CANCELLED`, but disconnected clients are not guaranteed to receive a response. Cancellation is cooperative: database operations may continue, transactions are not automatically rolled back, and no automatic retry is triggered. Queued image tasks do not inherit foreground request cancellation.
Framework-caught errors use `error: { code, message, type, request_id }`. Explicit 4xx `httpError` messages are preserved; all 5xx messages are generic. An explicit integer `statusCode` from 400 through 599 preserves a `code` matching `^[A-Za-z][A-Za-z0-9_]{0,63}$`, including `503 async_dispatch_unavailable`. A missing or invalid status becomes `500 INTERNAL_ERROR` regardless of any supplied code. See [HTTP API](/en/city-sdk-docs/reference/http-api#framework-errors) for defaults and messages.
Business and native handlers own the bodies of error Responses returned directly; the HTTP boundary still overwrites `x-request-id`. The framework does not buffer complete response bodies or SSE. After streaming starts, boundary timeout or cancellation aborts downstream work, cancels the reader, and ends the stream without changing the HTTP status, returning JSON, or synthesizing generic SSE error frames. An `onError` hook failure does not replace the original error.
The model layer uses server-side `AIServiceOptions.model_stream?: Partial`, defaulting to 120 seconds for first useful output, 120 seconds for idle, and 15 minutes total. Native model streams, OpenAI SSE / JSON, and every Relay language model execution share the policy; clients cannot raise deadlines through a request. First output accumulates provider open and actual read waits; idle accumulates actual read waits between useful outputs. Backpressure consumes neither budget, while the total wall clock keeps running. The HTTP SSE total clock starts at the end of request body reading; the model total clock starts at provider execution. Both apply independently, together with shorter provider deadlines and the default 180-second synchronous HTTP deadline; whichever expires first applies.
Model timeouts abort the same foreground execution without transparent retries. Timeout before provider open returns throws 504, such as `MODEL_FIRST_OUTPUT_TIMEOUT` or `MODEL_EXECUTION_TIMEOUT`; idle uses `MODEL_IDLE_TIMEOUT`. The Router preserves valid domain codes with a safe message. Once a native Response has started, model transport emits `model_error` (`provider_timeout`, `status_code: 504`, `retryable: false`), describing first-output timeout, stalled output, or total execution timeout. If no provider `model_start` was received, a framework `model_start` may precede the error solely for the failure terminal protocol, without fabricating usage. OpenAI SSE sends an error frame without a success `[DONE]` on failure; JSON aggregation returns 504 on timeout. An already-started SSE response keeps its HTTP status; these model error frames belong to the model layer.
Completion or cancellation releases timers, listeners, and readers without waiting for an upstream cancel that could hang indefinitely. Trustworthy usage facts are retained; missing usage does not lead to estimated tokens or costs. Existing `bill` callbacks use actual facts, and business charging rules do not promise zero charges in every case without usage. `completion.outcome` explicitly distinguishes `succeeded`, `failed`, and `cancelled`. A cancel after the terminal event does not relabel the result as cancellation or timeout, or duplicate settlement or charges. Underlying SQL side effects are not guaranteed to roll back. See [Calling models](/en/city-sdk-docs/service/ai/calling#model-execution-deadlines) for useful output and the full policy.
## Common API surface
- `new Service({ id, name })`
- `service.action(name, handler, options?)`
- `options.method?: "GET" | "POST"`
- `options.body?: "json" | "raw"` (POST defaults to `"json"`)
- `options.auth: ["user"] | ["admin"] | []`
- `base.use(service)`
- `city.service(id).action(name).invoke(input)`
- `city.service(id).get(path, query?)`
## Common misunderstandings
### An Action is not just a function
It eventually becomes a route, an auth boundary, a hook target, and a usage recording point.
### Official services and custom services do not need separate call patterns
From the product side, both still go through `city.service("service_id").action("action_id").invoke(...)`.
### GET and POST are not cosmetic
Read-oriented operations fit GET better. Execution and mutation fit POST better.
## Read next
- For hooks and extension around actions, read [Hooks and Service Mounting](/en/city-sdk-docs/packages/federation/hooks-and-service)
- For product-side calling, read [@downcity/federation](/en/city-sdk-docs/packages/federation/federation)
- For lower-level method details, read [City API](/en/city-sdk-docs/reference/federation)
### Hooks and Service Mounting
Source: https://downcity.ai/en/city-sdk-docs/packages/federation/hooks-and-service/
A lot of shared capability in Downcity is not created by copying logic into every action. It enters City through hooks and services.
## What each concept solves
The easiest split is:
- hooks: insert rules into an existing call lifecycle
- services: add a full reusable capability set into City
That is why auth, usage, and payment do not become separate systems. They become extension points inside the same Federation.
## When to think hook first
- you want logic before or after existing calls
- the logic is cross-cutting and should not live in every action
- the capability is local to your project and does not need to be its own package
Typical examples:
- quotas
- logging
- risk checks
- charging after a successful call
## When to think service first
- the capability should be reused across many products
- it is more than before or after logic and needs its own service or tables
- you want product-side callers to reach it through a stable service boundary
Typical examples:
- `@downcity/services`
- `@downcity/services`
- `@downcity/services`
## First understand the three hook positions
```txt
global
-> service
-> action
```
Their meanings are:
- global: shared by all services and actions
- service: shared by all actions in one service
- action: only affects one concrete action
## Common service mounting example
```ts
import { AIService, Federation } from "@downcity/federation";
import {
AccountsService,
CreditsService,
PaymentService,
googleAccountsProvider,
stripePaymentProvider,
UsageService,
} from "@downcity/services";
const base = new Federation({ database });
const credits = new CreditsService();
const ai = new AIService({ credits });
base.use(new AccountsService({
token_ttl: "7d",
providers: [
googleAccountsProvider(),
],
}));
base.use(credits);
base.use(ai);
base.use(new PaymentService({
resolve_topup: ({ topup_amount_minor }) => ({ credits: topup_amount_minor * 10_000 }),
on_paid: async (record) => {
await credits.topup({
card: { kind: "primary", user_id: record.user_id },
credits: record.credits,
source: "payment",
ref: record.payment_id,
idempotency_key: `payment:${record.payment_id}`,
});
},
providers: [
stripePaymentProvider({
secret_key: process.env.STRIPE_SECRET_KEY,
webhook_secret: process.env.STRIPE_WEBHOOK_SECRET,
}),
],
}));
base.use(new UsageService({
ai_usage_reader: ai,
credits_usage_reader: credits,
}));
```
In this setup, `AccountsService` owns the accounts HTTP surface. Mounting it once exposes `/providers`, the unified login entry, `me`, admin reads, the better-auth passthrough route, and the OAuth callback route. Concrete login methods appear only when the matching provider is mounted and configured.
`UsageService` combines technical AI usage from `AIService` with applied charges from `CreditsService`; it does not record global service-hook events.
## How product-side callers reach services
Once mounted, services still look like normal services from the product side:
```ts
const login = await guest.service("accounts").action("login/start").invoke({
provider: "email",
client_type: "cli",
bureau_id: "demo",
});
await guest.service("accounts").action("login/continue").invoke({
login_id: login.login_id,
login_secret: login.login_secret,
input: {
email: "user@example.com",
password: "password123",
},
});
const status = await guest.service("accounts").action("login/result").invoke({
login_id: login.login_id,
login_secret: login.login_secret,
});
// Use a verified email; retain this ID across exchange transport retries.
const exchange_id = crypto.randomUUID();
if (status.status !== "done") throw new Error("Login is not ready");
const session = await guest.service("accounts").action("login/exchange").invoke({
login_id: login.login_id,
login_secret: login.login_secret,
exchange_id,
});
const usage = await user.service("usage").get("me", {
from: "2026-08-01",
to: "2026-08-31",
timezone: "America/Los_Angeles",
});
const recent_usage = await user.service("usage").get("me/recent", {
limit: 20,
});
const methods = await guest.service("payment").get("methods");
const checkout = await user.service("payment").action("checkout/create").invoke({
method_id: "stripe",
topup_amount_minor: 500,
idempotency_key: "order_123",
});
```
That means `payment` is both the discovery entry and the execution entry; Stripe is selected as a provider.
## Relationship between hooks, services, and services
A useful chain is:
```txt
service / action
-> hooks add lifecycle rules
-> services add reusable services, tables, and management capability
-> clients still call everything through /v1/*
```
## Common API surface
- `base.use(service)`
- `guest.service("accounts")...`
- `guest.service("payment").get("methods")`
- `user.service("usage")...`
- `admin.service("payment").get("payments")`
## Common misunderstandings
### A service is not just another npm package
It often represents a whole boundary of services, tables, admin surfaces, and optional hook behavior.
### Hooks are not a place to hide full business features
Hooks are best for cross-cutting governance logic, not for turning every feature into middleware.
### Services do not replace City
Services add capability into the Federation. The product-side calling surface is still [@downcity/federation](/en/city-sdk-docs/packages/federation/federation).
## Read next
- For unified product-side service calls, read [@downcity/federation](/en/city-sdk-docs/packages/federation/federation)
- For auth capability, read [@downcity/services](/en/payments)
- For usage recording, read [@downcity/services](/en/payments)
- For one-time Stripe topups, read [@downcity/services](/en/payments)
### Store and Table
Source: https://downcity.ai/en/city-sdk-docs/packages/federation/store-and-table/
Downcity is often seen through AI calls, but its long-term reliability depends on a clear data layer.
## What this concept means
Many Federation capabilities are not just in-memory state. They must persist as data facts:
- whether a city is active
- which token belongs to whom
- what the current env value is
- whether a call has been recorded as usage
- whether a user currently has entitlement
That is why `@downcity/federation` has not only routes and services, but also a store and table layer.
## When you need to care about this layer directly
- you are checking whether a service actually wrote its tables
- you want your own business data to interact with Federation data
- you need controlled trusted-side reads or writes
- you are debugging operations and need facts, not only HTTP responses
## What `base.table()` represents
`base.table(name)` is Federation's controlled exposure of table capability inside one runtime and lifecycle.
## Minimal example: reading and writing tables
```ts
const cities = await base.table("cities");
const env = await base.table("env");
const notes = await base.table("notes.notes");
await notes.insert({
id: "note_1",
title: "First note",
status: "draft",
});
const draftNotes = await notes.select({
status: "draft",
});
```
## What tables you usually encounter
### Built-in Federation tables
- `cities`
- `env`
### Official service tables
Different services bring their own tables, such as accounts-related user or session tables, usage event tables, and Stripe entitlement or webhook event tables.
### Your own business tables
If your services define their own tables, they also live in the same runtime-governed data layer.
## Common scenarios
### Scenario 1: confirm whether data really landed
```ts
const usageEvents = await base.table("service_usage_events");
const rows = await usageEvents.select();
```
### Scenario 2: controlled trusted-side updates
```ts
const envTable = await base.table("env");
await envTable.update({
where: { key: "OPENAI_API_KEY" },
values: { value: "new-secret" },
});
```
### Scenario 3: deletion and cleanup
```ts
const notes = await base.table("notes.notes");
await notes.delete({ id: "note_1" });
```
## Common API surface
- `await base.table(name)`
- `table.select(where?)`
- `table.insert(values)`
- `table.update({ where, values })`
- `table.delete(where)`
## Common misunderstandings
### Federation is not only an API proxy
Many management and city capabilities depend on persistent data facts behind the route layer.
### `table()` is not a reason to skip good service design
You should still prefer services, and `Embassy Admin` for city-facing or managed entry points.
### Frontends should not treat tables as their API
City-side callers should continue to use `Embassy User` and `Embassy Admin`, not raw table access.
## Read next
- For how the database is wired in, read [Federation](/en/city-sdk-docs/packages/federation/federation)
- For terminal inspection of these tables, read [CLI](/en/city-sdk-docs/packages/cli)
- For service-specific data expectations, read the relevant service package docs together with this page
### HTTP and RPC
Source: https://downcity.ai/en/city-sdk-docs/packages/city/transport/
`City` owns one HTTP transport and one RPC transport. Both route by `agent_id` to the same Agent
collection and by `workspace_id` to a Workspace owned by City.
```ts
await city.listen({
http: { host: "127.0.0.1", port: 5314 },
rpc: { host: "127.0.0.1", port: 15314 },
});
await city.close(); // transports only; the creating host still disposes Agents
```
For separate lifecycle control, City can start either transport directly:
```ts
const http = await city.http({ host: "127.0.0.1", port: 5314 });
const rpc = await city.rpc({ host: "127.0.0.1", port: 15314 });
```
HTTP uses `http://host:port/agents//workspaces/` and RPC uses
`rpc://host:port//`.
There are no Agent-level transport constructors; external services belong to City.
### @downcity/city/local
Source: https://downcity.ai/en/city-sdk-docs/packages/local/
`@downcity/city/local` provides the local host capabilities shared by the CLI and Desktop:
the SQLite adapter, paths, product schemas, repositories, environment assembly, and Power loader.
```ts
import {
LocalDatabase,
AgentRepository,
WorkspaceRepository,
ensure_local_schema,
} from "@downcity/city/local";
const database = new LocalDatabase({ filename: database_path });
ensure_local_schema(database);
const workspaces = new WorkspaceRepository(database);
const agents = new AgentRepository(root_path);
```
The CLI and Desktop create these dependencies in their own composition roots, read configuration,
and explicitly call `new Agent()`. The local subpath does not create an Agent, Workspace, Model, or
City. Workspace and platform settings are stored as plaintext JSON, with `0600` permissions on the
local database for user-level isolation.
### CLI Quickstart
Source: https://downcity.ai/en/city-sdk-docs/packages/cli/quickstart/
The `downcity` package installs two command families:
- `fed` / `downfed`: manages and deploys Federations.
- `city` / `downcity`: manages local Agents, local powers, chat/gateway, and the local user's selected Federation login.
## Install
```bash
npm i -g downcity
```
Check versions:
```bash
fed -v
city -v
```
## Manage Federations With fed
Use `fed` when you are creating, deploying, or operating the shared backend.
```bash
fed
fed create
fed create --path ./edge-fed --template cloudflare-workers
fed create --path ./custom-fed --template git://example.com/custom-fed.git
fed deploy
fed deploy --dry-run
fed deploy --verify
```
`fed create` and `fed deploy` default to `--path .`. Use `--path ` for another directory, such as `fed deploy --path ./edge-fed`; positional path arguments are not accepted.
`fed create` generates a Local Node.js + SQLite project by default. `--template` can select `cloudflare-workers` or a Git template. Project identity and deployment intent live in `federation.toml`. Federation project configuration uses TOML only; JSON configuration is not supported.
`fed deploy` deploys the current project whether the destination is local or remote. Local deploys use the fixed default port `12314` when `deployment.port` is omitted and start a managed process. An explicit `deployment.port` overrides the default. If the selected port is occupied, an interactive terminal shows the listener PID, start time, command, working directory, and whether it belongs to the current project, then asks whether to stop it and continue (default: No). After confirmation, the CLI rechecks process identity, sends `SIGTERM`, and waits up to 5 seconds for the port to become available, without escalating to a forced kill. Deployment fails in non-interactive terminals, when process identity cannot be verified, or when the port remains unavailable. `--yes` does not bypass this confirmation. Process inspection requires `lsof` and `ps`. The CLI does not scan for another port or infer one from deployment history. On local deployments, the first deploy interactively sets an administrator ID and password, while ordinary redeploys preserve the existing administrator. Redeploying the same `fed_id` replaces the old process without changing administrator credentials. Cloudflare Workers deploys prepare D1, Queue, and R2, publish the Worker, then create a time-limited administrator Session Token for the local registry.
Manage deployed Federations:
```bash
fed server add
fed server --id fed_x
fed manage --id fed_x
fed server manage --name my-fed
fed web --id fed_x
fed status --id fed_x
fed logs --id fed_x
fed stop --id fed_x
fed restart --id fed_x
fed clean --id fed_x --dry-run
fed clean --name my-fed --yes
fed query GET /health --id fed_x
fed query GET /v1/ai/models --id fed_x
fed query POST /v1/ai/image/result --id fed_x --data '{"job_id":"..."}'
fed bureau token --id fed_x list
```
Federation URLs, administrator IDs, administrator Session Tokens, local PIDs, ports, logs, and deployment status are stored in the system-level Federation registry and do not depend on the current directory. Fed has no global active/default Federation and does not store `active_server_url`; deployment only registers or updates an instance. Lists have no global-current star marker.
`stop`, `restart`, `clean`, `status`, `logs`, `query`, `web`, `server`, `manage`, and `server manage` accept mutually exclusive `--id ` or `--name ` selectors, both with exact matching. Without a selector, a TTY opens a list and the choice applies only to this operation; non-interactive execution fails. Duplicate names prompt for a choice in a TTY and fail outside a TTY. `fed manage` opens the target's management workspace directly and accepts no action positional argument. Bureau Token commands follow the same target rules; selectors can also be placed on the `token` parent command, as shown above. `fed query` adds `Authorization: Bearer` when a valid administrator Session exists and asks you to log in again when it expires.
`fed status` displays the registry record, live system manager facts, and a `/health` probe separately for any saved connection. Local instances also show deployment history. Registered state, saved policy, and deployment outcomes do not establish that a service stopped or that a particular release is running. A local release is reported ready only when the manager verifies its instance identity and the health response has `ok: true` with matching `fed_id`, `release_id`, and `instance_id`. HTTP 200 alone does not establish identity. A manager inspection error is shown as `unknown` and requires manual inspection of the system service and health endpoint.
`logs`, `stop`, and `restart` only support CLI-managed local instances. `logs` displays up to the last 200 lines of the current `service.log` only, without filling from archives; read archives manually. `stop` disables automatic startup and stops the service. The stopped state survives system restarts until an explicit `fed deploy` or a `fed restart` permitted by the recovery guard; those operations restore the automatic startup policy from persisted configuration. Restart runs only the installed artifact with its persisted runtime configuration, without reading or rebuilding source. It works after the original project is deleted. Before restarting, `current.json` must also match the registry release. Build/package/preflight failures allow restarting the last successful release when there is no pending cutover recovery. Entering cutover sets `recovery_required = true`; a failed or interrupted cutover blocks restart until an explicit `fed deploy` succeeds. This guard persists through later build/preflight failures and clears only after a successful deployment. Historical `last_failure` alone does not block restart. Remove connection in the management UI only removes the connection; it does not stop the service.
## Independent Local Node Releases
The compiled entry, complete production dependencies, and project resources are installed at `~/.downcity/federation/deployments//releases/`. The adjacent `current.json` points to the successfully activated release; it does not establish that the release is currently running. Runtime configuration is stored at `~/.downcity/federation/config//runtime.env.json` with file permissions `0600`; the default SQLite path is `~/.downcity/federation/data//data.sqlite`. The registry also stores `release_id`, `release_dir`, `runtime_config_path`, and `data_dir`.
The deployment summary is stored at `~/.downcity/federation/deployments//deployment.json`. `status` shows the last successful release, the last failed release and failure phase, plus the latest release, outcome, phase, cutover, candidate, cleanup, and `recovery required`. A build that has not produced a candidate release shows `not produced`; missing history is displayed separately as not recorded. Failures never overwrite `last_success`. `last_failure` and `latest` are displayed separately, and a historical failure does not establish a current recovery guard. Cleanup describes that attempt's result, not live service state. Missing or unreadable history does not replace manager and health inspection.
Local Node deployments handle failures by phase, without automatic code or database rollback. There is no `rollback` command. These rules apply only to `local` Node, not Cloudflare Workers:
| Phase | Failure handling |
| --- | --- |
| build / package / validate / install / preflight | Preserve the existing instance and persisted runtime configuration without entering cutover. |
| stop | Do not start a candidate or competing instance; inspect the manager and health endpoint to establish actual state. |
| prepare | Commit configuration, initialize the database, and run migrations only after the old service has stopped. On failure, do not start the candidate or automatically roll back code or data. |
| start / ready | Stop the candidate and remove its automatic startup association. Confirmed cleanup is recorded as `stopped`; cleanup errors are recorded as `unknown`. Report both the original deployment error and any cleanup error. `unknown` requires manual inspection of the service, startup association, and health endpoint; it does not mean the service stopped. |
Declare project runtime resources explicitly in `package.json.files`, for example `"files": ["assets", "templates"]`. Production dependencies and their runtime resources are included in full; `.env` is excluded from the artifact. The system Node is used by default. Its version, platform, and architecture must match the build environment, particularly for native modules.
An explicitly selected SQLite database keeps its absolute path. Before deleting the project, check whether the selected database lives inside it; instances using that database still require the file. If the registered database file is missing, deployment fails rather than creating an empty replacement. If no explicit path is set but the source directory contains `data.sqlite` or `data/local.db`, the CLI rejects deployment and requires an explicit path in the project's `.env`, for example `DOWNCITY_FEDERATION_DATABASE_URL=file:/absolute/path/data.sqlite`. It does not guess or migrate the database.
Local `fed deploy --dry-run` builds and validates an artifact in a temporary directory, then deletes it. It does not install a release, modify persisted runtime configuration, or start or stop instances. Build scripts can still write build output into the project.
If an operation lock has a stale owner or no owner, the CLI reports its path and requires manual inspection. It does not automatically reclaim the lock.
Local deployments run under macOS user-level launchd or Linux user-level systemd. `restart_on_failure = true` is the default: unexpected exits trigger recovery at 10-second intervals, limited to 5 attempts within 60 seconds. An explicit stop does not trigger recovery.
`auto_start = false` is the default. Only an explicit `true` installs a persistent definition in macOS `~/Library/LaunchAgents` or enables the Linux user service in `default.target.wants`. macOS starts the service after the user logs in. Linux requires that user's systemd user manager to exist and be available, so this does not guarantee startup at boot. The CLI does not automatically enable linger.
System service definitions reference the launch entry and runtime configuration path without containing secrets. Runtime configuration stays in the separate `runtime.env.json` file with permissions `0600`. Deployment targets are `local` and `cloudflare-workers`; to deploy on another host, run local deployment commands on that machine.
### Local Logs
Application stdout/stderr pass through runner pipes with backpressure and serialized writes to `service.log`: 20 MiB per file with 5 archives, about 120 MiB per Fed including the current file. `.1` is newest and `.5` oldest. Runner diagnostics go to `supervisor.log` in the service directory: 2 MiB per file with 3 archives, about 8 MiB including the current file. These are fixed defaults with no additional configuration.
Oversized chunks are split by actual bytes so each file stays within its limit. Rotation does not restart the service or guarantee complete UTF-8 characters or lines. Logging failures stop the application and mark the runtime receipt `failed`; `status` reports `APPLICATION_LOG_FAILED`, `SUPERVISOR_LOG_FAILED`, or `RUNNER_FAILED` under `runner failure`. Logs and archives must be regular files; symlinks, directories, and other invalid targets are rejected. Existing oversized files cause an error without truncation; the user must explicitly archive or clean them up first.
Application output is not guaranteed to be automatically redacted. Developers must not log tokens, API keys, or complete request/response bodies. macOS launchd stdout/stderr point to `/dev/null`; the Linux journal retains runtime startup information under operating-system quotas. A running instance must load the CLI and runner containing this feature; documentation updates do not apply it. See [Local Fed Logs and Startup Diagnostics](/en/city-sdk-docs/packages/cli/operations-and-debug#local-fed-logs-and-startup-diagnostics) for startup failures and full logging boundaries.
## Clean Local Releases
`fed clean` only cleans releases of locally registered Feds with a local deployment. It does not clean remote connections or unregistered directories. Select the target with mutually exclusive, exact-match `--id ` or `--name `. Without a selector, a TTY opens a list to select one Fed for this operation only; non-TTY execution fails with a missing-target error. Duplicate names prompt for a further choice in a TTY and fail outside a TTY.
```bash
fed clean # TTY selection, preview, then confirmation
fed clean --id fed_x --dry-run # preview only
fed clean --name my-fed # preview, then interactive confirmation
fed clean --id fed_x --yes # explicit confirmation for non-interactive use
```
The preview lists each release ID, size, and reason for deletion or retention before asking for confirmation. `--dry-run` only previews and never deletes. Non-interactive deletion requires explicit `--yes`, which does not bypass protection checks. The default policy always retains the 3 most recent successful releases. There is no `--keep` option.
The following releases are also protected, with retention reasons shown in the preview:
- Releases referenced by the successful activation pointer `current.json` or the registry.
- Releases referenced by the service's `launch.json`, including references awaiting recovery startup.
- Releases referenced by in-progress deployment attempts, and candidates whose cleanup could not be confirmed.
- Unknown or damaged releases, and releases without trustworthy deployment records.
If the runner cannot be verified or any other protection-information check fails, cleaning is refused outright. After target selection, the same Fed operation lock covers preview, confirmation, and deletion to prevent concurrent cutovers from changing references.
Each deployment attempt is stored at `~/.downcity/federation/deployments//attempts/.json` to identify successful and failed deployment history. Failed artifacts are deleted only through a manual `fed clean` and remain subject to these protection checks. The CLI does not automatically clean releases. `clean` never deletes data, config, logs, staging, or deployment history; attempt records and the `deployment.json` summary remain after a release is deleted.
## federation.toml
```toml
schema = 1
type = "federation"
id = "fed_example"
name = "example"
entry = "src/index.ts"
[deployment]
target = "local"
# Optional: override the fixed default port 12314.
port = 12315
[deployment.process]
auto_start = false
restart_on_failure = true
[deployment.scripts]
build = "pnpm typecheck"
```
`deployment.process` applies only to `local`. Omitting the table or either field supplies the defaults above. Both fields require booleans; unknown fields are rejected. Declaring this table for `cloudflare-workers` is an error. Run `fed deploy` to apply project configuration changes; `fed restart` uses the persisted runtime configuration.
The optional `deployment.scripts.build` overrides the build stage; the release builder still compiles the entry. Local targets reject `deployment.scripts.deploy` and run the installed artifact's compiled entry directly with Node. See the [deployment guide](/en/city-sdk-docs/operations/deploy-cloudflare-workers) for Cloudflare Workers script overrides.
## Manage Local Agents And Login State With city
Use `city` when the local machine needs to join a Federation, sign in as a user, run Agents, or open chat.
```bash
city
city federation status
city federation join https://your-federation.example.com
city federation login
city agent create .
city agent list
city on
city agent chat
```
`city agent chat` keeps one live subscription to the active Session and merges Message, Part, text, reasoning, Tool, Interaction, and configuration updates as they arrive. Opening an Agent enters its most recent Session and follows that Session's Workspace; when the Agent has no history yet, Chat opens in the current Workspace and creates a new Session. The header shows the active Session model. Use `/model` to choose from the current user's available model catalog, or `/model ` to switch directly. A model change affects only the active Session and reaches the UI through a Session Mutation; it does not change the Agent default model. When `/session` switches conversations, the TUI subscribes to the new Session before loading its full snapshot and then merges any buffered events. Visible reasoning text is rendered in Assistant Part order with subdued styling; reasoning metadata alone does not produce invented reasoning content.
`city federation ...` only manages local Federation membership and user login state. It does not deploy Federations.
When connecting to the official `private/services/local-node`, `local` login issues an ordinary user token without a password on a trusted machine. CLI requests need no `Origin` header. This node accepts only loopback listen addresses and a loopback `PUBLIC_URL` with the same port. Browser pages must use the target's own origin, `PUBLIC_URL`, or an exact trusted origin in `DOWNCITY_LOCAL_ALLOWED_ORIGINS`. The allowlist does not elevate identity; administrator operations still require a real administrator Session. See [Official local-node configuration](/en/city-sdk-docs/reference/env-vars#official-local-node-configuration) for origin syntax and port constraints.
Each CLI City start has a unique instance ID. `city off` verifies the PID and instance ID together. If pid/meta files are stale or the PID has been reused by another process, the CLI does not signal that unrelated process.
After selecting an OAuth provider such as GitHub or Google, the CLI always prints the `authorization_url`. In a local graphical session it also attempts to open the default browser. When connected to a VPS over SSH or running headlessly, open that URL in your own browser while the CLI waits for the login result.
## Default Storage In federation.toml
Cloudflare Workers Federation projects can declare default storage in `federation.toml`. R2 is currently supported:
```toml
[deployment]
target = "cloudflare-workers"
[deployment.resources.storage]
type = "r2"
binding = "DOWNCITY_STORAGE"
name = "downcity-storage"
public_url_prefix = "https://images.example.com"
```
During deploy, `fed deploy` first checks whether a same-name R2 bucket exists. If it is missing and the deploy is not a dry run, the CLI creates it automatically. The CLI then writes the binding to the temporary `wrangler.toml` as `[[r2_buckets]]` and emits `public_url_prefix` as a Worker var.
## Common Misunderstandings
### `city deploy` is not the deploy entry
Use `fed deploy` to deploy Federations.
### `city create` is not the Federation project entry
Use `fed create` to scaffold a Federation project. Use `city agent create` to create a local Agent project.
### fed and city have different roles
- `fed`: manages shared backend and admin-side capabilities.
- `city`: manages local Agents and user-side connection state.
## Read Next
- To deploy a Federation, read [Deploy to Cloudflare Workers](/en/city-sdk-docs/operations/deploy-cloudflare-workers)
- To debug local state, read [Operations and Debugging](/en/city-sdk-docs/packages/cli/operations-and-debug)
- To understand the Federation runtime, read [Federation](/en/city-sdk-docs/packages/federation/federation)
### Models and Tables
Source: https://downcity.ai/en/city-sdk-docs/packages/cli/models-and-tables/
The CLI is most often used for two things:
- models
- tables
## Why models are a first debugging stop
Many "the AI path is wrong" issues are not provider failures. They are model-layer issues:
- was the model actually registered?
- is the configured model id the one you expected?
- do the stored model rows look correct?
## Why tables matter just as much
When you debug runtime behavior, you usually end up checking tables such as:
- `cities`
- `env`
- usage event tables
- accounts-related tables
- entitlement and webhook tables
## Common model-focused entry points
```bash
city
city federation login
city federation status
```
Use these commands to:
- inspect models exposed by Federation AIService
- select a City base and sign in with City
- confirm local Agents can resolve City connection settings before startup
## Common table-debugging scenarios
### Scenario 1: did a service really create or write data?
If you enabled accounts, usage, or Stripe payment services, what matters is whether your actual City has the tables and rows you expect.
### Scenario 2: why does usage, payment, or auth look wrong?
Looking at the tables first is often the fastest way to distinguish:
- the call never happened
- the service was not enabled
- the tables were not created
- the write failed
## A common workflow
```bash
city
# or start a local agent
city agent start .
city federation status
```
Then continue inside the interactive panel to inspect:
- tables
- schema
- rows
## Relationship with the City data layer
The CLI does not define the data model. It exposes the runtime data layer that City already owns.
That is why this page fits naturally with [Store and Table](/en/city-sdk-docs/packages/federation/store-and-table):
- `@downcity/agent` owns the controlled data layer
- `downcity` owns the human inspection and debugging entry
## Common misunderstandings
### Table inspection is not "low-level debugging"
For City, services, usage, and payment, table facts are often the fastest truth source.
### The CLI is not a general-purpose DB IDE
It is better understood as a City-oriented operations tool.
### Looking at models alone is not always enough
Models, service tables, usage events, and env data can all affect one city flow, so you often need to inspect them together.
## Read next
- For operational decision-making with the CLI, read [Operations and Debugging](/en/city-sdk-docs/packages/cli/operations-and-debug)
- For the data layer behind these tables, read [Store and Table](/en/city-sdk-docs/packages/federation/store-and-table)
### Operations and Debugging
Source: https://downcity.ai/en/city-sdk-docs/packages/cli/operations-and-debug/
The CLI and `Embassy Admin` can both help you debug Downcity, but they fit different work: `fed/downfed` manages Federation, `city/downcity` manages local Agents and local Federation connections, and `Embassy Admin` is for trusted programmatic management.
## The simplest rule first
If your thought is:
- "I need to see the facts right now"
start with the CLI.
If your thought is:
- "this action should live in the system long term"
move toward `Embassy Admin` or a trusted script.
## CLI, Embassy Admin, and direct DB inspection each fit different work
### Better fits for the CLI
- fast local inspection
- checking whether a service actually wrote the expected tables
- inspecting models, schema, and rows
- one-off debugging without writing code first
### Better fits for `Embassy Admin`
- backend-owned actions
- automated token issuance
- formal management workflows
- internal admin surfaces
### Better fits for direct database inspection
- when the issue has clearly reached the lower database layer
- when the CLI already narrowed the problem but you need deeper SQL-level facts
## Common CLI debugging actions
```bash
city
fed
city federation status
city agent list
```
## Local Fed Logs and Startup Diagnostics
```bash
fed status --id fed_x
fed logs --id fed_x
```
Check the system manager, health identity, and `runner failure` in `status` first. `logs` displays up to the last 200 lines of the current `~/.downcity/federation/logs//service.log` only. An empty or shorter current file is not supplemented from archives; read archives manually. Log access is limited to CLI-managed local instances and does not retrieve remote or Worker logs.
Application stdout and stderr pass through runner pipes with backpressure and serialized writes to `service.log`, without an unbounded queue. The limits are fixed defaults and require no additional configuration:
| File | Limit per file | Archives | Total file budget per Fed |
| --- | --- | --- | --- |
| `service.log` | 20 MiB | 5; `.1` newest, `.5` oldest | About 120 MiB, including the current file |
| `supervisor.log` | 2 MiB | 3; `.1` newest, `.3` oldest | About 8 MiB, including the current file |
Rotation splits by actual bytes, including oversized chunks, so each file stays within its limit. File boundaries do not guarantee complete UTF-8 characters or lines. Rotation does not restart the service. If application or supervisor logging fails, the runner stops the application and records `failed` in `~/.downcity/federation/deployments//service/receipt.json`. The `runner failure` field in `fed status` reports the corresponding `failure_code`:
| failure_code | What to inspect |
| --- | --- |
| `APPLICATION_LOG_FAILED` | Application log paths, permissions, disk space, and per-file limits |
| `SUPERVISOR_LOG_FAILED` | Supervisor log paths, permissions, disk space, and per-file limits |
| `RUNNER_FAILED` | Runner startup, runtime configuration, and system service diagnostics |
The runner writes `supervisor.log` in `~/.downcity/federation/deployments//service/`. It records fixed, safe diagnostic events/codes without bodies, tokens, keys, or full environment variables. macOS launchd stdout/stderr point to `/dev/null` and do not hold an unbounded log file directly. Linux writes the same fixed events to this file; the system journal separately retains runtime startup information. Journal quotas and rotation belong to the operating system, and the CLI does not change global journal configuration.
If Node fails before entering the runner, `supervisor.log` and the receipt may have no record of that failure. On macOS, inspect the user service with `launchctl`. On Linux, inspect the corresponding unit's state and startup information with `systemctl --user` and `journalctl --user`.
Current log and archive paths used by the writer must be regular files. Symlinks, directories, and other invalid targets are rejected; links are not followed. Existing files above their per-file limit cause an error and are not truncated. The user must explicitly archive or clean them up first. `fed clean` only cleans releases and does not delete logs.
Application output is not guaranteed to be automatically redacted. Application developers must not log tokens, API keys, or complete request/response bodies. A running instance must load the CLI and runner containing this feature; a documentation update does not apply it to running instances.
## Local SQLite backup and restore
```bash
fed backup --id fed_x
fed stop --id fed_x
fed restore --id fed_x --path /absolute/path/to/backup_id --dry-run
fed restore --id fed_x --path /absolute/path/to/backup_id
```
Online backup uses SQLite's backup API, including committed WAL data, without stopping the application. Restore requires an explicitly stopped service that cannot automatically recover. It saves the current database before preview and confirmation; cancellation does not replace the database, and completion leaves the service stopped. Use `--yes` for explicit non-interactive replacement authorization. Backups can contain sessions, user data, and credentials; files use `0600` and must not enter Git or a release.
See [SQLite Backup and Restore](/en/city-sdk-docs/packages/cli/backup-and-restore) for the full procedure, version compatibility, and failure boundaries.
## CLI and Desktop City ownership
The CLI and Desktop share the same `~/.downcity` data while owning independent City processes.
Each City registers its host at startup. If the other host is already running, the new host asks
whether it should close the existing City and take over. Cancelling leaves the existing host
untouched. Stopping City does not remove Agent, Power, or Session data.
## User system dashboard
Open `fed`, choose a saved Federation, then select `User system dashboard` in the Admin menu.
The CLI reads admin data from the installed official services and computes the dashboard locally in the terminal.
The dashboard covers:
- `accounts`: registered users, new users, active sessions
- `usage`: active users and service-call events
- `payment`: paying users, first-paid users, paid orders, real revenue by currency
- `balance`: credited credits and current balance credits
If a service is not installed, the dashboard marks that module as unavailable and still shows data from the other installed services.
Revenue uses successful payment records and their real `amount_minor` values. Credits are shown separately as balance and recharge units.
## A common debugging chain
1. confirm Federation is connected to the database you think it is
2. confirm the expected models and tables exist
3. confirm the service actually wrote data
4. only then suspect deeper business logic
## Example: usage seems missing
A good first reaction is not "change code" but "confirm facts":
- is the usage service enabled?
- was the usage table created?
- is this really the database instance you expect?
- were any events written at all?
## Example: payment completed but access is still denied
Check these facts first:
- did the webhook reach Federation?
- was the webhook event persisted?
- did the entitlement become active?
## Common misunderstandings
### The CLI is not just a one-time development tool
If you operate many products, services, or model configurations, it remains a frequent operations entry.
### `Embassy Admin` is not just a more advanced CLI
They are different modes:
- `Embassy Admin`: trusted programmatic management
- CLI: human terminal inspection
### Direct SQL should not always be your first instinct
In many cases the CLI is already enough to narrow the problem sharply.
## Read next
- For the basic `fed` / `city` entries, read [CLI Quickstart](/en/city-sdk-docs/packages/cli/quickstart)
- For model and table inspection, read [Models and Tables](/en/city-sdk-docs/packages/cli/models-and-tables)
- For the data layer behind those facts, read [Store and Table](/en/city-sdk-docs/packages/federation/store-and-table)
### SQLite Backup and Restore
Source: https://downcity.ai/en/city-sdk-docs/packages/cli/backup-and-restore/
`fed backup` and `fed restore` support registered local SQLite deployments with an independent release and persisted runtime configuration. They do not operate on remote PostgreSQL, Workers databases, unregistered directories, or database paths inferred from source.
## Create an online backup
```bash
fed backup --id fed_example
fed backup --name example
```
The service may remain running. The CLI uses SQLite's online backup API, including committed WAL data, rather than copying a live main database file. It does not stop or restart the service.
Targets follow the one-operation selection rules: `--id` and `--name` are mutually exclusive exact matches. Omitting them in an interactive terminal opens a list; non-interactive calls require a target. Duplicate names require selection; scripts should use a unique ID.
The database is identified only by the deployment's `runtime.env.json`: `DATABASE_PATH` must be an absolute path to an existing regular file and match the `file:` value in `DOWNCITY_FEDERATION_DATABASE_URL`. The CLI neither creates a missing source database nor searches the current directory for one.
Completed snapshots are stored at:
```text
~/.downcity/federation/backups///database.sqlite
~/.downcity/federation/backups///backup.json
```
`backup.json` is written after the snapshot is complete, converted to a standalone database needing no WAL/SHM files, and passes `PRAGMA integrity_check`. It records the owning Fed, creation time, application version, release ID, byte size, and SHA-256 digest. The CLI syncs the database, metadata, and directories to disk before reporting backup success. Temporary or incomplete directories are not accepted as completed backups.
Directories use `0700`; database and metadata files use `0600`. Backups can contain private user data, administrator and user sessions, service configuration, and credentials. Never commit them to Git or include them in a release. The digest detects file changes; it is neither encryption nor a digital signature. Use appropriate encrypted storage for off-machine copies.
## Preview and restore
Explicitly stop the target service before restore preflight:
```bash
fed stop --id fed_example
fed restore --id fed_example --path /absolute/path/to/backup_id --dry-run
```
`--path` accepts a completed backup directory or its `database.sqlite`. The sibling `backup.json` is required, must not exceed 64 KiB, and must contain valid JSON. The directory name must match its backup ID. A backup can be restored only to its owning Fed. The digest, size, and SQLite integrity are checked again; unknown formats and snapshots with `-wal`, `-shm`, or `-journal` sidecars are rejected. The selected backup directory, database file, and metadata file must not themselves be symbolic links. The checks do not cover every parent directory, so use backups in trusted locations.
`--dry-run` verifies the backup, database location, and manager stop facts without creating a safety backup, checkpointing the current database, replacing data, or changing service state. It does not open the current database to check SQLite integrity or connection contention. Passing preflight does not guarantee that the actual restore will succeed.
Perform a restore:
```bash
# Save the current database, display the plan, then request confirmation
fed restore --id fed_example --path /absolute/path/to/backup_id
# Explicit replacement authorization for non-interactive use
fed restore --name example --path /absolute/path/to/backup_id --yes
```
Preflight requires more than `active: false`. On macOS, the launchd job must be unloaded, its login startup definition absent, and the owned stopped marker present. On Linux, the systemd user service must be inactive, have no main PID, be disabled, have no default-target startup link, and have its stopped marker. Temporary exits, pending automatic recovery, or unverifiable status fail the check. The command does not stop the service for you.
## Restore sequence
1. Acquire the Fed operation lock and validate the target and complete backup.
2. Create a consistent safety backup of the current database with `purpose: before_restore`.
3. Display the replacement path, backup version, and safety backup location for explicit confirmation.
4. Recheck stop facts, backup integrity, and whether the current database changed during confirmation.
5. Prepare and verify the replacement in the current database's directory. Use SQLite checkpointing to settle WAL state, refusing databases held by other connections.
6. Atomically replace the main database and save its stopped status. Leave the service stopped.
Cancelling confirmation leaves the current database unreplaced and retains the safety backup. The read-only SQLite connection used for the safety backup may create empty WAL/SHM sidecars that remain after cancellation. Their presence does not mean the main database was replaced. Incomplete or modified snapshots, detected external writes during confirmation, and database contention that blocks validation prevent replacement. After confirmation, replacement preparation may checkpoint the current database and switch it to DELETE journal mode. A later failure before main-file replacement does not mean the files and journal state are unchanged. Errors from the replacement stage report whether replacement completed and where the safety backup is stored. Cleanup attempts every temporary restore file and its sidecars. If cleanup fails, the thrown `AggregateError` message still states whether the database was replaced and includes the safety backup path. Its `errors` array retains each cleanup error and, if restoration also failed, the original restore error. Inspect the database, safety backup, and manager stop facts before deciding what to do next. Do not retry blindly.
The Fed lock excludes concurrent deploy, restart, stop, and clean commands for this deployment. It does not control external processes bypassing Fed; close other direct database tools during restoration.
## After restoration
Restoration replaces the entire database, including database-stored accounts, sessions, business configuration, billing, and job facts. It does not switch the application release, `current.json`, persisted `runtime.env.json`, logs, or the City's selected connection.
The database schema must be compatible with the installed application. The CLI displays versions but does not guarantee schema compatibility across versions, roll back the application, or automatically migrate data. Decide explicitly whether to run `fed restart --id fed_example` after inspection. Existing deployment recovery guards remain in effect.
Database-stored administrator sessions may change, so the CLI's saved administrator Session may require a new login. User Tokens retained by City are valid only according to the restored database facts. Credential validity before restoration is not a guarantee afterward.
Backups and safety backups are neither scheduled nor cleaned automatically. `fed clean` manages releases only; it does not delete backups, databases, configuration, or logs. Establish a separate retention and off-machine storage policy.
### @downcity/agent
Source: https://downcity.ai/en/city-sdk-docs/packages/agent/
`@downcity/agent` provides Agent, AgentSessions, Session, and the execution runtime. `@downcity/city` provides RemoteAgent and
City. Agents do not own Powers. City owns unique Power instances, configuration projection, and lifecycle;
Power author contracts live in `@downcity/city/power`. Workspace resources come from
`@downcity/city`.
```ts
const city = new City({ workspaces: [workspace] });
const agent = new Agent({ id: "assistant" });
city.agents.add(agent);
const session = await agent.sessions.create({ workspace });
const turn = await session.prompt({ query: "Hello" });
const result = await turn.finished;
```
Provide Power instances through `CityOptions.powers` or `city.powers.add()` before use.
`city.agents.add()` only registers an Agent; every City Power becomes available automatically.
## Session origins and execution profiles
`origin.category` selects the `chat` or `work` category, and `origin.type` describes the business purpose. Callers define custom types and declare their category explicitly:
```ts
const session = await agent.sessions.create({
origin: { category: "work", type: "research" },
});
```
Each Power defines its own business types. A type name labels the purpose; the actual execution configuration supplies tools, instructions and the model. Memory Power creates `memory` Sessions in the `work` category and selects its dedicated execution profile. Using the same type name alone grants neither Memory tools nor permission to commit Job results.
A Session bound to a dedicated profile persists its profile ID, version and model identity. Restoration must resolve that profile. An unavailable profile or mismatched model identity rejects execution without falling back to Agent defaults.
## Read file changes for each turn
A Session bound to a Workspace persists file edits successfully committed by the built-in
structured `write` and `edit` tools in the final Assistant Message. The diff comes directly from
each atomic file-tool mutation instead of scanning the worktree before and after a turn, so changes
made by shell commands, scripts, external editors, or other Sessions are excluded. Git is not
required.
The `data-session-turn-file-diff` data part contains per-file status, line counts, and unified diff.
Use the exported parser to read it safely:
```ts
import { read_session_turn_file_diff_data } from "@downcity/agent/session";
const page = await session.messages();
for (const message of page.items) {
if (message.type !== "assistant") continue;
for (const part of message.parts) {
if (part.type !== "data") continue;
const file_diff = read_session_turn_file_diff_data(part);
if (file_diff) console.log(file_diff.files, file_diff.additions, file_diff.deletions);
}
}
```
## Group and GroupSession
`Group` is a collaborative subject with its own model, members, dispatch strategy, and
`GroupSession` collection. A GroupSession persists shared messages and dispatch state under
`groups//sessions//`.
After the first user message is persisted, the GroupSession uses `Group.model` to generate a
short title asynchronously. The title is canonical metadata stored in `meta.json`; it is separate
from `preview_text`, which remains the latest-message preview. Later messages do not replace the
title. Subscribe to `{ type: "title", title }` for live title changes, or call
`group_session.rename(title)` to persist a manual title and prevent background generation from
overwriting it.
```ts
const group_session = await group.sessions.create({ workspace });
group_session.subscribe((event) => {
if (event.type === "title") console.log(event.title);
});
await group_session.prompt({ query: "Review the login flow" });
await group_session.rename("Login flow review");
const sessions = await group.sessions.list();
console.log(sessions[0].title, sessions[0].preview_text);
```
### @downcity/city/workspace
Source: https://downcity.ai/en/city-sdk-docs/packages/workspace/
`@downcity/city/workspace` provides the Workspace implementation used by an Agent; common
constructors are also exported from `@downcity/city`. A Workspace owns the
project path, rooted file access, file and search tools, environment variables, and an optional Shell.
It does not own Agent identity, Powers, Sessions, storage, or model calls.
```bash
pnpm add @downcity/city @downcity/sandbox-microsandbox
```
```ts
import { Agent, City, Shell, Workspace } from "@downcity/city";
import { MicrosandboxProvider } from "@downcity/sandbox-microsandbox";
const workspace = new Workspace({
id: "project",
path: process.cwd(),
env: { NODE_ENV: "development" },
shell: new Shell({
sandbox_provider: new MicrosandboxProvider(),
}),
});
const city = new City({
workspaces: [workspace],
});
const agent = new Agent({ id: "repo-helper", model });
city.agents.add(agent);
const session = await agent.sessions.create({ workspace });
```
## Ownership
- `Workspace` owns project resources and the optional Shell.
- `Shell` owns its Sandbox Provider, persistent Workspace Sandbox, and Shell Sessions.
- `City` owns registered Workspaces without understanding their execution backend.
- `Agent` owns identity, instruction, model, custom tools, and Sessions; `City` owns Powers.
- `AgentSessions` owns Sessions. A Workspace is only a resource that a Session may use.
- Shell is a Workspace capability. There is no separate `@downcity/shell` package.
An Agent can create Sessions with multiple Workspace resources. A Workspace may be registered in a
City or managed by the host outside City. Agent-private Sessions and City-allocated Agent/Power
execution data remain isolated.
After an atomic file commit, the structured `write` and `edit` tools report a
`workspace.file_mutation` through `WorkspaceToolActionResult.effects`. Effects are not sent to the
model as Tool output. The Agent Session collects them only for the current Turn and projects file
mutations into an Assistant data part when the Turn closes. Shell and external edits do not produce
this effect.
## Storage
City provides a domain-neutral Storage Provider. The default is in-memory; a host can inject a local
file provider when persistence is needed. With a local provider, runtime state is centralized outside
project directories:
```text
~/.downcity/agents//
├── sessions/
└── powers/
```
`StorageProvider` is intentionally domain-neutral. Agent runtime interprets Session data, while the
City Power runtime interprets Power data. Workspace does not own or create this storage. Project
File/Search tools remain rooted at the real project path and cannot read this private state.
Edge adapters should import `WorkspaceRuntime` and protocol types from `@downcity/type/workspace`
so they do not load Node.js filesystem, PTY, or local Shell implementations.
### AIChannel and Provider Adapters
Source: https://downcity.ai/en/city-sdk-docs/service/ai/provider/
`AIChannel` owns only Federation's upstream execution boundary. It accepts `AIChannelStreamInput` and returns a `ReadableStream`. Fallback, billing, Sessions, and tool execution do not belong to the Channel.
## OpenAI-compatible upstream
```ts
import {
AIChannel,
AIService,
stream_openai_compatible_model,
type AIChannelStreamInput,
type AIChannelStreamResult,
} from "@downcity/federation";
class DeepSeekChannel extends AIChannel {
constructor() {
super({
id: "deepseek",
env: { DEEPSEEK_API_KEY: "DeepSeek API Key" },
base_url: "https://api.deepseek.com/v1",
});
}
protected async stream(
input: AIChannelStreamInput,
): Promise {
const api_key = input.env("DEEPSEEK_API_KEY");
if (!api_key) throw new Error("DEEPSEEK_API_KEY is required");
return stream_openai_compatible_model(input, {
api_key,
base_url: this.base_url ?? "https://api.deepseek.com/v1",
});
}
}
const channel = new DeepSeekChannel();
const ai = new AIService();
ai.use(channel.model({
id: "deepseek-v4-flash",
upstream_model: "deepseek-chat",
name: "DeepSeek V4 Flash",
context_window: 128_000,
}));
federation.use(ai);
```
`stream_openai_compatible_model()` is a boundary adapter. It maps `ModelCall` to Chat Completions and converts upstream SSE into Downcity events. A private vendor protocol should provide its own adapter with the same input and output contract.
## In-process ModelClient
For local Agent use without Federation:
```ts
const model = create_openai_compatible_model({
id: "deepseek-chat",
upstream_model: "deepseek-chat",
base_url: "https://api.deepseek.com/v1",
api_key: process.env.DEEPSEEK_API_KEY!,
});
```
## Reasoning and fallback
```ts
ai.use(channel.model({
id: "text-model",
upstream_model: "vendor-text-model",
name: "Text Model",
reasoning: {
efforts: [{ id: "high", name: "High" }],
default_effort: "high",
},
fallback: [{
match: (file) => file.media_type.startsWith("image/"),
model_id: "vision-model",
}],
}));
```
AIService passes only files from the latest user message to fallback rules. After selecting the final model, it validates reasoning and preserves that latest user message unchanged. Historical files matched by the final model's fallback rules become filename, original URL, or MIME type text before the call reaches the target Channel.
Channel and model `provider_options` are merged only on the server and interpreted by the selected Adapter. They are not part of the public model protocol.
## Decision models (System One)
A model that returns typed decisions instead of generated text implements `decision()` instead of `stream()`:
```ts
import {
AIChannel,
AIService,
type AIChannelActionInput,
type AIChargedResult,
type AIDecisionResult,
} from "@downcity/federation";
class JevChannel extends AIChannel {
constructor() {
super({ id: "typesafe", env: { TYPESAFE_API_KEY: "TypeSafe API Key" } });
}
async decision(input: AIChannelActionInput): Promise> {
const api_key = input.env("TYPESAFE_API_KEY");
if (!api_key) throw new Error("TYPESAFE_API_KEY is required");
return { output: await call_jev(api_key, input.input) };
}
}
const ai = new AIService();
ai.use(new JevChannel().model({
id: "jev-1.13",
upstream_model: "typesafe/jev-1.13",
name: "Jev",
pricing: { currency: "USD", unit: "request", rates: { request: 0.0004 } },
}));
federation.use(ai);
```
Federation exposes `POST /v1/ai/decision` automatically and validates the request before the call reaches the Channel. The catalog reports `model_type: "decision"` with `modalities: ["decision"]`, and because the model does not implement `stream()`, it is not offered as an Agent conversation model.
Metering and billing reuse the same path as every other capability: return `usage` from the Channel to record usage, and declare `pricing` to charge per request.
### OpenAI Chat Completions
Source: https://downcity.ai/en/city-sdk-docs/service/ai/chat-completions/
`POST /v1/ai/chat/completions` is an adapter around Downcity Model Protocol:
```text
OpenAI request
-> ModelCall
-> AIService / AIChannel
-> ModelStreamEvent
-> OpenAI JSON or SSE
```
```bash
curl "$FEDERATION_URL/v1/ai/chat/completions" \
-H "Authorization: Bearer $USER_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-v4-flash",
"messages": [{"role":"user","content":"Hello"}],
"stream": true
}'
```
Messages, tools, tool choice, images, reasoning, usage, and finish reasons are converted into the same Downcity execution path. The endpoint is not a raw passthrough.
### Model relay and API keys
Source: https://downcity.ai/en/city-sdk-docs/service/ai/relay/
A Federation with model relay enabled exposes `GET /v1/models` and `POST /v1/chat/completions`. Set your OpenAI client's Base URL to your Federation URL plus `/v1`. Streaming, non-streaming, tools, and usage share the existing AIService execution and settlement pipeline.
## Manage your keys
Website users can manage their own keys in [Account → API Keys](/account?view=keys); the full secret appears only in the successful creation dialog. SDK integrations use the account's login `user_token` to manage keys. A calling key cannot access account, payment, key management, or request history APIs.
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: "https://your-federation.example",
user_token,
});
const issued = await embassy.user.relay.create_key({
name: "Editor",
allowed_models: ["deepseek-v4-flash"],
spend_limit: 10000,
expires_at: null,
});
// Store issued.api_key securely in your calling client; it cannot be retrieved again.
const keys = await embassy.user.relay.list_keys();
await embassy.user.relay.update_key({ key_id: issued.key.key_id, status: "disabled" });
await embassy.user.relay.update_key({ key_id: issued.key.key_id, status: "active" });
await embassy.user.relay.revoke_key(issued.key.key_id);
```
`allowed_models` contains public model or route IDs. `[]` permits no inference; `["*"]` permits all published entries. Access to a route does not grant direct access to its model. Names, permissions, limits, and expiration can be updated. Disabled keys can be reactivated; revoked keys cannot. Disabling or revoking a key blocks new requests, while in-flight requests still settle.
`spend_limit` is measured in Credits; `null` means no key spending limit. Before inference, the service checks account balance and the key's **successfully settled** spending. It does not reserve funds. Concurrent in-flight requests can exceed the configured amount, so this is a soft limit. A key has no separate wallet: charges use the account's existing Credits ledger. Changing the limit does not reset settled lifetime spending; zero blocks new calls. The website shows the actual limit and does not infer used spending when the backend does not provide it.
The key list shows name, status and spending limit. Open a key's name for its permissions, expiration and creation time; use the right-hand actions to edit, disable, reactivate or revoke it. Copy and store a newly issued key before closing its one-time dialog. Never share it or include it in public code.
## Use an OpenAI client
Website [Models & setup](/account?view=models) provides the live catalog and backend-declared pricing. Open **Set up** for the selected model's capabilities, full pricing conditions, public model ID and configuration-derived Base URL. Copy those values into your client. The page never reads a real key; catalog visibility does not grant your key access.
Prices preserve the backend currency, quantity, unit, rate components and applicability dimensions. Multi-component or conditional pricing is not a single flat rate, and missing pricing does not mean free. No Credits conversion or discount is inferred. Unknown context or reasoning options remain undeclared; tools and vision support must not be inferred from model names or tags.
Set `FEDERATION_URL` to your service address and `DOWNCITY_API_KEY` to your securely stored calling key. Replace the example model ID below with the model or route ID copied from the catalog.
```bash
curl "$FEDERATION_URL/v1/models" \
-H "Authorization: Bearer $DOWNCITY_API_KEY"
curl "$FEDERATION_URL/v1/chat/completions" \
-H "Authorization: Bearer $DOWNCITY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"deepseek-v4-flash","messages":[{"role":"user","content":"Hello"}],"stream":true}'
```
Chat Completions supports streaming and non-streaming language calls. Responses and Anthropic Messages are not supported. Native `POST /v1/ai/stream` also accepts calling keys, using the Downcity Model Protocol's `model_id` and `call`:
```bash
curl "$FEDERATION_URL/v1/ai/stream" \
-H "Authorization: Bearer $DOWNCITY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"protocol_version":1,"model_id":"deepseek-v4-flash","call":{"messages":[{"role":"user","content":[{"type":"text","text":"Hello"}]}]}}'
```
The native endpoint returns Downcity model-event SSE, not OpenAI SSE; parse it with a client that implements the native protocol. With relay enabled, language endpoints preserve the requested model's capabilities and selling price. They do not automatically switch to another model for new media input. Explicitly select a capable model when needed.
## Inspect requests and spending
Website [Request history](/account?view=requests) offers your own request pages, key filtering and safe attempt details. The list shows model, execution status, charge and time. Open a model name to inspect the key, request ID, token measurements, duration, settlement and upstream attempts. **Filters** narrows the list by key; refresh and cursor pagination keep the existing query behavior. Unknown metering and unsettled charges remain unknown rather than zero.
```ts
const page = await embassy.user.relay.list_requests({ limit: 50 });
const record = page.items[0];
if (record) {
const attempts = await embassy.user.relay.list_attempts(record.request_id);
const next_page = await embassy.user.relay.list_requests({ before: record.request_id });
}
```
The Federation Router generates a `req_` for each HTTP request and ignores caller-supplied IDs. The relay record's `request_id`, Action `Context.request_id` and `Context.locals.request_id`, and the `x-request-id` response header all use that same ID; every upstream attempt has its own `attempt_id`. The Router overwrites the header on success, errors, native Responses, streams, and route 404s without consuming the body or buffering SSE. Framework error bodies and errors after streaming starts follow the [HTTP API contract](/en/city-sdk-docs/reference/http-api#framework-errors). History includes key ownership, model, channel, tokens, duration, and settlement status. Attempts include time to the first content event. `charged_credits` is available only after settlement reaches `completed`. Failed attempts, missing usage, and pending settlement must not be interpreted as zero spending. Logs do not store prompts, responses, calling keys, or provider credentials. Execution, metering and settlement are recorded separately. Requests rejected before upstream execution may have no history record. First-content latency is measured from the logical request start; unknown outcomes do not trigger automatic regeneration.
## Enable relay in your Federation
```ts
const ai = new AIService({
relay: true,
credits: {
precheck: (user_id, needed_credits) => credits.precheck(user_id, needed_credits),
charge: (input) => credits.charge(input),
},
}).use(models);
federation.use(ai);
```
The first startup imports registered language models into the persistent catalog, retaining their adapters and billing functions. Publish subsequent templates through the management SDK. Public capabilities, reasoning options, and selling prices come from registered templates; operators configure availability, channels, upstream mappings, priorities, weights, and routes. The website provides personal key management. Administrators can use Fedman's Channels & routes page to manage public models, channels, deployments and routes, or use the admin SDK below.
```ts
const admin = new Embassy({ federation_url, admin_token });
const metadata = await admin.admin.relay.metadata(); // Installed templates and adapters, no credentials
const health = await admin.admin.relay.health(); // Shared cooldown snapshot, not an active probe
const snapshot = await admin.admin.relay.catalog();
// Edit snapshot.catalog, then submit the revision that was read.
await admin.admin.relay.configure(snapshot.catalog, snapshot.revision);
```
Fedman derives form choices from the live catalog and `metadata()`. Create, edit, enable/disable and confirmed deletion use the existing catalog contract. References block deletion; there is no implicit cascade. Saves include the read revision; after a 409 conflict, reload the latest catalog and edit again. Registered channels must be installed and retain fixed runtime mappings. OpenAI channels reference server environment variable names; do not enter secret values. Deployment status shows shared cooldowns only. No cooldown record does not imply healthy service; no paid active probe is provided.
The catalog separates Model, Channel, Deployment, and Route. A Model references a capability and price template. A Channel selects the `registered` or `openai_chat_completions` adapter. A Deployment maps a public model to a channel and upstream model. A Route chooses deployments of the same public model. Standard OpenAI channels use a credential-free HTTPS API root as `base_url` and a Federation environment variable name as `credential_env`; catalog APIs never return credential values. New channels must support the template's declared capabilities.
The default `priority_weighted` strategy chooses the highest `priority` tier, then samples positive integer `weight` values. Direct model calls permit at most two attempts; a route's `max_attempts` is 1–3. Explicit 401, 403, and 429 rejections allow failover. Network errors, 5xx responses, timeouts, and errors after receiving an upstream stream do not trigger automatic retries. Shared database cooldowns honor `Retry-After` for 429 responses, capped at five minutes; other failures use short cooldowns. Expired cooldowns allow normal traffic to probe recovery. Channel `timeout_ms` defaults to 120000 and accepts 1000–300000; adapters must honor the cancellation signal.
Catalog snapshots are cached for five seconds per instance. Updates require `revision` to prevent lost writes; other instances see changes within one cache interval. Routing adds no model invocation. Key state is read on every request, while settled spending and account balance checks run in parallel. Requests and attempts are persisted before upstream execution, and shared health is read from the database. Measure the resulting latency in your deployment; it depends on database placement and upstream behavior.
RPM, TPM, global concurrency leases, Responses, Anthropic Messages, and OAuth account pools are not provided yet.
### Call a model
Source: https://downcity.ai/en/city-sdk-docs/service/ai/calling/
## Call a Federation model
```ts
const catalog = await city.ai.catalog();
const model = catalog.require("deepseek-v4-flash");
const stream = await model.stream({
messages: [{
role: "user",
content: [{ type: "text", text: "Explain this repository" }],
}],
});
for await (const event of stream) {
if (event.type === "text_delta") process.stdout.write(event.delta);
}
```
`model.stream()` returns a `ReadableStream`. A successful stream begins with `model_start` and provides final `model_usage` before `model_finish`. Invalid event ordering fails as a protocol error.
## Use a model with Agent
Objects returned by the catalog implement `ModelClient` and can be passed directly to Agent:
```ts
const catalog = await city.ai.catalog();
const model = catalog.require("deepseek-v4-flash");
const agent = new Agent({ id: "reviewer", model });
```
Agent owns Session context, tool loops, and approvals. Federation owns final model selection and billing.
## Multimodal fallback
Fallback checks file content only in the latest `role: "user"` message in `ModelCall.messages`. A new text-only user message does not trigger fallback again. When the final model's fallback rules reject a historical file, the execution view replaces that file with its `filename`, original URL, or MIME type as plain text. The original Session file remains unchanged. Trailing assistant or tool messages do not change which user message is inspected.
## OpenAI-compatible clients
Use `/v1/ai/chat/completions` for the OpenAI SDK, curl, or an existing gateway. The boundary adapter converts that request into the same `ModelCall`, so routing, fallback, reasoning, usage, and billing stay consistent.
## Model execution deadlines
Native `/v1/ai/stream`, OpenAI-compatible SSE and JSON, and every Relay language model execution share `execute_model_stream` and the server-side `AIServiceOptions.model_stream?: Partial`. Omitted fields use these defaults. An individual client request cannot raise the policy limits.
```ts
/** Configure language model execution deadlines in milliseconds. */
import { AIService } from "@downcity/federation";
const ai = new AIService({
model_stream: {
first_output_timeout_ms: 120_000,
idle_timeout_ms: 120_000,
total_timeout_ms: 900_000,
},
});
```
| Policy | Default | Clock |
| --- | --- | --- |
| `first_output_timeout_ms` | 120 seconds | Cumulative time waiting for provider open and actual reads before the first useful output |
| `idle_timeout_ms` | 120 seconds | Cumulative time waiting for actual reads between useful outputs; each useful output resets the budget |
| `total_timeout_ms` | 15 minutes | Wall-clock time from the start of provider execution, including open, reads, and consumer backpressure |
Consumer backpressure does not consume the first-output or idle budget; the total clock keeps running. `model_start`, `text_start`, `reasoning_start`, empty deltas, and usage are not useful output and do not renew the budget. Non-empty `text_delta` / `reasoning_delta`, `tool_call_start`, non-empty `tool_call_delta.input_delta`, and `tool_call_finish` count as useful output. Values must be safe integers from 1 through 2,147,483,647. Unknown fields or invalid values fail at construction.
Shorter provider deadlines, the default 180-second synchronous HTTP execution deadline, and the model policy apply independently. Whichever expires first aborts the same foreground execution. Timeouts do not trigger transparent retries.
## Model failures, usage, and settlement
A timeout before provider open returns throws HTTP 504 with a domain code such as `MODEL_FIRST_OUTPUT_TIMEOUT` or `MODEL_EXECUTION_TIMEOUT`; open consumes the first-output budget. An idle timeout uses `MODEL_IDLE_TIMEOUT`. The Router preserves valid domain codes and uses the safe message `Request timed out`.
Once the response has started, the native stream emits `model_error` with `code: "provider_timeout"`, `status_code: 504`, and `retryable: false`. Its message is `Model first output timed out`, `Model output stalled`, or `Model execution timed out`. If the provider has not emitted `model_start`, the transport may first emit a framework `model_start` solely to make the failure terminal conform to the protocol. It does not imply useful provider output or fabricate usage. OpenAI SSE emits an error frame and does not send a success `[DONE]` on failure; OpenAI JSON aggregation returns 504 on timeout. An SSE response that has started keeps its HTTP status.
Preserve all trustworthy usage facts already received. Without returned usage, tokens and costs are not estimated. Existing `bill` callbacks use actual facts; the business determines charging, and missing usage is not a promise of zero charges in every case. `completion.outcome` explicitly distinguishes `succeeded`, `failed`, and `cancelled`. A cancel after the terminal event does not relabel the result as cancellation or timeout, or cause duplicate settlement or charges.
## Media requests, HTTP deadlines, and cancellation
HTTP endpoints `/v1/ai/image/create`, `/v1/ai/asr`, `/v1/ai/tts`, `/v1/ai/video`, `/v1/ai/decision`, `/v1/ai/embedding`, `/v1/ai/rerank`, and `/v1/ai/audio` default to a 40 MiB body, a 60-second body read deadline, and a 180-second execution deadline. `/v1/ai/stream`, `/v1/ai/chat/completions`, and `/v1/chat/completions` use the same defaults. Lightweight `/v1/ai/image/result` uses ordinary limits: 1 MiB / 15 seconds / 30 seconds.
Body limits count actual `Uint8Array.byteLength`, including Base64 and JSON wrapping, and do not replace model or media file validation. Missing or falsely small `Content-Length` cannot bypass the limit. Invalid lengths return `400 INVALID_CONTENT_LENGTH`; a `Content-Encoding` other than `identity` returns `415 UNSUPPORTED_CONTENT_ENCODING`. Body timeout returns `408 REQUEST_BODY_TIMEOUT`, and oversized bodies return `413 BODY_TOO_LARGE`. The body deadline is total and does not reset on arriving chunks.
HTTP execution timing starts after the request body has been read. For non-SSE responses, the timer stays active until the response body finishes reading or is cancelled. Expiry before headers returns `504 REQUEST_TIMEOUT`; after headers have been sent, it only ends the stream. The HTTP boundary waits up to 180 seconds for model and media response headers by default; the model policy can expire earlier. On receiving an SSE `Response`, the HTTP timer switches to the default 15-minute `stream_lifetime_ms` total deadline, still measured from the end of request body reading and including the header wait. This clock is independent of the model total deadline measured from provider execution; whichever expires first applies.
The HTTP boundary does not buffer SSE, change an HTTP status after headers, or synthesize generic SSE error frames. The model layer expresses model timeouts through the native or OpenAI protocol described above. Timeout, cancellation, or completion releases timers, listeners, and readers without waiting for an upstream cancel that could hang indefinitely.
Client cancellation corresponds to `499 REQUEST_CANCELLED`; disconnected clients are not guaranteed to receive a response. Queued image tasks run independently and do not inherit cancellation from foreground creation or result queries. Cancelling a query does not cancel the image task. Database operations may continue; cancellation does not automatically roll back transactions or trigger retries. Provider Adapters should combine the request signal with their own deadlines; shorter upstream deadlines still apply.
For HTTP boundary configuration, see [Federation runtime](/en/city-sdk-docs/packages/federation/federation#http-policy-configuration) for configuration. Production deployment requires building the SDK and service artifacts containing the feature; running instances do not update automatically.
## Call a decision model
A decision model takes raw state and typed questions, and returns answers with calibrated probabilities instead of generated text:
```ts
/** Call Jev through the current Federation user context. */
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: "http://localhost:3000",
user_token: process.env.FEDERATION_USER_TOKEN,
});
const { answers } = await embassy.user.ai.decision({
model: "jev-latest",
state: { type: "text", text: "The customer has failed to connect Stripe for three days." },
questions: [
{ id: "urgent", type: "boolean", instructions: "Does this message express urgency?" },
{ id: "route", type: "choice", instructions: "Which queue should handle this?", options: ["billing", "support"] },
{ id: "churn_risk", type: "score", instructions: "Churn risk", min: 1, max: 4 },
],
});
answers[0].value; // true
answers[0].probability; // 0.87
answers[1].distribution; // { billing: 0.72, support: 0.28 }
```
The official edge-worker and local-node both provide `jev-latest` through B.AI's official `https://api.b.ai/v1/decisions` endpoint. Configure `B_API_KEY` in the Federation's Global / Env to enable `choice`, `score`, and `boolean` decisions. Jev is also available in the Desktop Group dispatch model selector.
The model catalog exposes structured `pricing` with currency, billing units, rates, and applicable conditions.
Jev accepts 2–255 choice options. Score ranges must map to 2–10 levels (`round(max - min) + 1`), and boolean results use a 0.5 probability threshold. JSON state cannot be an empty object or array.
`state` is either `{ type: "text", text }` or `{ type: "json", data }`. Three question types are supported, and none of them produces free text:
| Type | Answer | Notes |
| --- | --- | --- |
| `boolean` | `true` / `false` | — |
| `choice` | one of `options` | 1 to 255 unique options |
| `score` | a number | requires `min < max` |
Question ids must be unique and every question must be answered exactly once. Invalid input fails with 422 before any usage is recorded, and a Channel response that does not cover every question is rejected too.
`embassy.user.ai.decision(input, signal)` accepts an optional `AbortSignal`. Use `question_id` to associate each answer with its question. Group can bind this method as its decision client to select parallel responders each round; members keep their own execution models.
Decision models are not conversation models: they carry `modalities: ["decision"]` and cannot be passed to an Agent.
### Feedback Service
Source: https://downcity.ai/en/city-sdk-docs/service/feedback/
`FeedbackService` adds a simple feedback inbox to a Federation. Signed-in users can submit feedback for the Bureau bound to their Token, admins can review and reply, and users can later read the official reply through the API.
## Register
```ts
import { Federation } from "@downcity/federation";
import { FeedbackService } from "@downcity/services";
const fed = new Federation({ database });
fed.use(new FeedbackService());
```
The service stores feedback in Downcity's database. It does not send email, Slack messages, webhooks, or push notifications.
## User APIs
Submit feedback with a user token:
```bash
curl http://127.0.0.1:43127/v1/feedback/send \
-H "Authorization: Bearer ub_xxx" \
-H "Content-Type: application/json" \
-d '{
"message": "Image generation often stays queued",
"contact": "user@example.com",
"meta": {
"page": "/billing",
"client_version": "1.2.3"
}
}'
```
Response:
```json
{
"feedback_id": "fb_xxx",
"status": "open",
"created_at": "2026-06-30T10:00:00.000Z"
}
```
Read the current user's feedback for the Bureau bound to the Token:
```bash
curl "http://127.0.0.1:43127/v1/feedback/me?status=replied&limit=50" \
-H "Authorization: Bearer ub_xxx"
```
The response includes the original message, current status, admin reply, reply author, and reply timestamp.
## Admin APIs
List feedback:
```bash
curl "http://127.0.0.1:43127/v1/feedback/messages?status=open&limit=100" \
-H "Authorization: Bearer sk_admin_xxx"
```
Optional filters are `bureau_id`, `user_id`, `status`, and `limit`.
Reply to feedback:
```bash
curl http://127.0.0.1:43127/v1/feedback/reply \
-H "Authorization: Bearer sk_admin_xxx" \
-H "Content-Type: application/json" \
-d '{
"feedback_id": "fb_xxx",
"reply": "We fixed the async result parser.",
"reply_by": "support"
}'
```
Update status:
```bash
curl http://127.0.0.1:43127/v1/feedback/status \
-H "Authorization: Bearer sk_admin_xxx" \
-H "Content-Type: application/json" \
-d '{
"feedback_id": "fb_xxx",
"status": "closed"
}'
```
Supported statuses are `open`, `reviewing`, `replied`, and `closed`.
### Production Checklist
Source: https://downcity.ai/en/city-sdk-docs/operations/production-checklist/
Before launch, confirm at least the following:
## Security
- Administrator IDs, passwords, and session tokens exist only in trusted environments.
- Clients only receive `user_token`, not provider keys.
- `DOWNCITY_FEDERATION_TOKEN_SIGNING_KEY` is configured in City.
- Admin env endpoints only accept trusted requests.
## Stability
- Every service that should be exposed has been registered through `base.use(service)`.
- AI models have been registered through `AIChannel.model()` + `AIService.use()` and include the required capabilities.
- Critical provider env values have been configured.
- The city table uses an explicit database URL.
- before hooks block over-quota users.
- after hooks record usage and error clues.
## Multi-city setup
- `bureau_id` clearly separates cities.
- Usage records include `bureau_id`, `user_id`, and `model`.
- Different cities have default quota strategies.
## Rollback
- Provider keys can be rotated quickly.
- Model definitions can be paused or replaced quickly through code deployment.
- Service errors are captured by `onError` or your logging system.
### Deploy to Cloudflare Workers
Source: https://downcity.ai/en/city-sdk-docs/operations/deploy-cloudflare-workers/
This page is the operational path for deploying a Federation project to Cloudflare Workers.
If you only want to understand how Federation is wired to Workers, read [Cloudflare Workers](/en/city-sdk-docs/guides/cloudflare-workers) first. This page focuses on production steps: `federation.toml`, local project creation, local deploys, D1 / Queue / R2, interactive administrator setup, env setup, OAuth callbacks, and health checks.
## PostgreSQL and Supabase
Workers can keep Queues and R2 while connecting to managed PostgreSQL through Hyperdrive. Use `@downcity/database-postgresql`; existing Federation Accounts, Credits, Payment and AI services remain in place. Supabase Auth and Storage are not required.
Configure Hyperdrive's Supabase origin with the project's Direct endpoint. Hyperdrive pools upstream connections; disable query caching for authorization and financial queries. Local migration tools connecting independently to Supabase may still use the Session pooler. Store connection credentials in secrets or local environment variables.
When using `@downcity/database-postgresql` through Hyperdrive, set `prepare_statements: true` so postgres-js uses the prepared statement protocol; Cloudflare's postgres-js integration prohibits `prepare: false`. The adapter forces `prepare: true` for `unsafe` queries and carries this behavior into `begin` transactions and `savepoint` clients, overriding Drizzle's explicit `prepare: false`.
Create a separate PostgreSQL client and Federation container for each Worker invocation, with at most one client connection. Never reuse sockets across invocations. For HTTP streaming responses, dispose the client after completion or cancellation and after that invocation's registered background work has finished. Queue batches and scheduled handlers dispose their own containers in `finally` blocks.
For a guarded cutover, the official Worker accepts `DOWNCITY_MAINTENANCE="true"`. It allows only GET health, discovery, JWKS and login provider catalog requests. Other requests return retryable 503 responses; scheduled work is skipped and queue messages are retried without acknowledgement. Pause queue delivery during maintenance, then disable the guard and resume delivery after verification. Never acknowledge an unprocessed payment webhook as successful.
For a D1 migration, preserve all source tables, including historical tables. Pause every writer, queue consumer and scheduled processor before taking a consistent export. Run `prepare_schema()` on empty PostgreSQL to create structures only; import and verify the original identities, keys, accounts and ledgers before `prepare_database()` establishes constraints and runtime readiness. Never publish a production entry pointing to an empty target.
Archive snapshots and per-table content hashes verify preservation. PostgreSQL hashes the original UTF-8 archive payloads and aggregates per-table counts, sorted SHA-256 digests and required ledger-order digests; only summaries cross the network. Duplicate rows still participate in both counts and hashes. Archives do not replace usable application tables. Once writes switch to PostgreSQL, rollback requires reconciliation and transferring new writes back.
## Prerequisites
- A Cloudflare account
- Dependencies installed in the project
Downcity does not deploy Workers automatically after `git push`. Deployment is explicit:
```bash
fed deploy
```
## 1. Create a Federation project
Developers normally start from an empty directory:
```bash
mkdir my-city
cd my-city
fed create --path . --template cloudflare-workers
```
`fed create --path . --template cloudflare-workers` asks for the Federation name and generates the Worker project skeleton:
- `federation.toml`
- `src/index.ts`
- `package.json`
- `tsconfig.json`
The generated `federation.toml` stores project information and deployment intent. Federation project configuration uses TOML only; JSON configuration is not supported:
```toml
schema = 1
type = "federation"
id = "fed_example"
name = "my-city"
entry = "src/index.ts"
[deployment]
target = "cloudflare-workers"
[deployment.resources.d1]
type = "d1"
binding = "DB"
name = "my-city-db"
[deployment.resources.queue]
type = "queue"
binding = "DOWNCITY_QUEUE"
name = "my-city-queue"
[deployment.resources.storage]
type = "r2"
binding = "DOWNCITY_STORAGE"
name = "my-city-storage"
public_url_prefix = "https://images.example.com"
```
`id` is the path-independent Fed identity, and `deployment.target` declares where it deploys. `entry` and `deployment.resources` are commit-safe deployment intent; D1 ids, account state, Worker URLs, and Wrangler config are handled by `fed deploy`.
If the City template already lives in a Git repository, use `fed create` to bring it local first:
```bash
fed create --path my-city --template https://github.com/example/my-city.git
cd my-city
```
`fed deploy` does not deploy remote URLs directly. It only deploys local Federation projects, so `.env` and deploy results have a clear project owner.
## 2. Deploy the current directory
Inside the Federation project directory:
```bash
fed deploy
```
When `federation.toml` sets `target = "cloudflare-workers"` in `[deployment]`, `fed deploy` checks Cloudflare auth automatically. Account state is stored in the system-level Federation registry and reused by later deploys.
`fed create` and `fed deploy` default to `--path .`. Use `--path ` for another local directory; positional path arguments are not accepted:
```bash
fed deploy --path ./my-city
```
For a local target, omitting `deployment.port` uses the fixed default port `12314`. Set `port` in `[deployment]` to override it. If the selected port is occupied, an interactive terminal shows the listener PID, start time, command, working directory, and whether it belongs to the current project, then asks whether to stop it and continue (default: No). After confirmation, the CLI rechecks process identity, sends `SIGTERM`, and waits up to 5 seconds for the port to become available, without escalating to a forced kill. Deployment fails in non-interactive terminals, when process identity cannot be verified, or when the port remains unavailable. `--yes` does not bypass this confirmation. Process inspection requires `lsof` and `ps`. The CLI does not scan for another port or infer one from deployment history.
## 3. Resource Config
Cloudflare Workers currently supports three resource declarations:
```toml
[deployment]
target = "cloudflare-workers"
[deployment.resources.d1]
type = "d1"
binding = "DB"
name = "my-city-db"
[deployment.resources.queue]
type = "queue"
binding = "DOWNCITY_QUEUE"
name = "my-city-queue"
[deployment.resources.storage]
type = "r2"
binding = "DOWNCITY_STORAGE"
name = "my-city-storage"
public_url_prefix = "https://images.example.com"
```
If D1 / Queue are omitted, `fed deploy` uses `${name}-db` and `${name}-queue`. Storage is enabled only when `deployment.resources.storage` exists.
During deployment, `fed deploy` reuses same-name D1 databases, Queues, and R2 buckets. If a declared resource is missing and this is not `--dry-run`, it creates the resource automatically. The D1 database id is Cloudflare deploy state and is not written back to project config.
Set `dead_letter_queue = "my-city-dead-letter"` and `max_retries = 10` under `[deployment.resources.queue]` to pass them to the Wrangler consumer. The dead-letter queue name must be a non-empty string, and the queue must already exist; the CLI does not create it. `max_retries` accepts an integer from 0 to 100; 0 disables retries after the first failed attempt, and omission uses Cloudflare's default. When a dead-letter queue is configured, messages that exhaust their retries are moved to that queue.
Cloudflare account is not part of the Federation project config. `fed deploy` reuses Wrangler login first; only when Cloudflare cannot resolve the account automatically does the CLI prompt once and save it into local fed CLI state.
You can also pass the account id for one deploy:
```bash
fed deploy --account-id
```
## 4. Dry-run
Before publishing, check the bundle and Wrangler config:
```bash
fed deploy --dry-run
```
For another directory:
```bash
fed deploy --path ./my-city --dry-run
```
## 5. Deploy flow
`fed deploy` runs these steps:
- reads `federation.toml` from the target directory
- checks the target platform identity from `deployment.target` in `federation.toml`; Cloudflare Workers opens Wrangler login or guides account selection when needed
- if this is not `--dry-run`, automatically bumps `package.json.version` by one patch version before deployment
- runs `pnpm build` if package.json has a `build` script
- runs `pnpm typecheck` if package.json has a `typecheck` script
- prepares D1 by looking up `deployment.resources.d1.name`, and creates it automatically when missing
- prepares Queue by looking up `deployment.resources.queue.name`, and creates it automatically when missing
- if `deployment.resources.storage` is declared, prepares the corresponding R2 bucket and creates it automatically when missing
- generates Wrangler config temporarily instead of writing it into the project directory
- builds and loads the Worker's `prepare_database(env)` export, using the project's Wrangler `getPlatformProxy` to connect D1 to the exact remote database; schema, bootstrap, and service preparation must succeed before upload
- interactively asks for administrator credentials on first initialization or when `--admin-reset` is used, then writes the password digest through deployment-authorized D1 access
- runs `wrangler deploy --config `
- requests Worker `/health` to check runtime readiness and verifies `/v1/admin/login` when new credentials were applied
- registers the Worker URL, deploy state, administrator ID, and time-limited Session Token in the local Federation registry
- requests Worker `/health` when `--verify` is passed
Deploy output is grouped by stage: `Project`, `Version`, `Build`, `Typecheck`, `D1 Database`, `Queue`, `Storage`, `Wrangler`, `Deployment`, and `Federation Registry`.
Fed has no global active/default Federation and does not store `active_server_url`. A deployed instance appears in the list without a global-current star marker. Use mutually exclusive, exact-match `--id ` or `--name ` for instance commands such as `fed status --id fed_example`, `fed manage --id fed_example`, or `fed web --id fed_example`. Without a selector, a TTY prompts for this operation only and non-interactive execution fails. Duplicate names prompt in a TTY and fail outside one.
`status` shows the registry record and a live health probe for any saved connection, plus separate launchd/systemd manager status for local instances. These are independent facts. `logs`, `stop`, and `restart` only support managed local instances, not Worker process control or remote logs. Local restart uses only the installed release and persisted runtime configuration, without reading or rebuilding source, and works after the original project is deleted. An explicitly selected database keeps its absolute path. Local `logs` reads the existing `service.log`; `stop` disables automatic startup and stops the service. It remains stopped across system restarts until an explicit deploy/restart. See [Independent Local Node Releases](/en/city-sdk-docs/packages/cli/quickstart#independent-local-node-releases). Remove connection only removes the saved connection; it does not stop the service.
`[deployment.process]` applies only to `local`; declaring it for Cloudflare Workers is an error. Local launchd/systemd policies default to `auto_start = false` and `restart_on_failure = true`. See [CLI Quickstart](/en/city-sdk-docs/packages/cli/quickstart) for configuration, recovery limits, and user manager requirements.
`federation.toml` stays as the commit-safe project declaration. Business secrets, provider keys, and service env should be written into Federation's own env table instead of `federation.toml`.
`fed deploy --dry-run` and `fed deploy --verify-only` do not change the project version.
### Worker database preparation entry
Provide a named export. Share service registration with the request runtime, while creating a fresh instance for preparation:
```ts
function create_federation(env: Env): Federation {
const fed = new Federation({
database: new Database({ binding: env.DB }),
database_initialization: "prepared",
});
// Register the same services used by the request runtime here.
return fed;
}
export async function prepare_database(env: Env): Promise {
const fed = create_federation(env);
await fed.prepare_database();
}
```
The CLI loads the entry in a Node subprocess with the project's installed Wrangler, its esbuild, and project dependencies. Install a Wrangler version supporting remote D1 bindings. The entry and its imports must be loadable in Node; avoid Worker-only globals or database operations at module scope. The temporary bundle lives inside the project and is removed on completion or failure; the proxy is always disposed. Local `.env` files are excluded from the preparation proxy. D1 uses the generated configuration's exact database ID and `remote = true`; Queue/R2 remain local proxies. Preparation should only perform database work.
`--dry-run` builds, loads, and checks the export without calling it or opening a remote D1 proxy. `--verify-only` skips preparation. `--skip-build` still prepares the database. Projects overriding `deployment.scripts.deploy` must arrange preparation themselves. Existing projects without the export fail deployment and must update their Worker and installed SDK packages. Run `maintenance()` periodically rather than on each cold start.
Preparation and administrator writes happen before upload and are not rolled back if upload fails; `--admin-reset` may already have revoked old administrator sessions. Historical SQL migration files are not automatically scanned or applied.
## 6. Developer edge starter
The Downcity repository keeps `templates/edgefed` as a developer-friendly starter project:
```bash
fed deploy --path templates/edgefed --verify
```
This starter is useful for local experiments and custom deployments. Downcity's private official production Worker implementation lives outside the public repository.
## 7. Initialize Federation
Call `/health` once after deployment. This lets the Worker boot Federation and create the built-in `env` / `cities` tables.
```bash
curl https://my-city..workers.dev/health
```
Expected shape:
```json
{
"ok": true,
"services": ["env", "cities", "bureaus"]
}
```
## 8. Administrator login
On the first `fed deploy`, Downcity asks for an administrator ID, password, and confirmation. Passwords must be at least 12 characters; only a PBKDF2 digest is stored in D1. To replace lost credentials, run `fed deploy --admin-reset`; this requires deployment authority, revokes all existing administrator sessions, and asks for new credentials. `--yes` confirms the destructive reset in non-interactive environments but does not skip credential prompts.
After deployment, `fed web`, the admin workspace, and `fed query` authenticate through `/v1/admin/login` and use a time-limited administrator Session Token. The browser never receives the remote Session Token; it remains in the local CLI BFF or registry.
## 9. Write provider and service env
Provider keys and service secrets should be written into the Federation env table instead of public clients.
Example:
```bash
curl -X POST https://my-city..workers.dev/v1/env/upsert \
-H "Authorization: Bearer " \
-H "Content-Type: application/json" \
-d '{"key":"DEEPSEEK_API_KEY","value":"sk-..."}'
```
Common keys:
| Key | Purpose |
| --- | --- |
| `DEEPSEEK_API_KEY` | Provider key used by the edge starter project |
| `STRIPE_SECRET_KEY` | Stripe API key for Checkout creation |
| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret |
| `DOWNCITY_CITY_BASE_URL` | Public City base URL used to derive payment result pages |
| `CREEM_API_KEY` | Creem API key for Checkout creation |
| `CREEM_PRODUCT_ID` | One-time, tax-inclusive Creem product used for hosted Checkout |
| `CREEM_CURRENCY` | Creem product currency; it must match the product's actual currency |
| `CREEM_WEBHOOK_SECRET` | Creem webhook signing secret; the provider is disabled when missing |
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | Optional Google OAuth login |
| `WECHAT_CLIENT_ID` / `WECHAT_CLIENT_SECRET` | Optional WeChat website login |
## 10. Configure OAuth callbacks
If you enable OAuth login, configure the provider callback URL to the deployed Worker:
```text
https://my-city..workers.dev/v1/accounts/oauth/callback
```
The callback domain must match the public domain users actually visit. If you later move to a custom domain, update the OAuth provider configuration as well.
## 11. Verify
If a Federation is already connected, run only the health check:
```bash
fed deploy --verify-only
```
You can also check manually:
```bash
curl https://my-city..workers.dev/
curl https://my-city..workers.dev/health
```
## Updating the deployment
After code changes:
```bash
fed deploy --verify
```
Runtime env lives in D1, so redeploying the Worker does not erase provider keys, OAuth secrets, cities, balances, usage records, or Stripe payment records.
### Deploy With Dokploy
Source: https://downcity.ai/en/city-sdk-docs/operations/deploy-dokploy/
`templates/localfed` defaults to local development. The Compose deployment disables Local Account so its credential-free local login cannot be exposed publicly, and stores SQLite data in a persistent `/data` volume.
## Dokploy Settings
Create an app in Dokploy from this Git repository:
| Setting | Value |
| --- | --- |
| Deployment mode | Compose |
| Compose file | `./docker-compose.yml` |
| Container port | `43127` |
| Volume | Compose creates `downcity_infra_data` |
`HOST`, `PORT`, the database path, and the login mode are already defined in `docker-compose.yml`:
```txt
HOST=0.0.0.0
PORT=43127
DATABASE_PATH=/data/downcity.sqlite
LOCAL_LOGIN=false
```
`/data` must stay persistent. Cities, accounts, and Federation env entries are stored in that SQLite database.
## Domain Path
The Node block listens on `43127`, and the Federation API is mounted at the service root:
```txt
GET /health
POST /v1/env/upsert
GET /v1/services
POST /v1/ai/stream
```
If your domain is `https://base.example.com`, product-side SDKs and trusted backends should use:
```txt
base_url=https://base.example.com
```
## Provider Keys
The `localfed` template reads `DEEPSEEK_API_KEY` directly from the process environment. Configure it as a Dokploy secret:
```txt
DEEPSEEK_API_KEY=sk-...
```
## Verify
After Dokploy finishes the deployment, verify the public service:
```bash
curl https://base.example.com/health
```
When using an IP and port:
```bash
curl http://1.2.3.4:43127/health
```
Expected shape:
```json
{
"ok": true,
"services": ["env", "cities", "bureaus", "accounts", "ai"]
}
```
If the request times out, the Dokploy service is not exposed publicly, the VPS firewall does not allow `43127`, or a reachable domain has not been bound yet.
## Call From Embassy
Product frontends and apps call Federation through Embassy:
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: "https://base.example.com",
user_token: "user_token",
});
```
Trusted backends use the Embassy Admin domain with an administrator session token:
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: "https://base.example.com",
admin_token: administrator_session_token,
});
```
See [Embassy User](/en/city-sdk-docs/reference/city-user) and [Embassy Admin](/en/city-sdk-docs/reference/city-admin) for the full SDK surface.
### Environment and Key Rotation
Source: https://downcity.ai/en/city-sdk-docs/operations/env-rotation/
The main benefit of managing keys in the Federation is that many products do not need separate config updates.
## provider keys
Provider keys can be managed through Runtime env and saved into the Federation database:
```ts
await admin.env.upsert({
key: "OPENAI_API_KEY",
value: "sk_new",
});
```
After rotation, every service handler connected to this runtime reads the new value. Env values in the database take priority over `.env`.
## Downcity's own keys
Downcity maintains two critical keys of its own:
- `DOWNCITY_FEDERATION_TOKEN_SIGNING_KEY`
### admin secret
`Embassy Admin` uses a time-limited administrator session token obtained from `/v1/admin/login`.
### token signing key
`DOWNCITY_FEDERATION_TOKEN_SIGNING_KEY` is used internally by Federation to issue and validate `user_token`.
## What to watch during rotation
- Rotating a provider key usually does not affect existing `user_token`
- Rotating `DOWNCITY_FEDERATION_TOKEN_SIGNING_KEY` invalidates old tokens
- If you rotate the signing key in production, shorten token TTL ahead of time or schedule a clear cutover window
## Recommendations
- assign an internal owner for every provider key
- record key rotation time
- put production key rotation in a trusted backend or ops workflow instead of relying on manual browser actions
### Logging and Usage
Source: https://downcity.ai/en/city-sdk-docs/operations/logging-and-usage/
Downcity does not decide where your logs live, but hooks give you one consistent integration point.
## Recommended fields
- user_id
- bureau_id
- model
- started_at
- ended_at
- status
- error
## Where to record
```ts
ai.hook.after(async (ctx) => {
await logService.write({
user_id: ctx.user?.user_id,
bureau_id: ctx.bureau?.bureau_id,
model: ctx.variant?.id,
model_meta: ctx.variant?.meta,
started_at: ctx.started_at,
ended_at: ctx.ended_at,
});
});
```
Once many products share one runtime, usage data becomes centralized by default, which makes cost analysis and business decisions much easier later.
### Troubleshooting
Source: https://downcity.ai/en/city-sdk-docs/operations/troubleshooting/
## client returns 401
Check:
- whether the request includes `Authorization: Bearer `
- whether the token has expired
- whether City has `DOWNCITY_FEDERATION_TOKEN_SIGNING_KEY` configured
- whether the token was issued by the current Federation
- whether the Token's `bureau_id` belongs to the current product
## client returns 403
Check:
- whether the Bureau bound to the token has been paused
- whether the target Bureau was `active` when the admin side issued the token
## client returns 404
Check:
- whether the HTTP route is correct
- whether the target service has been registered in City
- whether the target Bureau existed when the admin side issued the token
## model not found or handler not hit
Check:
- whether the client-provided `model` has been registered through `AIChannel.model()` + `AIService.use()`
- whether the target model includes the required action for the current pathway, such as `text`, `stream`, or `image`
- whether the request included the intended model id
- whether `city.ai.catalog()` can see the model
These cases usually return `422`.
## Federation returns a framework error
Use the response's server-generated `x-request-id` to correlate `error.request_id` and framework diagnostics. POST Actions require a JSON object by default: malformed JSON returns `400 INVALID_JSON`, non-object JSON returns `400 INVALID_INPUT`, and body read failures return `400 INVALID_BODY`. Empty or whitespace-only input becomes `{}`.
An explicit integer `statusCode` in 400–599 preserves a `code` matching `^[A-Za-z][A-Za-z0-9_]{0,63}$`, including `503 async_dispatch_unavailable`. Without a valid status, the result is always `500 INTERNAL_ERROR`. Explicit 4xx `httpError` messages are preserved. Every 5xx hides the original message: 503 is `Service temporarily unavailable`, 504 is `Request timed out`, and other 5xx statuses use `Internal server error`.
Framework 5xx logs contain only `event`, `request_id`, `status`, and `code`. They do not record bodies, tokens, original Errors, or stacks, and do not provide a complete access log. Do not rely on original stack retention. If you add an `onError` hook, keep its diagnostics controlled; a hook failure does not replace the original error.
Error Responses returned directly by business or native handlers retain their own bodies; the boundary still overwrites `x-request-id`. After a stream starts, boundary timeout or cancellation aborts downstream work, cancels the reader, and ends the stream without changing the HTTP status, returning JSON, or synthesizing generic SSE error frames. See [HTTP API](/en/city-sdk-docs/reference/http-api#framework-errors) for the full contract.
## HTTP body rejected or request timed out
Record `x-request-id` and `error.request_id` first. IDs are generated at the HTTP boundary before middleware, cover middleware short circuits and 413, 408, 504 responses, and are shared by the Router and AI relay. This response header contract applies to ordinary HTTP; HTTP 101 upgrades are neither rewrapped nor managed, and their `x-request-id` response header is not guaranteed.
| Status and code | What to check |
| --- | --- |
| `400 INVALID_CONTENT_LENGTH` | The declared length must be a non-negative decimal integer; fix the caller's header |
| `415 UNSUPPORTED_CONTENT_ENCODING` | Omit `Content-Encoding` or use `identity` |
| `413 BODY_TOO_LARGE` | Count actual body bytes, including JSON / Base64 wrapping; missing or falsely small lengths cannot bypass the limit |
| `408 REQUEST_BODY_TIMEOUT` | Check upload speed and total body read time; sending chunks does not extend the deadline |
| `504 REQUEST_TIMEOUT` | Check middleware, handlers, and upstream time after the body finishes reading, including shorter Adapter deadlines |
| `499 REQUEST_CANCELLED` | Check caller cancellation or disconnection; a disconnected client may not receive a response |
| `504 MODEL_FIRST_OUTPUT_TIMEOUT` | Default 120-second cumulative budget exhausted; check provider open and actual read waits before useful output |
| `504 MODEL_IDLE_TIMEOUT` | No new useful output within the default 120 seconds of cumulative read waits; metadata, empty deltas, and usage do not renew the budget |
| `504 MODEL_EXECUTION_TIMEOUT` | Default 15-minute wall-clock deadline from provider execution exhausted, including consumer backpressure |
Ordinary requests default to 1 MiB / 15 seconds to read / 30 seconds to execute. `/v1/payment/webhook` uses 2 MiB / 15 seconds / 30 seconds. `/v1/ai/stream`, `/v1/ai/chat/completions`, `/v1/chat/completions`, and media endpoints (`image/create`, `asr`, `tts`, `embedding`, `rerank`, `video`, `audio`, `decision` under `/v1/ai/`) use 40 MiB / 60 seconds / 180 seconds. `/v1/ai/image/result` uses ordinary limits.
For non-SSE HTTP responses, the timer runs from the end of request body reading until the response body finishes reading or is cancelled. Expiry before headers returns 504; after headers have been sent, it only ends the stream. Bodyless OPTIONS requests also use the ordinary deadline. The HTTP boundary waits up to 180 seconds for model and media response headers by default; the model policy can expire earlier. Synchronous JSON remains subject to the 180-second HTTP deadline. On receiving an SSE `Response`, the HTTP timer switches to the default 15-minute `stream_lifetime_ms`, measured from the end of request body reading and including the header wait, without buffering SSE. This clock is independent of the model total deadline measured from provider execution. Shorter provider deadlines still apply; whichever expires first applies. Once streaming starts, the HTTP boundary only aborts downstream work and cancels the reader to end the stream, without changing the status or synthesizing generic SSE error frames.
Native `/v1/ai/stream`, OpenAI SSE / JSON, and every Relay language model execution share server-side `AIServiceOptions.model_stream`. The 120-second first-output budget accumulates provider open and actual read waits; the 120-second idle budget accumulates actual read waits between useful outputs. Backpressure consumes neither budget, while the total wall clock keeps running. Clients cannot raise the policy through a request. `model_start`, `text_start`, `reasoning_start`, empty deltas, and usage do not renew the budget. Non-empty `text_delta` / `reasoning_delta`, `tool_call_start`, non-empty `tool_call_delta.input_delta`, and `tool_call_finish` count as useful output.
Model timeout before provider open returns throws 504. The Router preserves valid domain codes and hides the original message behind `Request timed out`. For an already-started native stream, inspect `model_error.error`: `code: "provider_timeout"`, `status_code: 504`, `retryable: false`, with `Model first output timed out`, `Model output stalled`, or `Model execution timed out`. If the provider has not emitted `model_start`, a framework `model_start` may precede the error solely for the failure terminal protocol. It does not prove useful output or fabricate usage. OpenAI SSE sends an error frame without a success `[DONE]` on failure; OpenAI JSON aggregation returns 504 on timeout. An in-stream 504 does not change the HTTP status already sent.
Model timeouts abort the same foreground execution without transparent retries. Completion or cancellation releases timers, listeners, and readers without waiting for an upstream cancel that could hang indefinitely. Trustworthy usage facts are retained; missing usage does not lead to estimated tokens or costs. Existing `bill` callbacks use actual facts, and business charging rules do not promise zero charges in every case without usage. `completion.outcome` distinguishes `succeeded`, `failed`, and `cancelled`. A cancel after the terminal event does not relabel the result as cancellation or timeout, or duplicate settlement or charges. See [Calling models](/en/city-sdk-docs/service/ai/calling#model-execution-deadlines) for configuration and the full contract.
Cancellation is cooperative: database operations may continue, transactions are not automatically rolled back, and no automatic retry is triggered. Queued image tasks do not inherit cancellation from foreground creation or result queries. After a query is interrupted, use the existing task ID to check status rather than creating a duplicate task. Adapters should combine the request signal with their own deadlines; shorter upstream deadlines still apply.
Servers can partially override category limits through `FederationOptions.http` and use `routes` for exact-path overrides; see [HTTP API](/en/city-sdk-docs/reference/http-api#http-boundary-and-default-limits). Edge / local-node link the SDK through workspace dependencies, so development builds use the default policy. Production deployment requires building the SDK and service artifacts containing the feature; running instances do not update automatically.
## provider call failed
Check:
- whether the matching key exists in City `.env`
- whether the handler reads the correct `input.env()` key
- whether model `meta` matches the current provider calling style
## File tools take a long time to finish
“生成文件内容中” means the model is still preparing file content; writing has not started. The received character count shows generation progress. “等待执行” means the input is ready, and “写入文件中” means writing has started.
If the model reaches its output limit or the response lacks a normal finish marker, the tool is not executed. Reduce the scope of each change, edit long documents by section, and save large SVG illustrations as separate files. If another interruption occurs, check the model service before repeating the same oversized request.
For `edit` input validation errors, correct the original call: `edits` must be an array, not a JSON-encoded string. Partial changes do not require rewriting the entire file.
## usage not recorded
Check:
- whether `AIService` and `CreditsService` are mounted before `UsageService` and supplied as its readers
- whether the AI provider returned final `RuntimeMetering`; executions without final metering only increase the execution count
- whether the Credits transaction is an applied positive charge; top-ups, failed, and pending transactions are excluded
- whether the query supplies real ordered `from` and `to` dates plus a valid IANA `timezone`
### Federation Client SDK
Source: https://downcity.ai/en/city-sdk-docs/reference/client-sdk/
The client API follows three explicit identities:
| API | Credential | Purpose |
| --- | --- | --- |
| `embassy.user` | User Token | Login, AI, payment, and user Services |
| `embassy.admin` | Admin Session Token | Federation administration |
| `Bureau` | Bureau Token | Trusted product backend and local User Token verification |
```ts
import { Bureau, Embassy } from "@downcity/federation";
const embassy = new Embassy({ federation_url });
const bureau = new Bureau({ federation_url, bureau_token });
```
Do not place User Tokens, Admin Session Tokens, and Bureau Tokens in one shared client object.
Their owners, lifetimes, and trust boundaries are different.
### Runtime API
Source: https://downcity.ai/en/city-sdk-docs/reference/runtime-api/
This page is kept as a lightweight overview. The new reading order is:
- [Reference home](/en/city-sdk-docs/reference): choose an entry by role first
- [Federation](/en/city-sdk-docs/reference/federation)
- [HTTP API](/en/city-sdk-docs/reference/http-api)
- [Environment variables](/en/city-sdk-docs/reference/env-vars)
## What Federation is responsible for
- initialize the Runtime database
- validate `user_token`
- expose a unified `/v1/*` HTTP route space
- register Service, AIService, and services through `base.use(service)`
- mount Service actions and service routes into the same `/v1/*` space
- connect usage, plans, balances, billing, logs, and risk control through hooks
Continue with [Federation](/en/city-sdk-docs/reference/federation) for concrete methods.
### Federation
Source: https://downcity.ai/en/city-sdk-docs/reference/federation/
`Federation` is the server-side core instance (formerly called "City runtime" in older docs). It encapsulates HTTP routing, auth, env vars, and database infrastructure. The client-side entry is [`City`](/en/city-sdk-docs/reference/city-user); do not confuse the two.
## Minimal Usage
```ts
import { Federation } from "@downcity/federation";
const base = new Federation({ database });
```
## Service Registration
```ts
import {
AIService,
AIChannel,
stream_openai_compatible_model,
type AIChannelStreamInput,
type AIChannelStreamResult,
} from "@downcity/federation";
class DeepSeekChannel extends AIChannel {
constructor() {
super({
id: "deepseek",
base_url: "https://api.deepseek.com",
env: { DEEPSEEK_API_KEY: "DeepSeek API Key" },
});
}
protected async stream(
input: AIChannelStreamInput,
): Promise {
const api_key = input.env("DEEPSEEK_API_KEY");
if (!api_key) throw new Error("DEEPSEEK_API_KEY is required");
return stream_openai_compatible_model(input, {
api_key,
base_url: this.base_url ?? "https://api.deepseek.com/v1",
});
}
}
const deepseek = new DeepSeekChannel();
const ai = new AIService();
ai.use(deepseek.model({ id: "deepseek-v4-flash", upstream_model: "deepseek-chat", name: "DeepSeek V4 Flash" }));
base.use(ai);
```
See [AIChannel & Model Registration](/en/city-sdk-docs/service/ai/provider).
## Official Service Registration
```ts
import { AccountsService, googleAccountsProvider } from "@downcity/services";
base.use(new AccountsService({
providers: [
googleAccountsProvider(),
],
}));
```
## Routing
```ts
import { serve } from "@hono/node-server";
serve({ fetch: (request) => base.fetch(request), port: 43127, hostname: "127.0.0.1" });
```
## HTTP Middleware
Use `base.middle()` to register Federation-level HTTP middleware before the internal router and Action JSON parsing. The HTTP boundary generates the request ID and completes bounded body reading before dispatching middleware. Oversized bodies and body timeouts never reach middleware or business handlers. Ordinary HTTP middleware short-circuit responses also receive the boundary's `x-request-id`, shared by the Router and AI relay. HTTP 101 upgrades are neither rewrapped nor managed, and their `x-request-id` response header is not guaranteed.
`FederationOptions.http` enables category-based body and execution limits by default. `ordinary`, `webhook`, `media`, and `model_stream` accept partial `max_body_bytes`, `body_timeout_ms`, and `execution_timeout_ms` values. `routes` overrides exact `path` values and those limits. For non-SSE responses, the execution timer stays active until the response body finishes reading or is cancelled; bodyless OPTIONS requests also use the ordinary deadline. Expiry before headers returns 504; after headers have been sent, it only ends the stream. On receiving an SSE `Response`, the timer switches to `stream_lifetime_ms`, defaulting to `900_000`, limiting the total time to 15 minutes measured from the end of request body reading, without buffering SSE. Model execution is also governed by server-side `AIServiceOptions.model_stream?: Partial`, defaulting to 120 seconds for first useful output, 120 seconds for idle, and 15 minutes total. First output accumulates provider open and actual read waits; idle accumulates actual read waits between useful outputs. Consumer backpressure consumes neither budget, while the total wall clock keeps running. Clients cannot raise these limits through a request. The model total clock starts at provider execution, independently of the HTTP SSE clock measured from the end of body reading. Shorter provider deadlines and the default 180-second synchronous HTTP deadline still apply; whichever expires first applies. See [Federation runtime](/en/city-sdk-docs/packages/federation/federation#http-policy-configuration) for defaults and configuration.
Native `/v1/ai/stream`, OpenAI-compatible SSE / JSON, and every Relay language model execution share that model policy. Timeouts abort the same foreground execution without transparent retries. Timeout during provider open throws a 504 domain error with a safe Router message. Once streaming starts, native transport emits `model_error` (`provider_timeout`, `status_code: 504`, `retryable: false`); OpenAI SSE sends an error frame without a success `[DONE]`, and JSON aggregation returns 504 on timeout. Streaming keeps the HTTP status already sent. See [Calling models](/en/city-sdk-docs/service/ai/calling#model-execution-deadlines) for useful output, terminal outcomes, and settlement rules.
Completion or cancellation releases timers, listeners, and readers without waiting for an upstream cancel that could hang indefinitely. Applications can add host policies such as CORS, security headers, and coarse rate limits through middleware. The execution deadline covers middleware. Handlers can read cancellation through `ServiceRouteContext.abort_signal`, Action `Context.abort_signal`, and the native `request.signal`. Adapters should combine the request signal with their own deadlines; shorter upstream deadlines still apply. Cancellation does not guarantee reversal of database operations or external side effects and does not trigger automatic retries.
```ts
base.middle(async (ctx, next) => {
const started_at = Date.now();
const response = await next();
const headers = new Headers(response.headers);
headers.set("X-Downcity-Time", String(Date.now() - started_at));
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
}));
```
Middleware enters in registration order and exits in reverse order. It can return a `Response` directly to short-circuit a request, or call `await next()` and then modify response headers.
## instruction aggregation
`Federation` can return a plain-text instruction document for the current instance:
```ts
const text = await base.instruction();
```
The text aggregates:
- how to use the Federation itself
- which services are currently mounted
- env requirements declared by each module
- extra usage notes contributed by services
To read the same document remotely from a trusted admin side, call:
```txt
GET /v1/base/instruction
```
This route is admin-only and returns `text/plain`.
## Auth
Federation automatically validates `user_token` and administrator session tokens. Access current user via `ctx.user`.
## Database
`ctx.db["table_name"]` provides CityTableApi. Supports SQLite and PostgreSQL.
### Embassy User
Source: https://downcity.ai/en/city-sdk-docs/reference/city-user/
Create an Embassy with only the Federation URL, then use its `user` identity domain.
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({ federation_url: "https://fed.example.com" });
const providers = await embassy.user.account.providers();
```
## Account
```ts
await embassy.user.account.login({
provider: "email",
client_type: "cli",
bureau_id: "product-web",
input: { email: "user@example.com", password: "password" },
});
const current_user = await embassy.user.current();
const user_token = embassy.user.account.token();
await embassy.user.account.logout();
```
`bureau_id` belongs to the login request, not the Embassy constructor. A successful login updates
the User Token held by this instance. You may also provide an existing `user_token` when creating
the Embassy. Email login requires completed email verification. `login()` automatically exchanges the completed flow for a token; `status()` alone never delivers one. Logout revokes the current token before clearing local credentials and preserves it on failure for retry. New protected Bureau requests require online Federation validation; unavailable validation rejects access, while existing streams continue.
## Services
```ts
const models = await embassy.user.ai.catalog();
const methods = await embassy.user.payment.methods();
const services = await embassy.user.list_services();
const result = await embassy.user.service("rewrite")
.action("formal")
.invoke({ text: "hello" });
```
`embassy.user.get()` and `post()` target the trusted Bureau server resolved by Federation from the
current User Token. Embassy rejects forwarding that token to another origin.
### Embassy Admin
Source: https://downcity.ai/en/city-sdk-docs/reference/city-admin/
Administrator access is the `admin` identity domain of Embassy.
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({ federation_url: "https://fed.example.com" });
await embassy.admin.login({ admin_id: "owner", password: "password" });
```
The Federation returns a time-limited Admin Session Token. Embassy keeps it in the current
instance; `token()` reads it and `logout()` revokes it.
## Bureau management
```ts
const bureaus = await embassy.admin.bureaus.list();
const bureau = await embassy.admin.bureaus.create({
bureau_id: "product-web",
name: "Product Web",
server_url: "https://product.example.com",
});
await embassy.admin.bureaus.route.update({
bureau_id: bureau.bureau_id,
server_url: "https://new-product.example.com",
});
```
## Bureau Tokens
```ts
const issued = await embassy.admin.bureaus.tokens.issue({
bureau_id: "product-web",
purpose: "production backend",
});
const tokens = await embassy.admin.bureaus.tokens.list("product-web");
await embassy.admin.bureaus.tokens.revoke(issued.token_id);
```
Federation returns the plaintext Bureau Token only when it is issued. Store it in the trusted
backend and use the independent `Bureau` client for `identify()`; Embassy Admin does not identify
end-user requests.
### HTTP API
Source: https://downcity.ai/en/city-sdk-docs/reference/http-api/
All actions are exposed through the same shape:
```txt
POST /v1/{service}/{action}
GET /v1/{service}/{action}
```
The bearer credential decides the request identity:
- no token: `guest`
- `user_token`: `user`
- administrator session token: `admin`
Each action declares which identities it allows. The default is `["user"]`; `[]` means guest access is allowed.
## City Routes (common user-side routes)
| Route | Method | Purpose | Pathway |
| --- | --- | --- | --- |
| `/v1/ai/models` | `GET` | Model catalog | — |
| `/v1/ai/stream` | `POST` | Downcity Model Protocol stream transport | CityModel |
| `/v1/ai/image/create` | `POST` | Create image generation job | SDK |
| `/v1/ai/image/result` | `POST` | Poll image generation job | SDK |
| `/v1/ai/video` | `POST` | Video generation | SDK |
| `/v1/ai/tts` | `POST` | Text-to-speech | SDK |
| `/v1/ai/asr` | `POST` | Speech recognition | SDK |
| `/v1/ai/decision` | `POST` | Structured decision (System One) | SDK |
| `/v1/ai/chat/completions` | `POST` | OpenAI-compatible endpoint | OpenAI |
| `/v1/accounts/login/start` | `POST` | Specify `client_type`; receive `login_id`, `login_secret`, and the next step | — |
| `/v1/accounts/login/continue` | `POST` | Submit input with `login_id` and `login_secret` | — |
| `/v1/accounts/login/result` | `POST` | Query status with the claim proof; never returns a token | — |
| `/v1/accounts/login/exchange` | `POST` | Exchange the claim proof and stable `exchange_id` for `user_token` | — |
| `/v1/accounts/logout` | `POST` | Revoke the current Bearer User Token | — |
| `/v1/federation/token` | `GET` | Validate the current Bearer User Token online | — |
| `/v1/accounts/me` | `GET` | Read the current user and its verified Bureau | — |
| `/v1/accounts/oauth/callback` | `GET` | Third-party OAuth callback entry | — |
| `/v1/services` | `GET` | Registered service list | — |
| `/v1/{service}/{action}` | `POST` | Generic action call | — |
`/v1/accounts/oauth/callback` is the fixed return URL for GitHub, Google, and other third-party OAuth providers. Product clients usually do not call it directly.
Keep `login_secret` exclusively in the initiating product and send it in JSON request bodies, never URLs, pages, or logs. OAuth start requires `client_type: "web" | "cli" | "desktop"`, `redirect_uri`, a random `state`, `code_challenge`, and `code_challenge_method: "S256"`. Website callbacks must exactly match the registered Bureau `server.server_url` with `/api/auth/callback` appended; the BFF binds the initiating browser with a short-lived HttpOnly cookie. CLI/Desktop use a canonical `http://127.0.0.1:/` and the local system browser. Provider authentication returns directly to the product. Validate callback state, then exchange the received `authorization_code`, private `code_verifier`, `login_id`, `login_secret`, and random `exchange_id`. Status stays pending until exchange and never delivers a token. Reuse the same `exchange_id` and proof on transport retries within 60 seconds. Remote/headless CLI OAuth sign-in is unsupported.
Bureau checks new protected requests online with Federation and rejects access when validation is unavailable. Logout revokes the current token; streams already running are not forcibly interrupted.
## Admin Routes (same route space, admin credential required)
| Route | Method | Purpose |
| --- | --- | --- |
| `/v1/bureaus/list` | `GET` | List Bureaus |
| `/v1/bureaus/create` | `POST` | Create a Bureau with required `server_url` |
| `/v1/bureaus/pause` | `POST` | Pause a Bureau |
| `/v1/bureaus/activate` | `POST` | Activate a Bureau |
| `/v1/bureaus/archive` | `POST` | Archive a Bureau |
| `/v1/bureaus/server/update` | `POST` | Update the Bureau's single Server entrypoint |
| `/v1/bureaus/current` | `GET` | Resolve the current Bureau from a User Token |
| `/v1/accounts/tokens/issue` | `POST` | Issue user_token |
| `/v1/env/list` | `GET` | View runtime env |
| `/v1/env/upsert` | `POST` | Write env variable |
| `/v1/env/remove` | `POST` | Delete env variable |
| `/v1/env/import` | `POST` | Bulk import .env |
## Auth Header
```http
Authorization: Bearer
Content-Type: application/json
```
## Action request bodies
POST Actions default to `body: "json"`. An empty or whitespace-only body becomes `{}`; any non-empty body must be a JSON object. GET Actions read input from query parameters.
| Input failure | HTTP status | code |
| --- | --- | --- |
| Invalid JSON syntax | 400 | `INVALID_JSON` |
| A JSON array, `null`, string, number, or boolean | 400 | `INVALID_INPUT` |
| Request body cannot be read | 400 | `INVALID_BODY` |
Webhook Actions can explicitly select `body: "raw"`. The Action Context's `raw_body` and an Installable Action's `ctx.text()` preserve the original text. The latter's `ctx.json()` still requires a JSON object when called, with empty or whitespace-only input becoming `{}`. `Service.action()` accepts optional `options.body`; Installable `ctx.route()` accepts optional `body` only for Action routes. See [Service and Action](/en/city-sdk-docs/packages/federation/service-and-action).
Native `handler: { request }` route bodies also undergo one bounded read at the HTTP boundary. The Request is then rebuilt from the original bytes without Action JSON parsing. OAuth form submissions, callbacks, and redirects use their native protocols.
## HTTP boundary and default limits
`Federation.fetch()` enables bounded body reading before middleware and the Router by default. The following policies match exact paths; 1 MiB is 1,048,576 bytes.
| Category | Exact paths | `max_body_bytes` | `body_timeout_ms` | `execution_timeout_ms` |
| --- | --- | --- | --- | --- |
| `ordinary` | All other paths, including `/v1/ai/image/result` | 1,048,576 (1 MiB) | 15,000 | 30,000 |
| `webhook` | `/v1/payment/webhook` | 2,097,152 (2 MiB) | 15,000 | 30,000 |
| `model_stream` | `/v1/ai/stream` | 41,943,040 (40 MiB) | 60,000 | 180,000 |
| `media` | `/v1/chat/completions`, `/v1/ai/chat/completions`, and `image/create`, `asr`, `tts`, `embedding`, `rerank`, `video`, `audio`, `decision` under `/v1/ai/` | 41,943,040 (40 MiB) | 60,000 | 180,000 |
The boundary adds up the actual `byteLength` of each `Uint8Array` chunk, including JSON, Base64, and other wrapping bytes. Missing `Content-Length`, chunked transfer, or a falsely small declared length cannot bypass the limit. A declared length over the limit can be rejected early. The body deadline covers the entire read and does not reset on new chunks. `Content-Encoding` must be absent or `identity`; other encodings are not decompressed.
| HTTP boundary failure | HTTP status | code |
| --- | --- | --- |
| Invalid `Content-Length`, not a non-negative decimal integer | 400 | `INVALID_CONTENT_LENGTH` |
| Unreadable body or a chunk that is not a `Uint8Array` | 400 | `INVALID_BODY` |
| Body read deadline reached | 408 | `REQUEST_BODY_TIMEOUT` |
| Declared length or actual body exceeds the limit | 413 | `BODY_TOO_LARGE` |
| Unsupported `Content-Encoding` | 415 | `UNSUPPORTED_CONTENT_ENCODING` |
| Client cancellation | 499 | `REQUEST_CANCELLED` |
| Execution deadline reached before the response starts | 504 | `REQUEST_TIMEOUT` |
The execution deadline starts when the request body has been fully read and covers middleware and business handling. For non-SSE responses, the timer stays active until the response body finishes reading or is cancelled. Expiry before headers returns `504 REQUEST_TIMEOUT`; after headers have been sent, it only ends the stream without changing the HTTP status. Bodyless OPTIONS requests also use the ordinary execution deadline. Model and media endpoints wait up to 180 seconds for response headers by default; this is not a first useful output deadline.
On receiving an SSE `Response`, the HTTP timer switches to the `stream_lifetime_ms` total deadline, defaulting to `900_000` (15 minutes). It is measured from the end of request body reading and includes the wait for response headers, without buffering SSE. The model total deadline also defaults to 15 minutes but starts at provider execution. These clocks are independent; whichever expires first applies. Synchronous JSON remains subject to the default 180-second HTTP execution deadline, and shorter provider deadlines still apply.
After headers have been sent, the HTTP boundary does not change the status or synthesize generic SSE error frames. Cancellation or timeout aborts downstream work, cancels the reader, and ends the stream. Completion or cancellation releases timers, listeners, and readers without waiting for an upstream cancel that could hang indefinitely.
### Language model deadlines and errors
Native `/v1/ai/stream`, OpenAI-compatible SSE and JSON, and every Relay language model execution share the server-side `AIServiceOptions.model_stream?: Partial`: `first_output_timeout_ms: 120_000`, `idle_timeout_ms: 120_000`, and `total_timeout_ms: 900_000`. Clients cannot raise these limits through a request. The first-output budget accumulates provider open and actual read waits before useful output; idle accumulates actual read waits between useful outputs. Backpressure does not consume either budget, while total wall-clock timing continues. See [Calling models](/en/city-sdk-docs/service/ai/calling#model-execution-deadlines) for useful events and configuration examples.
| Model deadline | Domain code when thrown before response start | Error message in an already-started native stream |
| --- | --- | --- |
| First useful output | `MODEL_FIRST_OUTPUT_TIMEOUT` | `Model first output timed out` |
| Stalled output | `MODEL_IDLE_TIMEOUT` | `Model output stalled` |
| Total execution | `MODEL_EXECUTION_TIMEOUT` | `Model execution timed out` |
Timeout before provider open returns throws HTTP 504. The Router preserves valid domain codes and uses the safe message `Request timed out`. Model timeouts abort the same foreground execution without transparent retries. Once the native Response has started, the model transport emits `model_error` with `code: "provider_timeout"`, `status_code: 504`, `retryable: false`, and the message above. If the provider has not emitted `model_start`, a framework `model_start` may precede the error solely to satisfy the failure terminal protocol, without fabricating usage. OpenAI SSE sends an error frame without a success `[DONE]` on failure; OpenAI JSON aggregation returns 504 on timeout. An in-stream `status_code: 504` does not change the HTTP status already sent.
Trustworthy usage facts are retained. Missing usage does not lead to estimated tokens or costs. Existing `bill` callbacks use actual facts; business charging rules do not promise zero charges in every case without usage. `completion.outcome` distinguishes `succeeded`, `failed`, and `cancelled`. A cancel after the terminal event does not change the outcome or cause duplicate settlement or charges.
`499 REQUEST_CANCELLED` represents client cancellation; a disconnected client is not guaranteed to receive a response. Handlers can read Action `Context.abort_signal`, `ServiceRouteContext.abort_signal`, or the native `request.signal`. Adapters should combine the request signal with their own deadlines; shorter upstream deadlines still apply. Cancellation is cooperative: database operations may continue, transactions are not automatically rolled back, and no automatic retry is triggered. Queued image tasks run independently and do not inherit cancellation from foreground creation or result queries.
See [Federation runtime](/en/city-sdk-docs/packages/federation/federation#http-policy-configuration) for configuration and exact-path overrides. Edge / local-node link the SDK through workspace dependencies, so development builds use this default policy. Production deployment requires building the SDK and service artifacts containing the feature; running instances do not update automatically.
## Request IDs
Every request entering the `Federation.fetch()` HTTP boundary receives a server-generated `req_` before middleware runs. Caller-supplied request IDs are ignored. Boundary responses within the ordinary HTTP protocol overwrite `x-request-id`, including middleware short circuits, 413, 408, 504, success, business errors, native Responses, streams, and route 404s. The Router, Action Context's `request_id` and `locals.request_id`, and AI relay share the same ID. Responses handled by the host outside this boundary are outside this scope; HTTP 101 upgrades are neither rewrapped nor managed, and their `x-request-id` response header is not guaranteed.
## Framework errors
Errors thrown and caught by the framework use this JSON shape:
```json
{
"error": {
"code": "INVALID_JSON",
"message": "INVALID_JSON: Request body must be valid JSON",
"type": "invalid_request_error",
"request_id": "req_550e8400-e29b-41d4-a716-446655440000"
}
}
```
An explicit integer `statusCode` from 400 through 599 determines the HTTP status. With that valid status, a `code` matching `^[A-Za-z][A-Za-z0-9_]{0,63}$` is preserved, including domain codes such as `503 async_dispatch_unavailable`. Missing or invalid codes use the defaults below. Missing or invalid `statusCode` always becomes `500 INTERNAL_ERROR`, even when a code is present. `type` is determined by status.
| HTTP status | type | Default code |
| --- | --- | --- |
| 400 | `invalid_request_error` | `INVALID_REQUEST` |
| 401 | `authentication_error` | `UNAUTHENTICATED` |
| 403 | `permission_error` | `FORBIDDEN` |
| 404 | `not_found_error` | `NOT_FOUND` |
| 408 | `invalid_request_error` | `REQUEST_BODY_TIMEOUT` |
| 409 | `conflict_error` | `CONFLICT` |
| 413 | `invalid_request_error` | `BODY_TOO_LARGE` |
| 415 | `invalid_request_error` | `UNSUPPORTED_CONTENT_ENCODING` |
| 429 | `rate_limit_error` | `RATE_LIMITED` |
| 499 | `request_cancelled_error` | `REQUEST_CANCELLED` |
| Other 4xx | `invalid_request_error` | `REQUEST_REJECTED` |
| 503 | `server_error` | `SERVICE_UNAVAILABLE` |
| 504 | `server_error` | `REQUEST_TIMEOUT` |
| Other 5xx | `server_error` | `INTERNAL_ERROR` |
Explicit 4xx `httpError` messages are preserved. Every 5xx response, including errors with preserved domain codes, hides the original message: 503 uses `Service temporarily unavailable`, 504 uses `Request timed out`, and other 5xx statuses use `Internal server error`. Unknown Errors use the generic 500 response.
Business and native handlers own the error bodies of Responses they return directly. The framework does not normalize those bodies; it still overwrites `x-request-id`. Adding that header neither consumes the body nor buffers SSE. After streaming starts, boundary timeout or cancellation aborts downstream work and cancels the reader. The response cannot switch HTTP status or become a JSON error, and the boundary does not synthesize generic SSE error frames. An `onError` hook failure does not replace the original error.
Framework 5xx structured logs contain only `event`, `request_id`, `status`, and `code`. They exclude request/response bodies, tokens, the original Error, and stack traces. This is not a complete access log and does not retain original stacks.
## `GET /v1/ai/models`
The same route returns different visibility by identity:
- with `user_token`: only currently callable models
- with an administrator session token: the full code-registered model list plus `env_requirements`
```json
{ "items": [
{ "id": "deepseek-v4-flash", "name": "DeepSeek V4 Flash",
"description": "...", "modalities": ["text","stream"],
"tags": ["deepseek"],
"price": ["Input: 1 credit / 1K tokens", "Output: 3 credits / 1K tokens"],
"meta": {},
"reasoning": {
"efforts": [
{ "id": "low", "name": "Low" },
{ "id": "high", "name": "High" }
],
"default_effort": "low"
} }
]}
```
```json
{ "items": [
{ "id": "deepseek-v4-flash", "name": "DeepSeek V4 Flash",
"description": "", "modalities": ["text","stream","openai"],
"tags": ["deepseek"],
"price": ["Input: 1 credit / 1K tokens", "Output: 3 credits / 1K tokens"],
"meta": {},
"env_requirements": [
{ "key": "DEEPSEEK_API_KEY", "description": "deepseek API Key", "required": true }
] }
]}
```
Federation resolves both the user and Bureau identity from the bearer `user_token`. The request body
does not participate in identity resolution.
## `GET /v1/services`
```json
{
"items": [
{ "id": "ai", "name": "AI", "env": [] },
{ "id": "accounts", "name": "Accounts", "env": [] }
]
}
```
`env` exposes the runtime env requirements declared by the service so admin or debugging surfaces can render dependencies.
## `POST /v1/ai/stream`
This versioned Downcity Model Protocol transport accepts
`{ protocol_version: 1, model_id, call }`, where `call` is a `ModelCall` containing
messages, tools, reasoning, and generation options. SSE returns
`{ protocol_version: 1, event: ModelStreamEvent }`. Product code should use the
`CityModel` returned by the catalog or call `city.ai.stream({ model, call })`.
Both paths consume the same standard event stream.
When supplied, `call.reasoning.effort` must match the final model catalog's
`reasoning.efforts`. AIService validates it again after fallback selects the
execution model.
## `POST /v1/ai/decision`
Structured decision transport. Accepts
`{ model, state, questions }` where `state` is `{ type: "text", text }` or
`{ type: "json", data }`, and returns `{ answers, usage? }`. Each answer carries
`value`, an optional `probability`, and a `distribution` for choice questions.
Requests are validated before execution: question ids must be unique, choice
questions require 1 to 255 unique options, and `score` requires `min < max`.
Invalid input fails with 422 without recording usage.
Product code should call `city.ai.decision({ model, state, questions })`.
## `POST /v1/ai/chat/completions`
OpenAI-compatible endpoint. Accepts standard `{ model, messages, stream }` format.
Non-streaming returns OpenAI `chat.completion` JSON. Streaming returns OpenAI SSE.
Fully compatible with OpenAI SDK:
```ts
const openai = new OpenAI({
baseURL: "http://127.0.0.1:43127/v1/ai",
apiKey: "ub_xxx",
});
```
### Environment Variables
Source: https://downcity.ai/en/city-sdk-docs/reference/env-vars/
| Variable | Purpose |
| --- | --- |
| `DOWNCITY_FEDERATION_TOKEN_SIGNING_KEY` | Lets Federation issue and validate `user_token` internally |
| `DOWNCITY_CITY_DATABASE_URL` | Optional. Specifies the database URL used by Federation |
| `OPENAI_API_KEY` | Example provider key; recommended to write it into the Federation database through Admin env |
| `OPENAI_BASE_URL` | Example provider base URL; recommended to write it into the Federation database through Admin env |
`fed deploy` interactively provisions the administrator ID and password. The password is stored as a PBKDF2 digest and administrator sessions are stored server-side; there is no administrator key environment variable. `DOWNCITY_FEDERATION_TOKEN_SIGNING_KEY` and `BETTER_AUTH_SECRET` are generated automatically on first boot and stored in Federation's `env` table.
If `DOWNCITY_CITY_DATABASE_URL` is omitted, the default database path is:
```plaintext
.base/downcity.sqlite
```
## Official local-node configuration
These settings belong to the `private/services/local-node` host, whose default development port is `3000`. Use that service's `.env.example` to prepare project configuration. The development entry reads the project `.env`; standalone mode with `DOWNCITY_DATA_DIR` uses the CLI's persisted runtime snapshot.
| Variable | Default | Constraint |
| --- | --- | --- |
| `HOST` | `127.0.0.1` | Only `127.0.0.1`, `::1`, or `localhost`; no wildcard or public address |
| `PORT` | `3000` | Integer from 1 to 65535 |
| `PUBLIC_URL` | `http://localhost:${PORT}` | Canonical HTTP(S) loopback origin with the same effective port as `PORT`; falls back to `DOWNCITY_FEDERATION_BASE_URL` before the default |
| `DOWNCITY_LOCAL_ALLOWED_ORIGINS` | Empty | Comma-separated additional exact trusted HTTP(S) origins; no additional cross-origin pages by default |
| `DOWNCITY_FEDERATION_DATABASE_URL` | Unset | A `file:` SQLite URL, taking precedence over `DATABASE_PATH` |
| `DATABASE_PATH` | `./data/local.db` | SQLite file path; defaults to `data.sqlite` inside `DOWNCITY_DATA_DIR` when that directory is set |
Origins must have no trailing slash, path, query, fragment, credentials, or explicit default port. `*`, `null`, and inputs requiring URL normalization are rejected. Canonical origins using default ports 80/443 omit the port. Valid examples: `PUBLIC_URL=http://localhost:3000` and `DOWNCITY_LOCAL_ALLOWED_ORIGINS=http://localhost:5173,https://client.example.com`.
The node's `local` provider offers passwordless ordinary user login for a trusted local machine. Browser requests may come only from the target's own origin, `PUBLIC_URL`, or explicitly trusted origins. An allowed page may obtain local user access, so trust each entry explicitly. Normal CLI requests without `Origin` remain supported; cross-site Fetch Metadata cannot bypass origin checks. The allowlist grants no identity or administrator privileges. Administrator APIs require a real administrator Session, and users and Bureaus use their respective tokens. Startup writes upstream API keys into Federation's env table through an in-process trusted identity.
## How provider env is used
The model handler reads directly from `input.env`:
```ts
import {
AIChannel,
stream_openai_compatible_model,
type AIChannelStreamInput,
type AIChannelStreamResult,
} from "@downcity/federation";
class DeepSeekChannel extends AIChannel {
constructor() {
super({
id: "deepseek",
env: { DEEPSEEK_API_KEY: "DeepSeek API Key" },
base_url: "https://api.deepseek.com",
});
}
protected async stream(
input: AIChannelStreamInput,
): Promise {
const api_key = input.env("DEEPSEEK_API_KEY");
if (!api_key) throw new Error("DEEPSEEK_API_KEY is required");
return stream_openai_compatible_model(input, {
api_key,
base_url: this.base_url ?? "https://api.deepseek.com/v1",
});
}
}
const deepseek = new DeepSeekChannel();
```
So the practical rules are simple:
- you choose the env key names yourself
- uppercase snake case is recommended
- read values through `input.env(key)` inside `stream()`
## Write values into the database
A trusted backend can write provider keys through Embassy Admin:
```ts
await embassy.admin.env.upsert({
key: "DEEPSEEK_API_KEY",
value: "sk-xxx",
});
```
These values are stored in the `env` table inside the Federation database. Business runtime reads only from that Federation-managed env table and no longer falls back to `.env` or process environment variables.
See also [AIChannel environment variables](/en/city-sdk-docs/guides/provider-env).
### City SDK
Source: https://downcity.ai/zh/city-sdk-docs/
Downcity 的 City SDK 用来创建、部署和调用 City。一个 Federation 可以同时服务网页、扩展、App、桌面工具、客户 Demo 或内部工具,不需要每个 AI 产品都重搭一套 AI 后端。
City 对外暴露的不是 provider API,而是稳定的**产品调用边界**。在 City 内部,能力通过 `Service`、`Action` 和 `AIService` 组织:
- 产品侧拿到 `user_token`(其中包含 `bureau_id`)
- 用 `Embassy User` 调 `text()`、`stream()`、`image()` 这类 service
- City 内部自己决定模型目录、provider 路由、hooks、usage 和 env
服务端运行时的类叫 `Federation`(本文里也称 Federation),产品侧用 `City` 客户端去访问它。两者的边界见 [Federation 与 City](/zh/city-sdk-docs/concepts/federation)。
## 先选你的阅读入口
## 一张图看懂它怎么工作
多个产品 client
网页、扩展、App、桌面工具、客户 Demo、内部工具。
Embassy User + user_token (which contains bureau_id)
→
Federation
校验 token,读取模型目录,再把请求分发到 AIService、服务或自定义 Service 的 action。
hooks 与 usage
把套餐、余额、扣费、日志、风控接进 Federation,但业务规则仍然留在你自己的系统里。
→
上游调用层
OpenAI、Claude、Gemini、私有模型,或你自己的 AI Gateway / 中转服务。
对产品来说,City 暴露的是稳定的 Service action 和 model;上游接什么 provider、网关或私有部署,都是服务端内部细节。
## City SDK 负责什么
- Runtime 数据库和 Service 声明的表
- provider key 和 Runtime env
- `user_token` 校验与管理员会话管理能力
- `Provider` + `AIService.use()` 注册模型,自动提供 SDK 和 OpenAI 兼容两条通路
- `city.ai.catalog()` 读取 Runtime 注册出来的公开模型目录
- usage 记录和 hooks 扩展点
## 它不负责什么
- 你的用户系统
- 订单、订阅、CRM、内容数据
- 产品自己的页面、交互和业务体验
- 对外暴露“统一 provider API”给其他系统直接调用
更准确地说:
> City SDK 负责 Federation 以及其中面向 Service 的 AI 基础设施。
> 产品继续负责自己的用户、业务、界面和商业模式。
## 推荐阅读路线
1. 第一次接入,先去 [快速开始](/zh/city-sdk-docs/quickstart)
2. 想彻底理解这个产品模型,再看 [核心概念](/zh/city-sdk-docs/concepts)
3. 准备接真实业务,再看 [场景指南](/zh/city-sdk-docs/guides)
4. 想按 npm package 理清职责时,看 [Packages](/zh/city-sdk-docs/packages)
5. 需要具体接口时,再回到 [参考](/zh/city-sdk-docs/reference)
### Federation、Bureau、Embassy 与 City
Source: https://downcity.ai/zh/city-sdk-docs/concepts/federation/
四个概念拥有独立职责:
- `Federation` 是权威后端和信任根,拥有账户、Bureau 记录、Service、模型目录、Usage、
Env 和 Token 签发。
- `Bureau` 是 Federation 内的产品或业务分区。Bureau Token 表示可信产品后端身份。
- `Embassy` 是 user 与 admin 访问 Federation 的窗口,只有 `user` 和 `admin` 两个身份子域。
- `City` 是 `@downcity/city` 提供的应用组合根,持有 Workspace,也可以持有 Embassy 服务客户端;它不是 Federation
客户端,也不是 Federation 中需要注册的身份。
```ts
import { Embassy, Federation } from "@downcity/federation";
import { City } from "@downcity/city";
const federation = new Federation({ database });
const embassy = new Embassy({ federation_url: "https://fed.example.com" });
const city = new City({ embassy, workspaces: [workspace] });
const agent = new Agent({ id: "assistant" });
city.agents.add(agent);
```
## 身份边界
User Token、Admin Session Token 和 Bureau Token 不能混用:
- `embassy.user` 持有或获取 User Token。
- `embassy.admin` 持有或获取 Admin Session Token。
- `new Bureau({ bureau_token })` 持有长期 Bureau 机器凭证。
- City 不会成为上述任何一种身份。City 中运行的 Agent 可以把 Embassy 或其他客户端当作
普通依赖使用。
## CLI 对应关系
- `fed` / `downfed` 部署和管理 Federation。
- `city` / `downcity` 管理本地 Agent 宿主。
两个命令可以来自同一个发行包,但它们拥有不同的运行时和生命周期状态。
### 产品模型
Source: https://downcity.ai/zh/city-sdk-docs/concepts/product-model/
Downcity 最核心的心智不是“一个产品对应一个后端”,而是:
> 一个 Federation,服务多个 AI 产品和工作流。
这样做的原因很简单。真正被重复建设的,通常不是你的业务后端,而是 AI 调用这一层:
- provider key 存放
- 模型目录
- token 校验
- usage 记录
- hooks、限额、扣费和日志
这些能力一旦你开始做第二个、第三个 AI 产品,就会反复出现。
## 多个产品,一套 Federation
产品 A
网页工具、内容产品、工作流小工具。
bureau_id = product_a
产品 B
Chrome 扩展、桌面工具、移动端入口。
bureau_id = product_b
产品 C
客户 Demo、内部工具、行业专题站。
bureau_id = product_c
→
Federation
City 模型目录、provider env、service 路由、token 校验、usage 和 hooks。
## 什么应该留在 Federation
- 模型目录和 provider 配置
- `user_token` 校验
- `city.ai.stream()`、`city.ai.image_create()` / `city.ai.image_result()` 这类 AI service 调用能力
- `city.ai.decision()` 这类结构化决策调用
- usage 记录、日志、限额和商业 hooks
- 多个产品可以共用的调用逻辑
## 什么继续留在产品或业务系统
- 用户注册、登录和账号体系
- 订单、订阅、余额和 CRM
- 页面、交互、工作流和内容数据
- 每个产品自己的品牌、定价和市场策略
换句话说,Downcity 集中的是“AI 基础设施”,不是“全部业务系统”。
## 为什么这比“每个项目一个后端”更稳
如果你每做一个新产品都复制一套 AI 后端,很快会遇到这些问题:
- provider key 分散在多个地方
- token 规则不一致
- usage 和日志口径不统一
- 新 provider、新模型、新限额策略要改很多 repo
把 AI 调用层收敛到 Federation 后,新产品通常只需要做两件事:
1. 通过 `Embassy Admin` 创建一个 Bureau
2. 在产品侧接入 `Embassy User`
## `bureau_id` 在这个模型里代表什么
`bureau_id` 不是模型名,也不是租户系统的全部抽象。
它是 runtime 看待“产品边界”的稳定主键,用来回答这些问题:
- 这是哪个产品发起的调用
- 这个产品是否处于 `active` 状态
- hooks 和 usage 应该按哪个产品维度记录
- 一个用户在不同产品里的调用是否需要区分
如果你在做多产品组合,`bureau_id` 是最稳定的边界。
## model 在产品层里的角色
当前实现里,model 是 Runtime 注册出来的能力单元,不属于某个 city。
对产品来说,model 更像“可见能力”:
- 可以显式传给 `city.ai.stream({ model, call })`
- 每次 AIService 调用都必须显式传入模型 ID 或 `CityModel`
这意味着产品端看到的是稳定模型 ID,而不是上游 provider 的具体细节。
## 模型类别与能力
目录中的每个模型都带一个 `model_type`,表示它属于哪一类:`language`、`decision`、`image`、`sound` 或 `video`。它由 Federation 从模型实际实现的能力推导,与 `modalities` 同源。
两者分工不同:`model_type` 回答“它是什么”,用于展示与分组;`modalities` 回答“它能做什么”,判断可执行能力应读 `modalities`。例如对话模型带 `text` / `stream`,决策模型只带 `decision`,因此只有前者能交给 Agent。
### AI 架构
Source: https://downcity.ai/zh/city-sdk-docs/concepts/architecture/
```text
City 客户端 / Agent
|
v
CityModel(ModelClient)
|
v
Federation AIService
鉴权 -> 模型查找 -> fallback -> reasoning -> 计量
|
v
AIChannel.stream(AIChannelStreamInput)
|
v
OpenAI-compatible 或私有 Provider Adapter
```
`CityModel` 是客户端可执行模型,持有公开的 `CityModelDescriptor` 和 Federation transport,不知道上游密钥或厂商协议。
`AIService` 是服务端编排器,负责路由、fallback、reasoning 校验、usage 归一化和计费。
`AIChannel` 是服务端上游边界,负责连接配置、真实模型选择、服务端 `provider_options`,并通过 Provider Adapter 返回 `ModelStreamEvent`。
OpenAI 兼容端点只是适配器,不是第二条执行路径:
```text
OpenAI JSON/SSE -> ModelCall -> AIService -> AIChannel.stream -> ModelStreamEvent -> OpenAI JSON/SSE
```
### token 模型
Source: https://downcity.ai/zh/city-sdk-docs/concepts/token-model/
Downcity 使用管理员会话 Token 管理 Federation,并使用 `user_token` 让终端 client 调用 service。
可信后端
你的后端使用管理员 ID 和密码登录,然后持有有时限的管理员会话 Token。
创建 city / 申请 user_token
→
Downcity
校验管理员会话 Token,签发 `user_token`,并在内部保存 provider key。
→
终端 client
前端、扩展或 App 使用 Embassy User 携带 `user_token` 调用 Service。
拿不到管理员凭证
## user_token
`user_token` 是给终端用户或产品 client 使用的调用凭证。Embassy Admin 可以基于 `bureau_id + user_id` 向 Federation 申请。
- `bureau_id`
- `user_id`
- `metadata`
- `ttl`
登录开始时由产品配置明确 `bureau_id`;登录完成后,client 调用 service 只携带 `user_token`,
`bureau_id` 由 Federation 从已验证 Token 中读取。client 不接触 provider key,也不接触管理���会话 Token。
User Token 使用单一 `downcity:user` audience。Federation 与 Bureau Server 校验同一个 audience;
Bureau Server 还会比较 Token 中的 `bureau_id` 与自身绑定的 Bureau ID。`bureau_id` 始终保持
产品提供的原始值,不参与 audience 拼接或规范化。
## 管理员会话 Token
使用 `fed deploy` 配置的管理员 ID 和密码登录 Embassy Admin。登录响应会返回有时限的管理员会话 Token,用于创建 Bureau、管理 env,以及请求 Federation 为用户签发 `user_token`。
```ts
const embassy = new Embassy({
federation_url: "https://base.example.com",
admin_token: administrator_session_token,
});
const bureau = await embassy.admin.bureaus.create({
name: "Chrome Extension",
server_url: "https://bureau.example.com",
});
```
## 多产品复用
多个 client 可以归属同一个 Bureau。签发 token 时明确写入 `bureau_id`:
```ts
const user = await embassy.admin.service("accounts").action("tokens/issue").invoke({
bureau_id: bureau.bureau_id,
user_id: "user_123",
metadata: {
plan: "pro",
},
ttl: "7d",
});
console.log(user.user_token);
```
### 信任边界
Source: https://downcity.ai/zh/city-sdk-docs/concepts/trust-boundary/
Downcity 的安全模型建立在清晰的信任边界上。
## 可以放在 client
- `Embassy User`
- `federation_url`
- `user_token`
- 模型 ID
- prompt、messages、size、voice 等用户输入
## 必须留在可信环境
- provider API key
- 管理员 ID、密码和会话 Token
- Runtime env 管理权限
- token 签发逻辑
- 套餐、余额、扣费和风控判断
## City 的边界
City 负责校验 `user_token`,读取 Runtime env,并通过 service handler 调用真实模型。client 不需要知道 provider key,也不需要知道你内部如何扣费。
```plaintext
client 可以知道:我要调用哪个模型
client 不应该知道:这个模型背后用哪个 provider key
```
这个边界让纯客户端产品可以直接接入 City,同时不暴露敏感配置。
### usage 与商业模式
Source: https://downcity.ai/zh/city-sdk-docs/concepts/usage-and-billing/
Downcity 不替你决定商业模式。它提供 hook,让你把自己的套餐、余额、限额、日志和扣费系统接进 AI 调用生命周期。
## before hook
`before` 适合做调用前判断:
- 用户是否有权限
- 套餐是否允许该模型
- 今日额度是否足够
- 是否触发风控或频控
## after hook
`after` 适合做调用后记录:
- 记录 provider usage
- 写调用日志
- 扣除余额
- 同步账单
- 按产品维度分析成本
```ts
const ai = new AIService();
ai.hook
.before(async (ctx) => {
await quotaService.check(ctx.user?.user_id, ctx.variant?.id);
})
.after(async (ctx) => {
await usageService.record({
user_id: ctx.user?.user_id,
bureau_id: ctx.bureau?.bureau_id,
model: ctx.variant?.id,
output: ctx.output,
});
});
base.use(ai);
```
这样多个 AI 产品可以共享同一套商业逻辑,而不是每个项目各写一遍。
### 现在怎么用
Source: https://downcity.ai/zh/city-sdk-docs/quickstart/use-now/
如果你想先按仓库里的现成产品体验,入口是:
- `templates/localfed`
- `cli/city`
跑通后,你会得到这个调用链:
```plaintext
City Client
↓ Embassy Admin 创建 Bureau / 请求 Federation 签发 user_token
Federation
↓ Embassy User 携带 user_token 调用 service
AIChannel → AIService → handler
```
## 1. 启动 City
```ts
import {
Federation,
AIService,
AIChannel,
type AIChannelStreamInput,
type AIChannelStreamResult,
} from "@downcity/federation";
import { Database } from "@downcity/database-sqlite";
const database = new Database({ filename: "./data.sqlite" });
const base = new Federation({ database });
// 注册一个 echo 模型
class EchoChannel extends AIChannel {
constructor() {
super({ id: "echo" });
}
protected async stream(
input: AIChannelStreamInput,
): Promise {
const input_text = input.call.messages
.flatMap((message) => message.content)
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n");
return {
stream: new ReadableStream({
start(controller) {
controller.enqueue({ type: "model_start", request_id: crypto.randomUUID(), model_id: input.model.id });
controller.enqueue({ type: "text_start", content_id: "echo_text" });
controller.enqueue({ type: "text_delta", content_id: "echo_text", delta: `Echo: ${input_text}` });
controller.enqueue({ type: "text_finish", content_id: "echo_text" });
controller.enqueue({
type: "model_usage",
usage: { input_tokens: 0, output_tokens: 0, total_tokens: 0 },
});
controller.enqueue({ type: "model_finish", finish_reason: "stop" });
controller.close();
},
}),
};
}
}
const echo = new EchoChannel();
const ai = new AIService();
ai.use(echo.model({ id: "local-echo", upstream_model: "local-echo", name: "Local Echo" }));
base.use(ai);
import { serve } from "@hono/node-server";
await base.health();
serve({ fetch: (request) => base.fetch(request), port: 43127, hostname: "127.0.0.1" });
```
## 2. 创建 Bureau 并请求签发 token
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: "http://127.0.0.1:43127",
admin_token: administrator_session_token,
});
const token = await embassy.admin.service("accounts").action("tokens/issue").invoke({
bureau_id: "demo",
user_id: "user_123",
metadata: { plan: "pro" },
ttl: "7d",
});
```
## 3. 产品侧调用
```ts
const user_embassy = new Embassy({
federation_url: "http://127.0.0.1:43127",
user_token: token.user_token,
});
const catalog = await user_embassy.user.ai.catalog();
const model = catalog.require("local-echo");
// SDK 通路
const stream = await model.stream({
messages: [{
role: "user",
content: [{ type: "text", text: "你好 Downcity" }],
}],
});
for await (const event of stream) {
if (event.type === "text_delta") process.stdout.write(event.delta);
}
```
## 4. 你真正复用的是什么
多个产品接入后,复用的是这些东西:
- `.env` 中的 provider key
- `user_token` 校验
- AIService 的模型路由
- hook 里的套餐、限额、日志和扣费
下一步:
- [AIChannel 与模型注册](/zh/city-sdk-docs/service/ai/provider)
- [调用 AI 服务](/zh/city-sdk-docs/service/ai/calling)
- [创建 City](/zh/city-sdk-docs/quickstart/create-city)
- [签发 user_token](/zh/city-sdk-docs/quickstart/issue-token)
### 创建 Federation
Source: https://downcity.ai/zh/city-sdk-docs/quickstart/create-city/
服务端运行时的类是 `Federation`(文档里也叫 Federation),产品侧用 `City` 客户端去访问它。两者的区别见 [Federation 与 City](/zh/city-sdk-docs/concepts/federation)。
最快的本地创建和启动方式是:
```bash
fed create --path ./my-fed
cd my-fed
pnpm install
fed deploy
```
`fed create` 和 `fed deploy` 默认使用 `--path .`;其他目录通过 `--path ` 指定,不接受位置路径参数。按本次操作使用 `--id` / `--name` 选择实例的规则见 [CLI 快速开始](/zh/city-sdk-docs/packages/cli/quickstart)。
默认模板使用 Node.js + SQLite。`fed deploy` 使用固定默认端口 `12314`(可用 `deployment.port` 覆盖;端口冲突时交互确认是否停止占用进程,默认否,非交互终端报错),由 macOS 用户级 launchd 或 Linux 用户级 systemd 管理服务,并交互式配置管理员 ID 和密码;之后可以在任意路径运行 `fed` 查看并直接进入管理。模板的 `[deployment.process]` 显式设置 `auto_start = false`、`restart_on_failure = true`。异常退出后每隔 10 秒尝试恢复,60 秒内最多 5 次;主动 `fed stop` 禁用自动启动并保持停止,系统重启后仍有效,直到显式 deploy/restart。自动启动需显式开启:macOS 在用户登录后启动,Linux 需要用户 manager 可用,CLI 不自动开启 linger。
本地 Node 发布在切换前失败会保留旧实例和配置,没有待恢复切换时允许 restart;切换失败或中断后,恢复保护持续到一次显式 deploy 成功,期间 restart 被阻断,后续 build/preflight 失败不会清除保护。候选启动或就绪失败会停止候选并移除自启关联,清理异常显示 `unknown` 并要求人工检查。不自动回滚代码或数据库。`fed status` 分别显示登记、manager、健康与发布历史,最后成功 release 不代表其正在运行。阶段规则和配置细节见 [CLI 快速开始](/zh/city-sdk-docs/packages/cli/quickstart)。下文是手动嵌入 Federation runtime 时的 SDK 写法。
安装包:
```bash
pnpm add @downcity/federation @downcity/database-sqlite
```
准备好数据库即可。`fed deploy` 会交互式配置管理员 ID 和密码;密码只保存为 PBKDF2 摘要,登录后使用管理员会话 Token。Federation 首次启动时会自动补齐 `DOWNCITY_FEDERATION_TOKEN_SIGNING_KEY` 和 `BETTER_AUTH_SECRET`。provider key 则在启动后通过 Admin API 或 `fed` 的 admin workspace 写入:
```bash
OPENAI_API_KEY="..."
OPENAI_BASE_URL="https://api.openai.com/v1"
```
创建 Federation:
```ts
import { Federation } from "@downcity/federation";
import { Database } from "@downcity/database-sqlite";
const database = new Database({ filename: "./data.sqlite" });
const base = new Federation({ database });
```
默认数据库会落到:
```plaintext
./data.sqlite
```
本地 SQLite 使用 `@downcity/database-sqlite`。正式部署使用 PostgreSQL 时,改用 `@downcity/database-postgresql`。
如果要使用 Cloudflare Workers / D1,传入 D1 Adapter:
```ts
import { Database } from "@downcity/database-d1";
const database = new Database({ binding: env.DB });
const base = new Federation({ database });
```
Federation 会在第一次 `health()`、`fetch()`、`table()` 等运行时操作时自动初始化。
如果你的 Federation 还需要自己的业务表,可以通过 Service 或服务声明表。表会挂在对应 Service 的命名空间下,并和 Federation 默认数据库使用同一个数据库连接:
```ts
import { sqliteTable, text } from "drizzle-orm/sqlite-core";
import { Service } from "@downcity/federation";
const notes = sqliteTable("notes", {
id: text("id").primaryKey(),
title: text("title").notNull(),
status: text("status").notNull(),
});
const notesService = new Service({
id: "notes",
tables: { notes },
});
base.use(notesService);
const table = await base.table("notes.notes");
await table.insert({
id: "note_1",
title: "First note",
status: "draft",
});
```
常规项目不需要手动建表;第一次运行时操作会自动准备 Federation 内置表和 Service 声明的表。
启动服务:
```ts
import { serve } from "@hono/node-server";
await base.health();
serve({ fetch: (request) => base.fetch(request), port: 3001, hostname: "127.0.0.1" });
```
这个服务就是后续多个产品共用的 Federation。管理和业务数据暂时通过你自己的数据库与产品后端处理。
### 添加模型
Source: https://downcity.ai/zh/city-sdk-docs/quickstart/add-model/
创建 `AIChannel`,实现 Downcity Model Protocol stream,再注册 `AIModelSpec`:
```ts
import {
AIChannel,
AIService,
stream_openai_compatible_model,
type AIChannelStreamInput,
type AIChannelStreamResult,
} from "@downcity/federation";
class DeepSeekChannel extends AIChannel {
constructor() {
super({
id: "deepseek",
env: { DEEPSEEK_API_KEY: "DeepSeek API Key" },
base_url: "https://api.deepseek.com/v1",
});
}
protected async stream(
input: AIChannelStreamInput,
): Promise {
const api_key = input.env("DEEPSEEK_API_KEY");
if (!api_key) throw new Error("DEEPSEEK_API_KEY is required");
return stream_openai_compatible_model(input, {
api_key,
base_url: this.base_url ?? "https://api.deepseek.com/v1",
});
}
}
const channel = new DeepSeekChannel();
const ai = new AIService();
ai.use(channel.model({
id: "deepseek-v4-flash",
upstream_model: "deepseek-chat",
name: "DeepSeek V4 Flash",
context_window: 128_000,
}));
federation.use(ai);
```
这一个 `stream()` 同时支持 `city.ai.stream()`、`CityModel` 和 `/v1/ai/chat/completions`。
reasoning、fallback、计费和 `provider_options` 详见 [AIChannel 与模型注册](/zh/city-sdk-docs/service/ai/provider)。
## 结构化价格
模型可以通过 `pricing` 提供机器可读的价格方案。`unit` 表示计费对象,`scale` 表示每个价格对应的单位数量;多个方案可通过 `dimensions` 表达时段或档位。
```ts
pricing: {
currency: "USD",
unit: "token",
scale: 1_000_000,
rates: { input: 1.6, output: 9.6, cached_input: 0.16 },
}
```
旧版 `price` 字段仅作为兼容投影,新增模型不应单独维护价格文案。
### 签发 User Token
Source: https://downcity.ai/zh/city-sdk-docs/quickstart/issue-token/
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: "https://fed.example.com",
admin_token: administrator_session_token,
});
const issued = await embassy.admin.service("accounts")
.action("tokens/issue")
.invoke({
bureau_id: "product-web",
user_id: "user_123",
metadata: { plan: "pro" },
ttl: "7d",
});
```
Token 签发由 Federation 执行。Bureau 负责验证 User Token,但不签发它。
### 连接 Embassy
Source: https://downcity.ai/zh/city-sdk-docs/quickstart/connect-client/
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url: "https://fed.example.com",
user_token: "ub_xxx",
});
const catalog = await embassy.user.ai.catalog();
const model = catalog.get("gpt-5.4");
if (!model) throw new Error("model not found");
const result = await embassy.user.ai.text({
model,
prompt: "写一段欢迎语",
});
```
自定义或官方 Service 使用 `embassy.user.service(name)`。Provider Key、模型路由和 Usage
记账都留在 Federation 内部。
### 纯客户端产品
Source: https://downcity.ai/zh/city-sdk-docs/guides/pure-client-products/
纯客户端产品不是没有后端,而是不为每个产品重复创建 AI 后端。
Downcity 让新项目可以先只写前端,直接接入已经部署好的 Federation。这样你可以先验证产品体验,再决定要不要补自己的业务后端。
## 适合的产品形态
- 小工具网页
- Chrome 扩展
- 桌面壳
- 移动端入口
- 客户 Demo
- 内部工具
## 推荐边界
client 负责:
- UI 和交互
- 调用 Embassy User
- 登录开始时使用产品配置中的 `bureau_id`
- 保存或刷新 `user_token`
Federation 负责:
- provider key
- 模型目录
- `user_token` 校验
- service 路由
- usage 记录
- hook 和商业逻辑
## 一个最常见的最小结构
```plaintext
产品前端
↓
你的登录/签 token 接口
↓
Federation
```
这里的“产品后端”可以一开始非常薄,只做:
- 用户登录
- 通过 Embassy Admin 请求 User Token
- 把 `user_token` 返回给前端
普通 service 请求不再重复提交 `bureau_id`;Federation 从已验证的 `user_token` 中读取。
## 为什么这样更适合早期产品
- 不需要为每个 AI 想法复制一套 provider 集成
- 前端可以更快上线验证
- 多个产品共用同一套 AI 调用、日志和限额逻辑
如果后续产品变复杂,再补业务后端;不要在第一天就为每个 AI 想法复制一套 AI 基础设施。
### 多产品共用一套 Federation
Source: https://downcity.ai/zh/city-sdk-docs/guides/multi-product-city/
多个产品共用一套 runtime 时,最重要的不是“省一台服务器”,而是把**共享能力**和**产品差异**拆开。
应该共享的是:
- provider env
- 模型目录
- service 路由
- hooks、usage 和日志
- `user_token` 校验能力
应该继续留在产品侧的是:
- 页面和交互
- 用户体系
- 套餐、订单、余额的业务规则
- 每个产品自己的品牌、定价和定位
## 一张图看清楚复用边界
产品 A
例如网页工具。
bureau_id = web
产品 B
例如 Chrome 扩展。
bureau_id = extension
产品 C
例如客户 Demo 或内部工具。
bureau_id = demo
→
Federation
复用模型目录、provider env、service 逻辑、usage 记录和 hooks。
## `bureau_id` 应该怎么用
`bureau_id` 是产品边界,而不是模型边界。
它适合用来表达:
- 这是哪个产品发起的调用
- 某个产品是否还处于 `active`
- hooks 应该把 usage 记到哪个产品
- 某个用户在不同产品里的调用是否要区分
一个常见做法是给每个产品一个稳定的 `bureau_id`:
```ts
const issued = await admin.service("accounts").action("tokens/issue").invoke({
bureau_id: "demo",
user_id: "user_123",
metadata: {
plan: "starter",
channel: "extension",
},
});
```
## token metadata 适合放什么
`bureau_id` 负责“这是哪个产品”,而 token metadata 更适合表达“这个用户在这个产品里的业务状态”。
常见字段:
- `plan`
- `organization_id`
- `channel`
- `feature_flag`
- `team_id`
这样 hooks 就可以基于 `ctx.bureau` 和 `ctx.user.metadata` 做差异化处理,而不需要为每个产品单独复制一套 City。
## 多产品共享时的推荐分层
### 产品侧
- 保存自己的路由、界面和业务体验
- 用 `Embassy User` 调 City
- 只持有 `user_token`(其中包含 `bureau_id`)
### 业务后端
- 负责登录、订单、余额、订阅和业务数据
- 在可信环境里使用 `Embassy Admin`
- 在登录成功后申请 `user_token`
### City
- 负责模型目录
- 负责 provider 调用
- 负责 usage 和 hooks
- 负责可复用的 AI service 逻辑
## 什么时候应该新建一个 city
这些场景通常值得新建 city:
- 一个独立的产品或独立市场
- 需要单独暂停或启用调用
- 需要单独做 usage 统计或商业策略
- 需要区分浏览器扩展、Web App、客户 Demo 这类不同产品形态
这些场景通常不需要新建 city:
- 同一产品里的不同页面
- 同一产品里的不同 feature flag
- 单个用户的不同会话
这些更适合继续放在你自己的业务系统或 token metadata 里。
### Cloudflare Workers
Source: https://downcity.ai/zh/city-sdk-docs/guides/cloudflare-workers/
如果你准备把 Downcity 部署到 Cloudflare Workers,推荐做法不是等一个单独的 edge package,而是直接把 `@downcity/agent` 接到 Workers runtime。
公开仓库里保留了 `templates/edgefed` 作为开发者快捷示例。Downcity 官方私有 Worker 实现维护在公开仓库之外。
## 这条路径解决什么
Cloudflare Workers 和 Node.js 最大的不同,不是 HTTP 入口,而是 runtime 资源模型不同:
- 数据库通常来自 `env.DB` 这类 binding
- 环境变量读取不再是本地 `.env` 文件
- request origin 可能需要在每次请求时同步到 service
- Worker isolate 会复用,所以 runtime cache 需要自己管理
这也是为什么这里更适合用 guide 解释接法,而不是再抽一个空的 npm 包。
## 最小接法
Federation 需要一个 D1 Database Adapter:
```ts
import { Federation } from "@downcity/federation";
import { Database } from "@downcity/database-d1";
export interface Env {
DB: D1Database;
}
export default {
async fetch(request: Request, env: Env) {
const database = new Database({ binding: env.DB });
const base = new Federation({ database });
await base.health();
return base.fetch(request);
},
};
```
这里的重点是 Adapter 明确拥有 D1 的运行时差异:
- D1 binding 只传给 `@downcity/database-d1`
- Adapter 内部组合 Drizzle,并负责快照冲突重试与原子提交
- City 和 Service 都不会拿到原始 D1 binding
- 当前请求 origin 可以在请求前同步给需要 OAuth callback 的 service
## 从 `templates/edgefed` 快捷示例开始
仓库里的 `templates/edgefed/src/index.ts` 只保留 Worker 接入 Federation 必需的边界:
- 用 `@downcity/database-d1` 把 `env.DB` 接成 Federation 可用数据库
- 在 Worker isolate 内复用 Federation 实例
- 把 HTTP request 交给 Federation 处理
业务 Service、模型和 provider 应由产品按需组合,不属于 Edge runtime 模板。
## 和 Node 路线的边界
Worker 和 Node 是同一套心智模型:都创建对应的 Database Adapter,然后传给 `new Federation({ database })`。
- Node.js 本地使用 `@downcity/database-sqlite`
- Node.js 生产可使用 `@downcity/database-postgresql`
- Workers / D1 使用 `@downcity/database-d1`
## 下一步
- 如果你还没搭 City 本体,先读 [Federation](/zh/city-sdk-docs/packages/federation/federation)
- 如果你要管理 provider key,继续读 [provider 环境变量](/zh/city-sdk-docs/guides/provider-env)
- 如果你需要最小 Worker 接入示例,直接看 `templates/edgefed/src/index.ts`
### 鉴权与 user_token
Source: https://downcity.ai/zh/city-sdk-docs/guides/auth-and-user-token/
Downcity 不替你托管用户系统。它只要求 client 请求携带可校验的 `user_token`。
## 已有登录系统
如果你已经有登录系统,可以在登录后用 Embassy Admin 请求 Federation 签发 Downcity Token:
```ts
const user = await embassy.admin.service("accounts").action("tokens/issue").invoke({
bureau_id: "demo",
user_id: session.user.id,
metadata: {
plan: session.user.plan,
},
ttl: "7d",
});
```
然后把两样东西交给产品侧:
- `bureau_id`
- `user_token`
## 没有复杂后端
如果新产品是纯客户端项目,可以把 token 签发收敛到 Federation,而不是每个产品写一套服务。
## token 不应该做什么
- 不要把 provider key 写进 token。
- 不要把不可公开的计费规则写进 token。
- 不要让 client 持有管理员 ID、密码或会话 Token。
token 只表达“这个用户是谁”和“这次请求有哪些业务 metadata”。
### AIChannel 环境变量
Source: https://downcity.ai/zh/city-sdk-docs/guides/provider-env/
在 Channel 上声明密钥:
```ts
class DeepSeekChannel extends AIChannel {
constructor() {
super({
id: "deepseek",
env: { DEEPSEEK_API_KEY: "DeepSeek API Key" },
base_url: "https://api.deepseek.com/v1",
});
}
protected async stream(input: AIChannelStreamInput) {
const api_key = input.env("DEEPSEEK_API_KEY");
if (!api_key) throw new Error("DEEPSEEK_API_KEY is required");
return stream_openai_compatible_model(input, {
api_key,
base_url: this.base_url ?? "https://api.deepseek.com/v1",
});
}
}
```
`env` 会为模型目录的管理端视图生成必填 env 声明。一个 Channel 需要多个环境变量时直接添加多个字段。
值存储在 Federation env 表中,执行时通过 `input.env(key)` 读取。它们不会进入 `CityModelDescriptor` 或客户端运行时。
### 模型适配器
Source: https://downcity.ai/zh/city-sdk-docs/guides/model-adapters/
Downcity 核心只有一种模型协议。OpenAI Chat Completions 只在 HTTP 边界适配:
```text
City SDK / CityModel ------\
-> ModelCall -> AIService -> AIChannel.stream()
OpenAI Chat Completions ---/ -> ModelStreamEvent
```
OpenAI-compatible 上游使用 `stream_openai_compatible_model()`。私有 HTTP 协议应实现自己的 Adapter,把 `ModelCall` 转成厂商请求,并返回 `AIChannelStreamResult`;AIService 不理解厂商请求格式。
OpenAI Chat Completions 只是同一 Model Protocol 路径外层的 HTTP Adapter。没有 raw passthrough,也没有第二条模型执行链,因此 tools、fallback、reasoning、计量和计费在不同客户端之间保持一致。
Channel 负责:
- 密钥和 base URL;
- 上游模型工厂与协议选择;
- 模型级 `provider_options`;
- usage 解释和计费;
- 私有流到 `ModelStreamEvent` 的转换。
AIService 负责:
- 模型注册表和公开目录;
- 鉴权和可用性;
- 媒体 fallback 与 reasoning 校验;
- 计量、余额检查和扣费结算。
### hook 与商业逻辑
Source: https://downcity.ai/zh/city-sdk-docs/guides/hooks-and-billing/
Downcity 的 hook 分三层:Action → Service → Global。执行顺序从外层到内层:
```
global.before
→ service.before
→ action.before
→ action.run() ← 核心逻辑
→ action.after ← 扣费
→ service.after
→ global.after
```
## Action 级 hook
每个 Action 有独立的 hook,适合挂业务逻辑:
```ts
const zh2en = svc.action("zh2en", async (ctx) => {
return await translate(ctx.input.text, "en");
});
// 调用前检查余额
zh2en.before(async (ctx) => {
const bal = await balance.get(ctx.user!.user_id);
if (bal <= 0) throw new Error("余额不足");
});
// 调用后扣费(可访问 ctx.output)
zh2en.after(async (ctx) => {
await deductBalance(ctx.user!.user_id, 10);
await logUsage(ctx);
});
```
## Service 级 hook
同一 Service 下所有 Action 共享:
```ts
svc.hook.before(async (ctx) => {
console.log(`${ctx.user?.id} → ${ctx.service?.id}.${ctx.action?.id}`);
});
svc.hook.after(async (ctx) => {
// 聚合统计、统一日志
});
```
## 对比
| | Action hook | Service hook |
|---|---|---|
| 粒度 | 单个 action | 该 service 下所有 action |
| 用途 | 余额检查、扣费、per-action 日志 | 公共校验、聚合统计 |
| 注册 | `action.before(fn)` | `svc.hook.before(fn)` |
## ctx 中的关键字段
```ts
interface Context {
input: Record // 请求参数
output?: unknown // Action 执行结果(after 可读)
user?: { user_id, metadata } // 当前用户
bureau?: { bureau_id, status } // 已验证的 Bureau 身份
service?: { id, name } // 当前 Service
action?: { id } // 当前 Action
}
```
### 账户登录
Source: https://downcity.ai/zh/city-sdk-docs/packages/federation/client/auth-flows/
账户操作统一位于 `embassy.user.account`。
```ts
const providers = await embassy.user.account.providers();
const login = await embassy.user.account.login({
provider: "email",
client_type: "cli",
bureau_id: "product-web",
input: {
email: "user@example.com",
password: "password",
},
});
```
邮箱须完成验证后才能登录。多步骤 Provider 使用 `login_start()` 和 `continue()`,同一账户访问器保管发起端领取凭据。`status()` 只查询状态;完成后调用 `exchange()` 领取并保存 User Token,同一访问器在网络失败重试时保留稳定的交换 ID。`login()` 自动完成交换。
GitHub、Google 和 WeChat OAuth 在第三方认证成功后自动返回发起产品。所有 OAuth 开始请求都提供 `redirect_uri`、随机 `state`、`code_challenge` 和 `code_challenge_method: "S256"`。产品验证返回的 state,再携带 `authorization_code`、`code_verifier` 与发起端私密证明交换 Token。`status()` 不交付授权码或 Token;领取凭据和 verifier 不得进入 URL 或日志。
CLI 和 Desktop 使用宿主管理的本机回调。从 `@downcity/federation/node` 导入 `create_loopback_login_callback`,该 Node 专用入口监听 `127.0.0.1` 随机非特权端口,验证随机回调路径、Host 和 state。把接收器参数交给 `login_start()`,传 `client_type: "cli"` 或 `"desktop"`,使用本机系统浏览器打开授权 URL;收到回调后调用 `exchange({ authorization_code: callback.authorization_code, code_verifier: callback.code_verifier })`。取消、超时或关闭窗口时释放监听。凭据保留在宿主进程;CLI OAuth 要求本机浏览器,远程或无图形会话不支持此登录方式。
宿主管理的 `login()` 可提供 `on_authorize: async (url) => ({ authorization_code, code_verifier })`:打开浏览器,等待并验证产品回调后返回交换证明。跨页面的网站在 BFF 中使用 `login_start()` 和 `exchange()`。
网站使用 `client_type: "web"`,`redirect_uri` 必须精确等于已注册 Bureau 的 `server.server_url` 后追加 `/api/auth/callback`。生产和本地开发地址分别注册 Bureau,本地 HTTP 允许 localhost。BFF 用同源 POST 发起登录,将 state、verifier 与领取凭据保存在短期 host-only HttpOnly Cookie 中;回调验证浏览器交易和 state 后交换授权码,再建立网站会话。
`exchange({ exchange_id })` 可指定安全保存的交换 ID;同一事务的网络重试复用原 ID。
`token()` 读取当前 User Token。`await embassy.user.account.logout()` 先撤销当前 Token,再清理本地凭证;失败保留凭证以便重试。Bureau 对新的受保护请求向 Federation 在线验证,检查不可用时拒绝访问;已开始的流式请求不强制中断。
登录后继续使用同一个 `embassy.user` 调用 `current()`、AI、Payment 和 Service。
### User 与 Admin Service
Source: https://downcity.ai/zh/city-sdk-docs/packages/federation/client/service-calls/
User 与 Admin 使用同一套 Service 协议,但属于两个独立身份子域。
```ts
const user_services = await embassy.user.list_services();
const profile = await embassy.user.current();
const result = await embassy.user.service("rewrite")
.action("formal")
.invoke({ text: "hello" });
const admin_services = await embassy.admin.list_services();
const env = await embassy.admin.env.list();
```
Federation 模型目录与 AI 执行使用 `embassy.user.ai`,Payment 使用
`embassy.user.payment`。Admin-only 管理能力始终留在 `embassy.admin`,不要把管理员凭证
传入 user 子域。
### Federation 运行时
Source: https://downcity.ai/zh/city-sdk-docs/packages/federation/federation/
`Federation` 是 Downcity 的服务端长期运行容器(文档里也叫 Federation)。它把 Database Adapter、service、鉴权和统一 `/v1/*` 路由收在同一个服务端入口里。产品侧访问它用的是 `City` 客户端,区别见 [Federation 与 City](/zh/city-sdk-docs/concepts/federation)。
## 这个概念在说什么
可以先把 Federation 理解成“多个产品共用的 AI infrastructure runtime 进程”。
它长期持有这些能力:
- Database Adapter
- service 注册表
- 服务挂载点
- HTTP 路由入口
- token、city、env 等基础设施
所以你通常不是“调用一下 Federation”,而是“启动一套 Federation runtime,然后让多个产品 client 长期连接它”。
## 什么时候你需要关心这一页
- 你准备第一次真正把 Federation 跑起来
- 你想理解为什么 `Federation` 只需要一个 Database Adapter
- 你已经会写 service,但还不清楚 `fetch()`、`serve()` 各自用在什么地方
- 你要把 Federation 接到现有 Node 服务、Cloudflare Worker 或别的 HTTP 入口上
## 什么时候这页不是重点
- 你只想知道产品前端怎么用 `City` 客户端调用:优先读 [Client SDK](/zh/city-sdk-docs/packages/federation/client)
- 你只想知道账号登录怎么跑通:优先读 [@downcity/services](/zh/payments)
- 你只想看某个 custom service 怎么写:优先读 [Service 与 Action](/zh/city-sdk-docs/packages/federation/service-and-action)
## 最小可运行示例
下面这个例子说明 Federation 运行时最小长什么样:
```ts
import { AIService, Federation } from "@downcity/federation";
import { Database } from "@downcity/database-sqlite";
import { serve } from "@hono/node-server";
const database = new Database({ filename: "./.base/downcity.sqlite" });
const base = new Federation({ database });
const ai = new AIService();
ai.use({
id: "local-echo",
name: "Local Echo",
actions: {
text: async (ctx) => ({
id: crypto.randomUUID(),
role: "assistant",
parts: [
{
type: "text",
text: String(ctx.input.prompt ?? ""),
state: "done",
},
],
}),
},
});
base.use(ai);
await base.health();
serve({
fetch: (request) => base.fetch(request),
port: 43127,
hostname: "127.0.0.1",
});
```
这个例子里真正重要的是三件事:
1. `database` 决定 Federation 使用哪一个数据库 Adapter
2. `base.use(...)` 决定 Federation 暴露哪些能力
3. `base.fetch()` 决定你怎么把它接进 HTTP 层
## HTTP 请求与错误
每个进入 `Federation.fetch()` HTTP 边界的请求,在 middleware 前由服务端生成 `req_`,忽略调用者提供的 ID。普通 HTTP 协议范围内的边界响应覆盖 `x-request-id`,包括 middleware 短路、413、408、504、成功、业务错误、native Response、流式响应和路由 404。Router、HTTP Action 的 `Context.request_id` 与 `Context.locals.request_id`、AI relay 使用相同 ID。宿主在边界之外直接处理的响应不属于此范围;HTTP 101 upgrade 不重新包装或托管,也不保证 `x-request-id` 响应头。
POST Action 默认 `body: "json"`:空体或纯空白解析为 `{}`,非空体必须是 JSON 对象;GET 从 query 读取参数。Webhook Action 可显式使用 `body: "raw"`;原生 `handler: { request }` 路由的正文同样有界读取一次,再按原始字节重建 Request,不进行 Action JSON 解析,OAuth form 与 redirect 按原生协议处理。详见 [Service 与 Action](/zh/city-sdk-docs/packages/federation/service-and-action#action-请求体模式)。
框架捕获的抛错返回 `error: { code, message, type, request_id }`。明确的 4xx `httpError` 保留 message。显式整数 `statusCode` 为 400–599 且 `code` 匹配 `^[A-Za-z][A-Za-z0-9_]{0,63}$` 时保留领域码,包括 `503 async_dispatch_unavailable`;缺失或无效的状态码一律成为 `500 INTERNAL_ERROR`。所有 5xx message 都通用:503 为 `Service temporarily unavailable`,504 为 `Request timed out`,其他 5xx 为 `Internal server error`。
业务或 native handler 直接返回的错误 Response 保持其正文,仍覆盖 `x-request-id`,不消费 body、不缓冲 SSE。流开始后的边界超时或取消会 abort 下游并取消 reader、结束流,不能改写 HTTP 状态或返回 JSON 错误,也不构造通用 SSE 错误帧。`onError` hook 自身失败不会覆盖原始错误。
框架 5xx 结构日志仅包含 `event`、`request_id`、`status`、`code`,不含正文、Token、原始 Error 和 stack。这不提供完整 access log,也不保留原始堆栈。状态分类与默认码详见 [HTTP API](/zh/city-sdk-docs/reference/http-api#框架错误)。
## HTTP 策略配置
`FederationOptions.http` 配置默认启用的 HTTP 边界,在 middleware 和 Router 前按实际 `Uint8Array.byteLength` 累计正文。省略或伪造较小的 `Content-Length` 不能绕过上限。`ordinary` 默认 1 MiB / 15 秒读取 / 30 秒执行;`webhook` 仅匹配 `/v1/payment/webhook`,默认 2 MiB / 15 秒 / 30 秒。`model_stream` 匹配 `/v1/ai/stream`,`media` 匹配 `/v1/chat/completions`、`/v1/ai/chat/completions` 以及 `/v1/ai/` 下的 `image/create`、`asr`、`tts`、`embedding`、`rerank`、`video`、`audio`、`decision`,两类均默认 40 MiB / 60 秒 / 180 秒。轻量的 `/v1/ai/image/result` 使用 `ordinary`。
四类配置均为 partial,可单独设置 `max_body_bytes`、`body_timeout_ms`、`execution_timeout_ms`,未指定字段保留本类别默认值。`routes: [{ path, max_body_bytes?, body_timeout_ms?, execution_timeout_ms? }]` 按完整 pathname 精确覆盖,优先于类别;未指定限额继承该路径所属类别。不接受前缀、通配符、查询串、片段或重复路径。限额必须为正安全整数,正文上限最多 256 MiB,毫秒期限最多 2,147,483,647;未知字段或无效值在构造时拒绝。
正文读取是总期限,收到 chunk 不会重置。执行期限从请求正文读完起算,涵盖 middleware 和业务处理。非 SSE 的 timer 持续到响应正文读完或取消才释放;响应头发送前到期返回 `504 REQUEST_TIMEOUT`,响应头已发送后只结束流,不改状态。无正文的 OPTIONS 请求也使用普通执行期限。模型及媒体入口默认等待响应头 180 秒。收到 SSE `Response` 后,timer 切换为 `stream_lifetime_ms`,默认 `900_000`(15 分钟),仍从请求正文读完起算,包含等待响应头的时间;它必须为正安全整数且不超过 2,147,483,647。边界不缓冲 SSE。模型总期限从 provider 执行开始计时,与从正文读完起算的 HTTP SSE 总期限独立,取先到期的一层;同步 JSON 仍受默认 180 秒 HTTP 执行期限约束。
无效长度返回 `400 INVALID_CONTENT_LENGTH`,`Content-Encoding` 除省略或 `identity` 外返回 `415 UNSUPPORTED_CONTENT_ENCODING`。正文超时返回 `408 REQUEST_BODY_TIMEOUT`,超限返回 `413 BODY_TOO_LARGE`;客户端取消对应 `499 REQUEST_CANCELLED`,断开后不能保证收到响应。完整状态与限额见 [HTTP API](/zh/city-sdk-docs/reference/http-api#http-边界与默认限额)。
`ServiceRouteContext.abort_signal` 和 Action `Context.abort_signal` 可读,原生路由可使用 `request.signal`。Adapter 应将请求信号与自身 deadline 合并,上游较短期限仍生效。取消为协作式中断,数据库操作可能继续,不表示事务撤销,也不触发自动重试。已入队图片 task 独立执行,不继承前台创建或结果查询请求的取消。
Edge / local-node 通过 workspace 链接 SDK,开发构建使用该默认策略。生产部署需构建包含功能的 SDK 和服务产物,运行实例不会自动更新。
## 模型执行策略
`AIServiceOptions.model_stream?: Partial` 配置语言模型期限,省略字段使用 `first_output_timeout_ms: 120_000`、`idle_timeout_ms: 120_000`、`total_timeout_ms: 900_000`。原生 `/v1/ai/stream`、OpenAI-compatible SSE / JSON 与 Relay 的所有语言模型执行共用 `execute_model_stream`;客户端不能在请求中抬高策略。
首输出预算累计等待 provider open 和首个有效输出前实际等待 read 的时间;idle 累计有效输出之间实际等待 read 的时间,并在有效输出时重置。背压期间不累计首输出或 idle,总墙钟一直计时。`model_start`、`text_start`、`reasoning_start`、空 delta 和 usage 不续期;非空文本 / reasoning 增量、工具调用开始、非空输入增量和工具调用结束算有效输出。配置值必须是 1–2,147,483,647 的安全整数,未知字段或无效值在构造时拒绝。配置示例见 [调用模型](/zh/city-sdk-docs/service/ai/calling#模型执行期限)。
Provider 更短的期限、HTTP 期限和模型期限取先到期的一层,超时 abort 同一次前台执行,不透明重试。Provider open 未返回时抛出 504,如 `MODEL_FIRST_OUTPUT_TIMEOUT` 或 `MODEL_EXECUTION_TIMEOUT`,Router 保留合法领域码并使用安全 message `Request timed out`。原生流已开始时补 `model_error`,错误为 `provider_timeout`、`status_code: 504`、`retryable: false`,说明首输出超时、输出停滞或总执行超时。尚无 provider `model_start` 时可补框架 `model_start`,仅用于失败终态协议,不伪造 usage。OpenAI SSE 发 error 帧,失败不发成功 `[DONE]`;JSON 聚合超时返回 504。已开始的 SSE 保持 HTTP 状态。
可信 usage 事实会保留,未返回 usage 不估算 token 或费用;既有 `bill` 按实际 facts 执行,具体收费由业务决定,不承诺缺少 usage 就永远零收费。`completion.outcome` 区分 `succeeded`、`failed`、`cancelled`;终态后 cancel 不误记取消或超时,不重复结算或扣费。结束或取消释放 timer、listener 和 reader,不等待可能无限挂起的上游 cancel;底层 SQL 副作用不能保证回滚。
## 生产启动与数据库准备
本地默认使用 `database_initialization: "automatic"`,首次初始化自动准备表、索引及系统数据。生产环境可以使用 `"prepared"`,将这些操作移出请求的启动路径。
部署进程应创建一个注册了完整 Service 的新实例,先调用 `await federation.prepare_database()`。该方法执行数据库准备、Service 准备及初始化验证,成功后写入准备版本标记;失败必须中止发布。随后上线的请求实例使用相同的 Service 配置及 `database_initialization: "prepared"`,只加载必要配置和密钥,缺少准备标记时拒绝启动。
`prepare_database()` 必须在该实例处理请求或调用 `health()` 之前执行,不应暴露成公开 HTTP 接口。跨实例 schema 变更仍需要受控发布,准备标记不替代应用自己的数据迁移历史。
全量迁移已有数据库时,先在空目标调用 `prepare_schema()`。该方法仅创建结构,不生成 Federation ID、配置或签名密钥,也不运行 Service 数据修复。导入并验证全部业务数据后,再调用 `prepare_database()` 完成运行准备,复用导入的原身份和密钥。
```ts
const federation = new Federation({
database,
database_initialization: "prepared",
on_startup_timing: ({ phase, duration_ms, ok }) => {
console.info({ phase, duration_ms, ok });
},
});
// 在调用 prepare_database() 或 health() 前注册全部 Service。
```
宿主通过定时任务调用 `await federation.maintenance()`,清理过期撤销记录和支持维护生命周期的 Service 数据。请求仍然校验凭证的有效期,安全性不依赖物理删除是否及时完成。自定义 Service 可分别通过 `on_prepare_database()` 和 `on_maintenance()` 扩展这两个阶段,`on_init()` 只处理实例运行所需的初始化。
启动计时事件只包含阶段名称、毫秒耗时和成功状态。启动失败的实例应由宿主退避重建整个容器,避免在部分安装完成的同一对象上重复注册路由。
## 场景一:Federation 自己就是主服务
如果你想让 Federation 自己作为主 HTTP 入口,最直接的理解方式就是上面的 `serve()`:
```ts
import { serve } from "@hono/node-server";
await base.health();
serve({ fetch: (request) => base.fetch(request), port: 3001, hostname: "127.0.0.1" });
```
这种方式适合:
- 先快速跑起一个独立 Federation
- 单独部署一个可复用的 AI backend
- 小团队先把 Federation 和业务后端拆成两个清晰边界
## 场景二:接进你自己的服务框架
如果你已经有现成的 HTTP 框架,更常见的是按请求转给 Federation:
```ts
export default {
async fetch(request: Request) {
return base.fetch(request);
},
};
```
这种方式适合:
- Cloudflare Workers
- 你已经有现成网关或 API server
- 想把 Federation 当成内部运行时,而不是单独开一个端口
### Cloudflare Workers 并发冷启动
同一个 Worker 部署可能同时启动多个 isolate。它们拥有独立内存,但共享同一个 D1,因此模块级 Promise 只能避免单个 isolate 重复初始化,不能充当全局锁。
Federation 会在共享数据库中原子初始化系统 env 和 Ed25519 user token signing key,并通过唯一约束保证全局只有一把 active signing key。如果数据库中存在旧版本并发启动遗留的多把 active key,启动时会保留创建时间最早的一把,并把其余 key 转为 retired。retired key 仍会发布到 JWKS,用于验证已经签发的 token。
## 场景三:本机 HTTP
如果 Federation 只需要被同一台机器上的可信进程访问,可以直接把标准 `fetch` handler 挂到你的本机 HTTP server:
```ts
import { Federation } from "@downcity/federation";
import { serve } from "@hono/node-server";
const base = new Federation({ database });
serve({
fetch: (request) => base.fetch(request),
hostname: "127.0.0.1",
port: 15315,
});
const federation_url = "http://127.0.0.1:15315";
```
然后 Embassy 可以直接连接这个 HTTP 地址:
```ts
import { Embassy } from "@downcity/federation";
const embassy = new Embassy({
federation_url,
admin_token: administrator_session_token,
});
await embassy.admin.list_services();
```
本机 HTTP 和远程 HTTP 使用同一套身份模型:Embassy Admin 使用管理员会话 Token,需要用户身份的 Action 仍然必须携带正常 `user_token`。
如果 `AccountsService` 配置了 `local_login: true`,`/v1/accounts/providers` 会只返回本地登录方式。调用 `POST accounts.login/start` 并传入 `provider: "local"`、明确的 `client_type` 与 `bureau_id`,保存返回的 `login_id` 和仅供发起端保管的 `login_secret`。`POST accounts.login/result` 携带两者只查询状态;完成后通过 `POST accounts.login/exchange` 携带两者及稳定随机 `exchange_id` 领取 `user_token`,再用该 Token(其中包含 `bureau_id`)创建或更新 Embassy User。交换请求发生网络错误时复用原 `exchange_id`。
### 官方 local-node 的本机边界
官方 `private/services/local-node` 启用 `local_login`,用于可信本机的免密码用户登录。监听地址只接受 `127.0.0.1`、`::1` 或 `localhost`;`PUBLIC_URL` 必须是相同端口的规范 HTTP(S) loopback Origin,默认 `http://localhost:3000`(端口由 `PORT` 决定)。不允许通配监听、公网地址或通过任意 DNS 名称访问本地服务。
宿主在分发登录、exchange、native route 和管理请求之前统一校验浏览器来源。请求同源、`PUBLIC_URL` 和 `DOWNCITY_LOCAL_ALLOWED_ORIGINS` 中的精确来源可进入;其他来源返回 403。额外来源用逗号分隔,例如 `http://localhost:5173,https://client.example.com`,默认留空。每项都必须是规范 HTTP(S) Origin,不带尾部 `/`、路径、查询、片段、凭据或显式默认端口;不接受 `*`、`null` 或需要 URL 规范化的输入。允许来源的 CORS 响应只返回该精确 Origin。
白名单页面可能获得本地免密码登录的普通用户能力,必须逐项确认可信。来源白名单不授予身份,各登录流程自身的同源与凭据规则仍然生效;管理员接口只接受真实管理员 Session,用户和 Bureau 凭据不能提升为管理员。正常无 `Origin` 的 CLI 请求可用;带有跨站 Fetch Metadata 的浏览器请求必须提供允许的 Origin。该边界不防止恶意本机进程伪造请求。
HTTP 请求没有凭据时保持匿名。节点启动时的 provider env 和 Bureau 初始化通过进程内 `trusted_identity` 完成,不向外部 HTTP 请求附加管理员身份。完整变量格式见[环境变量](/zh/city-sdk-docs/reference/env-vars#官方-local-node-的配置)。
## 为什么只传 Database Adapter
`@downcity/federation` 负责的是跨运行时都应该稳定的逻辑:
- service 生命周期
- action 路由
- token 鉴权
- city / env / store 基础设施
而具体宿主环境只负责创建对应 Adapter:
- Node.js 可以用 `@downcity/database-sqlite` 或 `@downcity/database-postgresql`
- Cloudflare Workers 可以用 `@downcity/database-d1`
- Federation 启动时会把需要的 env 写入内置 `env` 表
这就是为什么同一套 runtime 模型可以复用到不同宿主环境,而不是每换一个平台就重写一套后端。
## 默认 Storage
如果你的 Federation 需要把运行期产生的外部文件转存到自有存储,可以注册默认 storage:
```ts
import { Federation, R2Storage } from "@downcity/federation";
const base = new Federation({ database });
base.storage(R2Storage({
bucket: env.DOWNCITY_STORAGE,
public_url_prefix: env.DOWNCITY_STORAGE_PUBLIC_URL_PREFIX,
}));
```
注册后,service 可以通过 `ctx.storage` 访问这套能力。内置 AI 图片任务会在 `image_fetch` 成功后自动把远程 file part URL 转存到默认 storage;如果转存失败,会保留上游原始 URL,不会让图片任务失败。
## 常用 API / 入口
这一页最相关的 Federation API 是:
- `new Federation({ database })`:创建 Federation 实例
- `base.use(...)`:挂 service、AIService 和官方服务
- `base.storage(...)`:注册默认文件存储后端
- `base.fetch(request)`:处理单次请求
- `base.health()`:触发初始化并返回健康信息
- `base.table(name)`:拿某张表的受控数据接口
如果你是从“怎么写能力”进入,下一页更关键的是 [Service 与 Action](/zh/city-sdk-docs/packages/federation/service-and-action)。
## 常见误解
### Federation 是 runtime,不是整个 SDK
Federation 是服务端长期运行容器。产品侧真正调用它用的是 `City` 客户端,见 [Client SDK](/zh/city-sdk-docs/packages/federation/client)。
### Federation 不是纯 HTTP 代理
它背后还持有:
- 内置表
- token / city / env 基础设施
- service 数据层
- hook 生命周期
### Federation 不等于某一个 AI provider
provider、model、service、custom service 都只是 Federation 上挂载的能力,不是 Federation 本身。
## 继续阅读
- 想知道 Federation 里到底挂的是什么,读 [Service 与 Action](/zh/city-sdk-docs/packages/federation/service-and-action)
- 想知道服务和扩展点怎么进去,读 [Hook 与服务挂载](/zh/city-sdk-docs/packages/federation/hooks-and-service)
- 想知道数据层怎么落地,读 [Store 与 Table](/zh/city-sdk-docs/packages/federation/store-and-table)
- 想看更底层 API,再读 [Federation API](/zh/city-sdk-docs/reference/federation)
### Database Adapter
Source: https://downcity.ai/zh/city-sdk-docs/packages/federation/database-adapters/
Federation 不接收裸 Drizzle db。它接收一个继承自 `@downcity/federation` 的 `Database` 实例,由 Adapter 统一拥有 Driver、事务、DDL 与连接生命周期。
## SQLite
```bash
pnpm add @downcity/federation @downcity/database-sqlite
```
```ts
import { Federation } from "@downcity/federation";
import { Database } from "@downcity/database-sqlite";
const database = new Database({ filename: "./federation.sqlite" });
const federation = new Federation({ database });
```
本地测试可使用 `filename: ":memory:"`。文件数据库默认启用 WAL。
## Cloudflare D1
```bash
pnpm add @downcity/federation @downcity/database-d1
```
```ts
import { Federation } from "@downcity/federation";
import { Database } from "@downcity/database-d1";
export interface Env {
DB: D1Database;
}
export default {
async fetch(request: Request, env: Env): Promise {
const database = new Database({ binding: env.DB });
const federation = new Federation({ database });
await federation.health();
return federation.fetch(request);
},
};
```
D1 Adapter 使用读取快照、冲突重试和原子 `batch()` 提供与其他运行时一致的 `context.transaction()`。事务内后续读取可以看到尚未提交的插入、更新和删除。
## PostgreSQL
```bash
pnpm add @downcity/federation @downcity/database-postgresql
```
```ts
import { Federation } from "@downcity/federation";
import { Database } from "@downcity/database-postgresql";
const database = new Database({ url: process.env.DATABASE_URL! });
const federation = new Federation({ database });
```
PostgreSQL Adapter 使用 postgres-js 与 Drizzle 原生事务。
## Service 看到什么
普通 Service 通过 `context.table()` 和 `context.transaction()` 访问数据库。需要参数化 SQL 的官方 Service 只能使用受限的 `context.database.query()` / `atomic()`;不会拿到 D1 binding、better-sqlite3 connection 或 postgres-js client。
## 生命周期
`Federation` 拥有传入的 Database。服务关闭时调用:
```ts
await federation.dispose();
```
Adapter 会幂等释放自己拥有的连接;释放后的数据库操作会失败。
### Service 与 Action
Source: https://downcity.ai/zh/city-sdk-docs/packages/federation/service-and-action/
`Service` 和 `Action` 是 `@downcity/federation` 里最重要的业务组织单位。
先记一句话就够了:
> Service 是一组长期存在的业务能力,Action 是真正被调用的具体入口。
## 这个概念在说什么
你最终给产品暴露的,不是一个“随便写的 handler”,而是 City 里统一管理的一组 action。
每个 Action 同时承担四个角色:
- 业务入口
- HTTP 路由节点
- hook 作用点
- 权限边界
所以理解 Service / Action,本质上就是理解 Downcity City 如何组织业务能力。
## 什么时候应该写 custom service
- 你要表达的是产品业务动作,而不是单纯模型推理
- 你要让前端、App、服务都走统一的业务入口
- 你希望一个能力能被 hook、鉴权、usage 和服务治理
典型例子:
- 改写内容
- 生成报告
- 执行工作流
- 处理上传后的业务逻辑
## 什么时候更适合先用 AIService
如果你只是想提供这些 AI 能力:
- `text`
- `stream`
- `image`
- `video`
优先从 `AIService` 开始会更自然,因为它已经替你处理了模型目录和 AI 输出约定。
## 最小 custom service 示例
```ts
import { Federation, Service } from "@downcity/federation";
const base = new Federation({ database });
const translate = new Service({
id: "translate",
name: "翻译",
});
translate.action("zh2en", async (ctx) => {
return {
text: await runTranslate(String(ctx.input.text ?? ""), "en"),
};
});
translate.action("list", async () => {
return {
items: ["zh2en"],
};
}, {
method: "GET",
});
base.use(translate);
```
这里你做了三件事:
1. 创建一个 service
2. 往里面注册多个 action
3. 把整个 service 挂到 City
## 路由会怎么暴露
上面的 Action 会自动进入统一路由空间:
```txt
POST /v1/translate/zh2en
GET /v1/translate/list
```
这也是为什么产品端最后统一都能通过 `@downcity/federation` 调:
```ts
const result = await client
.service("translate")
.action("zh2en")
.invoke<{ text: string }>({
text: "你好 Downcity",
});
const list = await city.service("translate").get("list");
```
## 常见场景
### 场景一:产品业务 Action
```ts
const writer = new Service({ id: "writer", name: "内容写作" });
writer.action("draft", async (ctx) => {
return {
title: "Draft",
topic: ctx.input.topic,
};
});
```
适合:
- 业务工作流
- 自定义生成结果
- 你自己的 SaaS 能力
### 场景二:管理侧 Action
```ts
writer.action("remove", async (ctx) => {
await removeDraft(String(ctx.input.id));
return { ok: true };
}, {
auth: ["admin"],
});
```
适合:
- 只能由可信后端执行的动作
- 运维、删除、配置变更
### 场景三:guest 入口
```ts
writer.action("webhook", async (ctx) => {
await verify_webhook(ctx.raw_body ?? "");
return { accepted: true };
}, {
auth: [],
body: "raw",
});
```
适合:
- 第三方 webhook
- 登录前入口
- 回调型 Action
## AIService 和普通 Service 的关系
AIService 不是另一套协议,而是 City 里一类更偏 AI 的 service。
它额外提供:
- 模型目录
- 多 modality 调用
- OpenAI 兼容入口
- 更适合 `UIMessage` / stream 的返回约定
所以你可以这样区分:
- 直接模型推理:优先 `AIService`
- 业务动作或服务动作:优先 `Service`
## Action 请求体模式
`service.action(name, handler, options?)` 支持可选 `body: "json" | "raw"`。POST Action 默认 `"json"`:空体或纯空白解析为 `{}`,非空体必须是 JSON 对象。无效 JSON 返回 `400 INVALID_JSON`;数组、`null` 和其他 JSON 基础类型返回 `400 INVALID_INPUT`;请求体读取失败返回 `400 INVALID_BODY`。GET Action 从 query 读取参数。
Webhook 验签或其他文本协议使用 `body: "raw"`。普通 Action 通过 `ctx.raw_body` 读取原始文本,`ctx.input` 初始为 `{}`。Installable Service 的 `ctx.route({ method, path, body?, handler })` 同样支持可选 body 模式,仅适用于 Action handler。该路由 handler 内的 `ctx.text()` 返回原始文本,`ctx.json()` 则按需严格解析 JSON 对象,空体或纯空白返回 `{}`。
Installable 原生路由使用 `handler: { request }`,正文同样由 HTTP 边界有界读取一次,再按原始字节重建 Request,不进行 Action JSON 解析。`body` 仅为 Action 选项。原生 OAuth 的 form 提交、回调和 redirect 按各自协议处理。正文额度、读取超时和编码校验同样适用于原生路由,见 [HTTP API](/zh/city-sdk-docs/reference/http-api#http-边界与默认限额)。
## 请求上下文与错误
HTTP Action 的 `ctx.request_id` 与 `ctx.locals.request_id` 包含服务端在 HTTP 边界、middleware 前生成的 `req_`,与响应头 `x-request-id`、Router 和 AI relay 的请求 ID 一致;忽略调用者提供的 ID。普通 HTTP 的 middleware 短路以及 413、408、504 响应也携带该 ID。HTTP 101 upgrade 不重新包装或托管,也不保证 `x-request-id` 响应头。
Action `Context.abort_signal` 与 Installable `ServiceRouteContext.abort_signal` 可读,原生 handler 可使用 `request.signal`。Adapter 应合并请求取消和自身 deadline,上游较短期限仍生效。客户端取消对应 `499 REQUEST_CANCELLED`,断开后不能保证收到响应。取消为协作式中断,数据库操作可能继续,不表示事务撤销,也不触发自动重试;已入队图片 task 不继承前台请求取消。
框架捕获的抛错统一返回 `error: { code, message, type, request_id }`。明确的 4xx `httpError` 保留 message,所有 5xx 使用通用 message。显式整数 `statusCode` 为 400–599 且 `code` 匹配 `^[A-Za-z][A-Za-z0-9_]{0,63}$` 时保留领域码,包括 `503 async_dispatch_unavailable`。缺失或无效的状态码一律成为 `500 INTERNAL_ERROR`,不使用附带的 code。默认码与消息见 [HTTP API](/zh/city-sdk-docs/reference/http-api#框架错误)。
业务与 native handler 直接返回的错误 Response 由业务负责正文,HTTP 边界仍覆盖 `x-request-id`。框架不整体缓冲响应 body 或 SSE;流开始后的边界超时或取消会 abort 下游并取消 reader、结束流,不能改写 HTTP 状态或返回 JSON 错误,也不构造通用 SSE 错误帧。`onError` hook 自身失败不会覆盖原始错误。
模型层使用服务端 `AIServiceOptions.model_stream?: Partial`,默认首有效输出 120 秒、idle 120 秒、总执行 15 分钟,原生模型流、OpenAI SSE / JSON 和 Relay 的所有语言模型执行共用策略;客户端不能通过请求抬高期限。首输出累计等待 provider open 和实际 read,idle 累计有效输出之间实际等待 read;背压期间不累计首输出或 idle,总墙钟持续计时。HTTP SSE 总期限从请求正文读完起算,模型总期限从 provider 执行起算;两层独立,provider 更短期限及 HTTP 同步默认 180 秒仍生效,取先到期的一层。
模型超时 abort 同一次前台执行,不透明重试。Provider open 未返回时抛出 504,如 `MODEL_FIRST_OUTPUT_TIMEOUT` 或 `MODEL_EXECUTION_TIMEOUT`;idle 使用 `MODEL_IDLE_TIMEOUT`,Router 保留合法领域码并使用安全 message。原生 Response 已开始时由模型 transport 补 `model_error`(`provider_timeout`、`status_code: 504`、`retryable: false`),说明首输出超时、输出停滞或总执行超时;缺少 provider `model_start` 时可补框架 `model_start` 以满足失败终态协议,不伪造 usage。OpenAI SSE 发 error 帧,失败不发成功 `[DONE]`;JSON 聚合超时返回 504。SSE 已开始后保持 HTTP 状态,这些模型错误帧由模型层负责。
结束或取消释放 timer、listener 和 reader,不等待可能无限挂起的上游 cancel。可信 usage 事实会保留,未返回 usage 不估算 token 或费用;既有 `bill` 按实际 facts 执行,具体收费由业务决定,不承诺缺少 usage 就永远零收费。`completion.outcome` 明确为 `succeeded`、`failed`、`cancelled`,终态后 cancel 不误记取消或超时,不重复结算或扣费。底层 SQL 副作用不能保证回滚。有效输出和完整策略见 [调用模型](/zh/city-sdk-docs/service/ai/calling#模型执行期限)。
## 常用 API / 入口
这一页最相关的调用入口有:
- `new Service({ id, name })`
- `service.action(name, handler, options?)`
- `options.method?: "GET" | "POST"`
- `options.body?: "json" | "raw"`(POST 默认 `"json"`)
- `options.auth: ["user"] | ["admin"] | []`
- `base.use(service)`
- `city.service(id).action(name).invoke(input)`
- `city.service(id).get(path, query?)`
## 常见误解
### Action 不只是一个函数
它最终会成为:
- HTTP 路由
- 鉴权边界
- hook 作用点
- usage 记录点
### service 和 custom service 不需要两套调用方式
对产品端来说,它们最终都统一走:
```ts
city.service("service_id").action("action_id").invoke(...)
```
### GET / POST 的差别不是语法装饰
读操作更适合 GET,例如:
- `me`
- `list`
- `summary`
写操作、执行动作更适合 POST,例如:
- `login`
- `draft`
- `checkout/create`
## 继续阅读
- 想知道 hook 和 service 怎么围绕 Action 工作,读 [Hook 与服务挂载](/zh/city-sdk-docs/packages/federation/hooks-and-service)
- 想知道产品端怎么调用这些能力,读 [@downcity/federation](/zh/city-sdk-docs/packages/federation/federation)
- 想看更底层 API 选项,读 [City API](/zh/city-sdk-docs/reference/federation)
### Hook 与服务挂载
Source: https://downcity.ai/zh/city-sdk-docs/packages/federation/hooks-and-service/
Downcity 很多共享能力不是靠“把代码复制到每个 service 里”完成的,而是通过 hook 和 service 进入 City。
## 这两个概念分别在解决什么
可以先这样分工:
- hook:给已有调用链插入规则
- service:给 City 增加一整组长期复用能力
所以你看到的 usage、账号、支付,并不是“额外开一套系统”,而是作为扩展点进入同一套 Federation。
## 什么时候该先想 hook
- 你想在某类调用前后加规则
- 逻辑是横切的,不想写进每个 action
- 能力只在当前项目里使用,不一定要独立成 package
典型例子:
- 额度判断
- 日志记录
- 风控校验
- 调用后扣减余额
## 什么时候更适合做 service
- 能力需要跨多个产品复用
- 不只是前后置逻辑,而是一整组 service / 表 / 管理入口
- 你希望产品侧能长期通过统一 service 调它
典型例子:
- `@downcity/services`
- `@downcity/services`
- `@downcity/services`
## 先理解 hook 的三层位置
```txt
global
-> service
-> action
```
含义分别是:
- global:所有 service / action 共享
- service:某个 service 下所有 action 共享
- action:只对一个具体 action 生效
这三层不是为了增加复杂度,而是为了让你把规则放在最合适的位置,而不是一股脑写死到业务函数里。
## 最常见的 service 挂载示例
```ts
import { AIService, Federation } from "@downcity/federation";
import {
AccountsService,
CreditsService,
PaymentService,
googleAccountsProvider,
stripePaymentProvider,
UsageService,
} from "@downcity/services";
const base = new Federation({ database });
const credits = new CreditsService();
const ai = new AIService({ credits });
base.use(new AccountsService({
token_ttl: "7d",
providers: [
googleAccountsProvider(),
],
}));
base.use(credits);
base.use(ai);
base.use(new PaymentService({
resolve_topup: ({ topup_amount_minor }) => ({ credits: topup_amount_minor * 10_000 }),
on_paid: async (record) => {
await credits.topup({
card: { kind: "primary", user_id: record.user_id },
credits: record.credits,
source: "payment",
ref: record.payment_id,
idempotency_key: `payment:${record.payment_id}`,
});
},
providers: [
stripePaymentProvider({
secret_key: process.env.STRIPE_SECRET_KEY,
webhook_secret: process.env.STRIPE_WEBHOOK_SECRET,
}),
],
}));
base.use(new UsageService({
ai_usage_reader: ai,
credits_usage_reader: credits,
}));
```
这段代码背后的意思是:
- `new AccountsService()` 给 City 增加 `accounts` service 容器
- `AccountsService` 会自动挂载 `/providers`、统一登录入口、`me`、管理侧读取、better-auth passthrough 与 OAuth callback 入口;具体登录方式只有在对应 provider 挂载且配置满足后才会开放
- `new PaymentService()` 给 City 增加统一支付入口,用来暴露当前可用的支付方式
- `new UsageService(...)` 聚合 `AIService` 技术用量与 `CreditsService` 已入账消费,并提供当前用户查询入口
- `stripePaymentProvider()` 给统一 Payment 服务增加 Stripe Checkout、webhook 和支付结果同步
## service 挂进来后产品端怎么调
从产品视角看,service 最终会变成统一 service:
```ts
const login = await guest.service("accounts").action("login/start").invoke({
provider: "email",
client_type: "cli",
bureau_id: "demo",
});
await guest.service("accounts").action("login/continue").invoke({
login_id: login.login_id,
login_secret: login.login_secret,
input: {
email: "user@example.com",
password: "password123",
},
});
const status = await guest.service("accounts").action("login/result").invoke({
login_id: login.login_id,
login_secret: login.login_secret,
});
// 邮箱须先验证;交换请求发生网络错误时复用该 ID。
const exchange_id = crypto.randomUUID();
if (status.status !== "done") throw new Error("登录尚未完成");
const session = await guest.service("accounts").action("login/exchange").invoke({
login_id: login.login_id,
login_secret: login.login_secret,
exchange_id,
});
const usage = await user.service("usage").get("me", {
from: "2026-08-01",
to: "2026-08-31",
timezone: "Asia/Shanghai",
});
const recent_usage = await user.service("usage").get("me/recent", {
limit: 20,
});
const methods = await guest.service("payment").get("methods");
const checkout = await user.service("payment").action("checkout/create").invoke({
method_id: "stripe",
topup_amount_minor: 500,
idempotency_key: "order_123",
});
```
也就是说,service 并不会让产品端学第二套调用协议。
## hook、service 的关系
可以把它们想成一条链:
```txt
service / action
-> hook 在调用前后加规则
-> service 提供可复用 service、表和管理能力
-> client 统一通过 /v1/* 调用
```
这条链的好处是:
- 业务能力能复用
- 规则能集中治理
- 前端和后端的调用模型保持统一
## 常用 API / 入口
这一页最常用的公共入口其实很简单:
- `base.use(service)`:把 service 挂进 City
- `guest.service("accounts")...`
- `guest.service("payment").get("methods")`
- `user.service("usage")...`
- `admin.service("payment").get("payments")`
如果你是从扩展角度思考,最重要的不是记很多 API,而是先判断“这是 hook 问题还是 service 问题”。
## 常见误解
### service 不是单纯的 npm 包
它代表的是一整组进入 City 的能力边界,通常还伴随:
- service
- 数据表
- 管理接口
- 可选 hook 逻辑
### hook 不等于随便加中间件
hook 适合放横切治理逻辑,不适合把整个业务动作都塞进去。
### service 不替代 City
service 负责把能力挂进 City,真正的产品调用入口仍然是 [@downcity/federation](/zh/city-sdk-docs/packages/federation/federation)。
## 继续阅读
- 想看 city 端怎么统一调用 service,读 [@downcity/federation](/zh/city-sdk-docs/packages/federation/federation)
- 想看账号能力,读 [@downcity/services](/zh/payments)
- 想看 usage 记录,读 [@downcity/services](/zh/payments)
- 想看 Stripe 一次性充值,读 [@downcity/services](/zh/payments)
### Store 与 Table
Source: https://downcity.ai/zh/city-sdk-docs/packages/federation/store-and-table/
Downcity 最常被看见的是 AI 调用,但它能长期稳定运行,靠的是一套明确的数据层。
## 这个概念在说什么
很多 Federation 能力都不是纯内存状态,它们最终都必须落到数据事实:
- city 是否 active
- 某个 token 属于谁
- 某个 env key 当前值是什么
- 某次 service 调用是否已记录 usage
- 某个用户是否已经拿到 entitlement
这就是为什么 `@downcity/federation` 里不仅有 HTTP 路由,还有 store / table 这一层。
## 什么时候你需要直接关心这一层
- 你在排查 service 有没有真的写表
- 你要把 Federation 数据和自己的业务表联动
- 你想从代码里读写某些受控表
- 你在做运维排查,不想只看 HTTP 返回
## `base.table()` 代表什么
`base.table(name)` 不是“随便暴露数据库”,而是 Federation 对底层数据库能力的受控暴露。
它给你的不是随意 SQL 字符串,而是围绕 Federation 生命周期统一管理的表接口。
## 最小示例:读写 Federation 表
```ts
const cities = await base.table("cities");
const env = await base.table("env");
const notes = await base.table("notes.notes");
await notes.insert({
id: "note_1",
title: "First note",
status: "draft",
});
const draftNotes = await notes.select({
status: "draft",
});
```
这段代码说明三件事:
1. Federation 内置表可以直接拿
2. 你自己的 service 表也可以通过统一入口拿
3. 数据操作最终受 runtime 和 City 生命周期治理
## 你通常会碰到哪些表
### Federation 内置表
- `cities`
- `env`
它们支撑的是:
- 产品状态
- 运行时环境变量
- Federation 的管理基础设施
### service 表
不同 service 会带自己的表,例如:
- accounts 相关用户 / session 表
- usage 事件表
- Stripe entitlement / webhook 事件表
### 你自己的业务表
如果你在 service 里定义了业务表,也会进入同一个统一 runtime 数据层。
## 常见场景
### 场景一:确认数据到底有没有落进去
```ts
const usageEvents = await base.table("service_usage_events");
const rows = await usageEvents.select();
```
这类场景常见于:
- usage 为什么看起来没记上
- Stripe webhook 进来了没有
- 账号注册后表里有没有数据
### 场景二:程序里做受控更新
```ts
const envTable = await base.table("env");
await envTable.update({
where: { key: "OPENAI_API_KEY" },
values: { value: "new-secret" },
});
```
适合:
- 可信环境里的受控维护
- 内部脚本
- 管理后台后端逻辑
### 场景三:删除或清理某类数据
```ts
const notes = await base.table("notes.notes");
await notes.delete({ id: "note_1" });
```
适合:
- 业务清理
- 测试环境重置
- 服务联动逻辑
## 常用 API / 入口
这一层最重要的 API 很少:
- `await base.table(name)`
- `table.select(where?)`
- `table.insert(values)`
- `table.update({ where, values })`
- `table.delete(where)`
如果你想看更底层方法签名,去读 [Runtime API](/zh/city-sdk-docs/reference/runtime-api) 和 [City API](/zh/city-sdk-docs/reference/federation)。
## 常见误解
### Federation 不只是 API 代理
它后面还有长期存在的数据层,很多管理能力都建立在这些表上。
### `table()` 不是让你跳过 Federation 设计
更推荐先通过:
- service
- service
- Embassy Admin
来表达业务入口;`table()` 更适合可信环境和受控排查。
### 不是所有表都应该直接给前端碰
前端产品应该继续走 `Embassy User` / `Embassy Admin`,而不是直接访问底层表。
## 继续阅读
- 想知道数据库是怎么接进来的,读 [Federation](/zh/city-sdk-docs/packages/federation/federation)
- 想在终端里查这些表,读 [CLI](/zh/city-sdk-docs/packages/cli)
- 想看 service 会落哪些表,结合对应 package 页一起读
### HTTP 与 RPC
Source: https://downcity.ai/zh/city-sdk-docs/packages/city/transport/
`City` 统一拥有一个 HTTP transport 和一个 RPC transport。两个端口都按 `agent_id`
路由到同一组 Agent,并通过 `workspace_id` 选择 City 持有的 Workspace;Session 仍由 Agent 创建。
```ts
await city.listen({
http: { host: "127.0.0.1", port: 5314 },
rpc: { host: "127.0.0.1", port: 15314 },
});
await city.close(); // 只关闭 transport;Agent 仍由创建它的宿主释放
```
如果需要分别控制生命周期,也可以直接启动 City 的单个 transport:
```ts
const http = await city.http({ host: "127.0.0.1", port: 5314 });
const rpc = await city.rpc({ host: "127.0.0.1", port: 15314 });
```
HTTP 地址是 `http://host:port/agents//workspaces/`,RPC 地址是
`rpc://host:port//`。不再提供 Agent 级 transport 构造器,外部服务统一属于 City。
### @downcity/city/local
Source: https://downcity.ai/zh/city-sdk-docs/packages/local/
`@downcity/city/local` 提供 CLI 与 Desktop 共用的本地宿主能力,包括 SQLite Adapter、
路径、产品 Schema、Repository、环境装配与 Power Loader。
```ts
import {
LocalDatabase,
AgentRepository,
WorkspaceRepository,
ensure_local_schema,
} from "@downcity/city/local";
const database = new LocalDatabase({ filename: database_path });
ensure_local_schema(database);
const workspaces = new WorkspaceRepository(database);
const agents = new AgentRepository(root_path);
```
CLI 与 Desktop 在各自组合根中创建这些依赖,读取配置后显式调用 `new Agent()`。
该 local 子入口不创建 Agent、Workspace、Model 或 City。
Workspace 与平台设置以明文 JSON 保存,依靠本地数据库文件的 `0600` 权限进行用户级隔离。
### CLI 快速开始
Source: https://downcity.ai/zh/city-sdk-docs/packages/cli/quickstart/
`downcity` 包会安装两组命令:
- `fed` / `downfed`:管理和部署 Federation。
- `city` / `downcity`:管理本机 Agent、本地 Power、chat/gateway,以及当前本机登录到哪个 Federation。
## 安装
```bash
npm i -g downcity
```
查看版本:
```bash
fed -v
city -v
```
## 管理 Federation:用 fed
当你要创建、部署或管理共享后端时,使用 `fed`。
```bash
fed
fed create
fed create --path ./edge-fed --template cloudflare-workers
fed create --path ./custom-fed --template git://example.com/custom-fed.git
fed deploy
fed deploy --dry-run
fed deploy --verify
```
`fed create` 和 `fed deploy` 默认使用 `--path .`。其他目录必须通过 `--path ` 指定,例如 `fed deploy --path ./edge-fed`,不接受位置路径参数。
`fed create` 默认生成 Local Node.js + SQLite 项目。`--template` 可以选择 `cloudflare-workers` 或 Git 模板。项目身份和部署方式统一写在 `federation.toml` 中。Federation 项目配置只支持 TOML,不兼容 JSON 配置。
`fed deploy` 表示部署当前项目,不区分本地与云端。本地目标未设置 `deployment.port` 时固定使用默认端口 `12314` 并启动受管进程,显式设置 `deployment.port` 可覆盖默认值。选定端口被占用时,交互终端会展示占用进程的 PID、启动时间、命令和工作目录,并标明是否属于当前项目,询问是否停止后继续部署(默认否)。确认后 CLI 重新核对进程身份,发送 `SIGTERM` 并最多等待 5 秒释放端口,不自动强制终止。非交互终端、无法核实进程身份或端口未释放时部署失败;`--yes` 不跳过停止进程的确认。进程检查需要系统提供 `lsof` 和 `ps`。CLI 不扫描其他端口,也不从部署历史推断端口。首次部署时 CLI 交互式设置管理员 ID 和密码,后续普通部署复用现有管理员。重复部署同一 `fed_id` 时会用最新代码替换旧实例,不会修改管理员。Cloudflare Workers 目标会准备 D1、Queue 和 R2,再发布 Worker,并通过管理员登录创建有期限的 Session Token 保存到本地 registry。
管理已部署 Federation:
```bash
fed server add
fed server --id fed_x
fed manage --id fed_x
fed server manage --name my-fed
fed web --id fed_x
fed status --id fed_x
fed logs --id fed_x
fed stop --id fed_x
fed restart --id fed_x
fed clean --id fed_x --dry-run
fed clean --name my-fed --yes
fed query GET /health --id fed_x
fed query GET /v1/ai/models --id fed_x
fed query POST /v1/ai/image/result --id fed_x --data '{"job_id":"..."}'
fed bureau token --id fed_x list
```
所有 Federation URL、管理员 ID、管理员 Session Token、本地 PID、端口、日志和部署状态都保存在系统级 Federation registry,不依赖当前路径。Fed 没有全局 active/default Federation,也不保存 `active_server_url`;部署只登记或更新实例。列表没有表示全局当前连接的星标。
`stop`、`restart`、`clean`、`status`、`logs`、`query`、`web`、`server`、`manage` 与 `server manage` 使用互斥的 `--id ` 或 `--name `,ID 和名称均精确匹配。省略选择参数时,TTY 显示列表,选择只用于本次操作;非交互环境缺少参数时报错。名称重名时,TTY 继续选择,非 TTY 报错。`fed manage` 直接进入目标管理工作区,不接受 action 位置参数。Bureau Token 命令遵循相同的目标规则,选择参数也可放在 `token` 父命令上,如上例所示。`fed query` 在存在有效管理员 Session 时自动携带 `Authorization: Bearer`,Session 失效后要求重新登录。
`fed status` 对已保存连接分别展示 registry record、系统 manager 事实与 `/health` 实时探测;本地实例另展示发布历史。登记状态、保存的策略和发布结果都不证明服务已停止或某个 release 正在运行。本地 release 只有在 manager 核对实例身份,且健康响应为 `ok: true`、`fed_id`、`release_id`、`instance_id` 全部匹配时才显示 ready;HTTP 200 本身不足以确认身份。manager 检查异常显示 `unknown`,需要人工检查系统服务与健康端点。
`logs`、`stop` 和 `restart` 仅支持 CLI 管理的 local 实例。`logs` 显示当前 `service.log` 末尾最多 200 行,不跨文件补足;归档可人工读取。`stop` 禁用自动启动并停止服务,停止状态跨系统重启保留,直到用户显式执行 `fed deploy` 或符合恢复保护要求的 `fed restart`;这些操作会按持久配置恢复自动启动策略。`restart` 只运行已安装产物并读取持久运行配置,不读源码、不重新构建,原项目删除后仍可重启。重启前还会检查 `current.json` 必须与 registry 的 release 一致。没有待恢复切换时,build/package/preflight 失败仍允许 restart 原成功 release。进入切换后设置 `recovery_required = true`;切换失败或中断时阻断 restart,必须显式执行 `fed deploy` 并成功才能恢复。此保护持续到发布成功,后续 build/preflight 失败也不会清除。历史 `last_failure` 本身不构成阻断。管理界面的 Remove connection 只移除连接,不停止服务。
## 本地独立 Node 发布
编译后的入口、完整生产依赖及项目资源安装到 `~/.downcity/federation/deployments//releases/`,同级 `current.json` 是成功激活指针,不代表该 release 当前正在运行。运行配置位于 `~/.downcity/federation/config//runtime.env.json`,文件权限为 `0600`;默认 SQLite 位于 `~/.downcity/federation/data/