Custom Power
Build a custom Power with Actions, Hooks, System, Lifecycle, and a City module.
Custom Power contracts come from @downcity/city/power. City owns one Power instance per Power ID
and automatically exposes every registered Power to every Agent.
import {
Power,
create_action,
} from "@downcity/city/power";
class NotesPower extends Power {
readonly name = "notes";
readonly title = "Notes Helper";
readonly description = "Adds note-related actions.";
readonly actions = {
status: create_action({
execute: async ({ context }) => ({
success: true,
data: {
workspace_path: context.workspace.path,
storage_path: context.storage.path,
session_id: context.session?.id ?? null,
},
}),
}),
};
}
const city = new City({ powers: [new NotesPower()], workspaces: [workspace] });
city.agents.add(agent);Use city.powers.prepare(inputs) when an entire batch must initialize before any tools or catalog entries become visible. initialize() keeps the batch private; publish() publishes it synchronously. On failure, dispose() releases all adopted instances using the same lifecycle contexts, including instances that have not initialized.
const batch_city = new City();
const batch = batch_city.powers.prepare([new NotesPower()]);
try {
await batch.initialize();
batch.publish();
} catch (error) {
await batch.dispose();
throw error;
}
// City retains resource ownership after publication and releases them on close.Implement only the Actions, Hooks, Resolves, System, Availability, HTTP, or Lifecycle behavior the
domain actually needs. Use initialize/dispose for Power-owned resources and derive any internal
resource key from real domain ownership, not Workspace entry. Do not hide long-lived resources inside Hooks.
Use context.power.background(async () => { ... }) through the lifecycle context saved by initialize(context) for work that continues across requests. Work runs only after the Power is ready and retains its execution lease until its actual Promise settles. Reload or removal reports busy while it runs. Unregistered detached timers are not tracked work.
Hosts can provide Agent's acquire_execution constructor callback to synchronously obtain a lease covering input initialization, queuing, and the full Turn. Completion or failure releases it; reading history does not invoke it. agent.reconfigure_behavior(behavior) replaces complete behavior only while idle, preserving identity and history and invalidating old runtime handles. Retrieve existing Sessions again by their original IDs.
See Power Development for the complete module, manifest, Context, and testing model.
Activity renderer
Register activity in the browser renderer to control an action's title, optional target summary, and expandable details. It is independent of the view slot that publishes content directly in a reply.
/** Browser-only activity renderer. */
import {
define_power_renderer,
type PowerActivityProps,
type PowerActivityDescription,
} from "@downcity/city/power/react";
/** Read only explicit fields from the Notes action result. */
function note_text({ tool }: PowerActivityProps): string {
const result = tool.output as { /** Action business result. */ data?: { /** Saved note text. */ text?: unknown } } | undefined;
return typeof result?.data?.text === "string" ? result.data.text : "";
}
/** Describe without constructing the detail body or executing an action. */
function describe_note(props: PowerActivityProps): PowerActivityDescription {
const { tool, locale } = props;
const zh = locale.startsWith("zh");
return {
title: zh ? "笔记操作" : "Note operation",
tone: tool.state === "failed" ? "failed"
: tool.state === "waiting-user" ? "waiting"
: tool.state === "completed" ? "complete" : "running",
has_detail: Boolean(note_text(props)),
};
}
/** Mounted by React only while the activity is expanded. */
function note_detail(props: PowerActivityProps) {
return <pre>{note_text(props).slice(0, 4096)}</pre>;
}
export default define_power_renderer({
activity: { describe: describe_note, detail: note_detail },
});PowerActivityProps contains the read-only canonical tool snapshot and current locale. The Power call input uses { action, args }; its result wraps business data in output.data. Interpret your own action's exact contract, including business failure or background processing, rather than equating tool completion with business success.
describe is a synchronous pure function. Return a nonempty text title, optional text summary, tone (running, waiting, complete, or failed), and has_detail. It must not call Hooks, fetch data, execute actions, or format full output. detail is an optional React component and may use Hooks; do not execute an action just by opening a historical record. Details need a registered component and has_detail: true. Different actions in the same Power can have different expansion behavior.
The host owns icons, activity groups, status styling, expansion state, and error isolation. Group summaries stay plain text. Details mount on expansion and unmount on collapse; bound large previews in your component. Canonical failure and waiting states take priority over conflicting custom descriptions. A missing or invalid slot falls back to a lifecycle-only row without raw-output expansion. A detail rendering error affects only that activity.
An activity-only renderer needs no Sidebar/Mainview capability flags. Keep it in the Power's standard browser renderer entry; it receives no extra execution gateway or secret access. view and preview own published content and its deduplication.
Background input rendering
The optional input slot is independent of activity. describe({ input, locale }) returns a title, optional summary, tone, and has_detail, or null to hide an internal event. Its detail component mounts only while expanded and receives the same snapshot plus the host's safe Markdown render_text and attachment render_file ports. It receives no execution gateway.
The host routes exact producer kinds and tags: Session owns delegation_result, Shell owns shell_result, and power_result uses power_id from its matching context envelope. Interpret only your Power's explicit producer contract. Do not guess JSON from arbitrary text or display source identifiers, machine envelopes, or internal Agent instructions. Keep events without a body on one line; return null for routine internal maintenance. Hiding UI leaves canonical input, ordering, and delivery identity intact.
Maintain complete localized sentences for each action and distinguish submission, queuing, processing, and results using its business receipt. A locale change reprojects the same snapshot without a model translation call. Search and list actions stay on one line; useful bodies use bounded previews. PowerActivityProps may also provide render_text and render_file; use safe plain text when a standalone host omits these ports.
View content
An Action publishes a SessionViewContent in its returned messages to add structured display content to the reply. Set type: "view", the providing power_id, a positive schema_version, serializable data, and nonempty fallback_text. The runtime adds Part identity and source_tool_call_id; the source association prevents a completed tool call and its published content from appearing twice.
The browser renderer's view component receives PowerViewMessageComponentProps. Validate the version and your data contract before rendering. fallback_text provides a readable result when the renderer is unavailable. The view reply slot is distinct from views, the list of independent business pages opened through ui.open_view.
/** Read-only Notes reply view. */
import { define_power_renderer, type PowerViewMessageComponentProps } from "@downcity/city/power/react";
/** Render the Notes view contract; mismatched data uses the text fallback. */
function notes_view({ part }: PowerViewMessageComponentProps) {
const data = part.data as { /** User-readable note body. */ text?: unknown } | null;
const text = part.schema_version === 1 && typeof data?.text === "string"
? data.text : part.fallback_text;
return <p>{text}</p>;
}
export default define_power_renderer({ view: notes_view });