Power Hooks and Resolve

Use one overview page to distinguish pipeline, guard, effect, and resolve before going deeper

This area is easy to misunderstand because:

  • all four live inside power definitions
  • all four look like "register a function"
  • but their runtime semantics are very different

If you only remember one line, start here:

  • pipeline: rewrite a value
  • guard: block a flow
  • effect: run side effects
  • resolve: produce one authoritative answer

Start with the comparison

TypeWho triggers itReturns a valueMultiple handlers allowedWhat failure meansBest fit
pipelinehost code calls ityesyesthrows and stops the current callprogressively transform one value
guardhost code calls itnoyesany thrown error blocks the flowpre-checks and authorization
effecthost code calls itnoyesany thrown error stops the current effect calllogging, analytics, syncing
resolvehost code calls ityesno, exactly onemissing, duplicate, or disabled resolution failsprovide one final answer

The most important thing to remember

Declaring a hook inside a power does not make it run automatically.

What actually happens is: host code explicitly calls a named point at a specific time.

For example:

const value = await city.powers.scope({ agent_id: agent.id, workspace_id: workspace.id }).pipeline("chat.enrich_message", input);
await city.powers.scope({ agent_id: agent.id, workspace_id: workspace.id }).guard("review.require_checked", value);
await city.powers.scope({ agent_id: agent.id, workspace_id: workspace.id }).effect("audit.observe", value);
const role = await city.powers.scope({ agent_id: agent.id, workspace_id: workspace.id }).resolve("auth.resolve_role", {
  userId: "owner",
});

So the clean mental split is:

  • the power defines an extension point handler
  • the host decides when that extension point executes

If the host never calls that point, the hook never runs.

Hooks are declared by Power instances and dispatched by the City-owned Registry for the current Agent/Workspace scope. A Session captures one execution lease at each checkpoint, so the call observes a stable Power set; concurrent unbinding waits for active leases to finish.

Inside a Power, context.city.powers exposes only pipeline(), effect(), and run_action() for collaboration. guard and resolve remain host-control and authority surfaces and are called from host execution entries such as city.powers.scope({ agent_id: agent.id, workspace_id: workspace.id }).

Why resolve deserves separate attention

Many readers naturally treat resolve as just another hook flavor.

But it is really closer to:

  • an authority point
  • a "who gives the final answer?" question

That is why it differs from the other three:

  • the first three allow several powers to participate
  • resolve allows exactly one power to be the final authority

This is also why:

  • duplicate registration for one resolve point throws
  • missing resolvers throw
  • a disabled resolver power also causes failure

Live execution state

session.execution_state is a transient effect checkpoint. Its value contains session_id, turn_id, and state: running when the model and tool execution loop starts, and idle when it exits. Waiting for child work is idle; execution emits running again when it resumes. Later execution triggered by background results follows the same rules.

Use this checkpoint for lightweight live feedback such as typing indicators. Events are not persisted or replayed and do not require a handler_id. Handlers should return promptly, move network requests into cancellable background work, and release resources using the current Turn's abort signal. Handler failures do not change the execution result. Telegram Messenger uses this checkpoint to maintain its typing heartbeat.

Callbacks after a Session Turn finishes

Agent automatically emits session.turn_committed when a Turn completes, fails, or stops. The Session remains available for later input.

Register an application callback through AgentOptions.hooks:

import { Agent, SESSION_HOOK_POINTS, type SessionTurnCommittedHookValue } from "@downcity/agent";
import type { JsonValue, ToolCallContext } from "@downcity/type";

const agent = new Agent({
  id: "reviewer",
  model,
  hooks: {
    pipeline: {},
    guard: {},
    effect: {
      [SESSION_HOOK_POINTS.turn_committed]: [Object.assign(async (value: JsonValue, context: ToolCallContext) => {
        const event = value as unknown as SessionTurnCommittedHookValue;
        await result_outbox.enqueue({
          idempotency_key: event.completion_id,
          session_id: context.session_id,
          turn_id: event.turn_id,
          status: event.status,
          text: event.result.text,
        });
      }, { handler_id: "report_outbox" })],
    },
  },
});

result_outbox is an application-provided delivery port. Events also include result.success, optional result.error, and canonical messages for the Turn. Select behavior using context.session_descriptor and persisted business references; retain each request's destination separately.

Before closing the Turn's canonical messages, Agent saves its result and recipient identities in a private write-ahead journal. A journal write failure rejects turn.finished and leaves recoverable state rather than acknowledging success. If the process stops after journaling but before finalization, recovery reuses the saved result; submitting the same request_id does not run the model again. A fulfilled turn.finished does not acknowledge callback completion or external delivery. Callback delivery and delegated-result delivery retry independently with exponential backoff from one to sixty seconds.

Every completion callback requires a nonempty, unique handler_id that stays stable across restarts. Events retain their original recipient set, and each handler acknowledges independently. Temporarily removed handlers remain pending, and reordering handlers does not change ownership. An acknowledged handler is not replayed because another handler fails. Power completion Hooks also declare handler_id; the SDK namespaces it with the Power name.

Delivery is at least once: a crash after an external side effect but before local acknowledgement can still cause replay. Make side effects idempotent with completion_id. Return after accepting work into your delivery queue, and pass context.abort_signal to cancellable I/O. Each callback times out after thirty seconds by default. Agent shutdown aborts active callbacks and stops waiting, retaining unacknowledged records for recovery. JavaScript cannot forcibly terminate a function that ignores cancellation; the same recipient is not retried concurrently in that process until the original invocation settles. Functions are registered again on startup, not serialized.

Recovery requires persistent Storage. Custom hosts should assemble all agents, Workspaces, Powers, and subscriptions before calling await agent.resume_work() to resume pending completion events and delegated work. CLI and Desktop already do this. Manually invoking an arbitrary Power effect does not receive this persistent-delivery behavior.

Messenger uses the same completion Hook to enqueue final Channel output into its reliable Outbox, including later Turns triggered by delegated results. Background replies retain the original calling Turn's IM message and thread. Inputs merged into one Turn deduplicate replies by Conversation. Failed Turns send a brief failure notice; stopped Turns do not send automatically. Appending an Agent Message alone does not trigger a Turn-completion callback.

  1. Mental model overview
  2. Call flow
  3. Pipeline
  4. Guard
  5. Effect
  6. Resolve
  7. How to choose

Jump straight to scenarios