Prompts and Turns

Submit user input with session.prompt() and understand steering, queueing, and final results

session.prompt() is the only user-input entry point. It accepts one new input and returns a TurnHandle once the SDK has assigned that input to a concrete Turn.

const turn = await session.prompt({
  query: "Analyze this repository",
});

const result = await turn.finished;
if (result.success) {
  console.log(result.text);
}

prompt() does not mean “wait for the final model response.” Receive live activity through subscribe() and the final result through turn.finished.

Input shapes

query accepts a string or a Downcity Session User Part array:

const turn = await session.prompt({
  query: [
    {
      type: "context",
      tag: "reference",
      context: "An earlier quoted message",
    },
    { type: "text", text: "Explain the architecture in this image" },
    {
      type: "file",
      media_type: "image/png",
      url: "/absolute/path/architecture.png",
      filename: "architecture.png",
    },
  ],
});

Both input and persisted messages use Downcity's snake_case fields. Input content has no canonical part_id. Human input becomes User Parts; a trusted host must declare the actual actor for automated input, which becomes an Agent input Part, including the first input of a Task or delegated Session.

actor defaults to the local user. Actor identity governs occupation; the canonical input identity governs idempotency. A stable request_id reuses the original User Message or input_id and its actual Turn result without repeating execution. Runtime request actor, Powers descriptors, and callback bindings are stored on that input Part's meta, independently of other inputs sharing the same Agent Message.

A context Part retains structured tag and context fields in the canonical Message. It becomes Text Content such as <reference>An earlier quoted message</reference> only when model context is assembled. A tag must start with a lowercase letter and may contain only lowercase letters, numbers, underscores, and hyphens; XML structural characters in the body are escaped safely. Context is not an ordinary user body, so provide a text Part alongside it in normal prompts.

Data URLs are used only for drafts and upload transport. The Session decodes them into its own attachments/ directory, and canonical file Parts store file paths. Attachments always provide paths and metadata. Static PNG, JPEG, and WebP verified from file headers can also be included automatically when each is at most 2 MiB and all request media fit within 4 MiB and the model input budget. Recent images take priority; current and historical attachments follow the same rules. PDFs and other files remain references until explicitly read, and images omitted for budget retain their references. See Messages and Parts.

A Session fork copies local attachments registered as owned by the source Session into the new Session's attachment directory. Model references are derived from the copied canonical files. The fork therefore keeps its historical attachments when the source Session is later archived or removed.

For remote Sessions, Data URLs are saved on the server. Local read accepts only runtime-accessible files allowed by project policy or registered as owned by the current Session. Remote clients can transfer attachments as Data URLs. HTTP URLs remain remote references without implicit downloads. Missing attachments record their unavailable status without blocking the entire Session.

Turn handles

const turn = await session.prompt({ query: "Continue" });

console.log(turn.id);
console.log(turn.result); // null before completion

const result = await turn.finished;

finished never rejects for a model or tool failure. It always resolves to:

{
  turn_id: string;
  success: boolean;
  text: string;
  error?: string;
}

Application code must check success; waiting for promise fulfillment alone is not a success check.

Read structured Agent Messages through messages() and subscribe(); the Turn result does not duplicate them. A final model-request failure ends the Turn with success: false, closes its Agent Message, and releases execution resources. An available Retry action starts a new execution from the failed model request.

If a Tool throws, returns { success: false }, or receives malformed JSON arguments, the SDK marks its Tool Part as failed and sends that result into the next model step. These errors do not end the Turn by themselves. Model-request failures and infrastructure failures can end the Turn. Transient model errors receive up to five automatic retries before partial output or tool side effects, for at most six calls. Reasoning and tool events count as partial output. A failed draft is discarded. Attempts and backoff share a default 900-second request budget; tools use the Turn cancellation signal. Backoff is 300, 1,000, 2,000, 4,000, and 8,000 milliseconds with ±10% jitter. An upstream Retry-After is retained as retry_at_ms and takes precedence; a wait outside the remaining budget fails with timeout_phase: "recovery_budget". Cancellation stops waiting and reading the stream.

Every failed model request publishes a live warning / model_request Mutation. request_kind distinguishes Turn, title, and history-compaction calls. attempt and max_attempts identify the current and maximum call counts, while will_retry tells the subscriber whether another call will follow. Main Turn Warnings include turn_id; background Session requests may omit it. The final failure has will_retry: false. A user-requested cancellation does not publish a Warning.

If an OpenAI-compatible Provider closes its SSE stream in the middle of an event, the SDK reports a retryable transport_error. A complete SSE event containing invalid JSON produces a provider_error that does not request automatic retry; users can still retry manually. Public errors use stable descriptions rather than exposing the underlying JSON parser message.

Sending input while a Turn runs

You can call prompt() again while a Session is running:

const first_turn = await session.prompt({ query: "Analyze the directory layout first" });
const follow_up = await session.prompt({ query: "Only inspect packages/agent" });

The Session decides what happens to the second input:

SituationResult
The current Turn can still absorb inputHuman input becomes a User Message; runtime input becomes an Agent input Part; both join the current Turn
The Turn has passed that boundaryThe input queues for the next Turn and retains its human or runtime identity
The Session is idleA new Turn starts immediately

Runtime input inputs commit at a complete Step checkpoint in the shared FIFO and do not close the current writer. A human steer creates a User Message and closes the preceding reply at that boundary. Background results remain input inputs even when the occupied actor is a user; late results follow the receiving workflow's original-Turn, retry, or follow-up policy.

Two prompt() calls can return the same turn.id. That means they were merged into one execution, not executed twice. Do not build a second client-side queue or assume every call starts a new Turn.

Live rendering and final result

A typical UI does both:

const unsubscribe = session.subscribe(render_mutation);
const turn = await session.prompt({ query: "Produce an implementation plan" });
const result = await turn.finished;
unsubscribe();
  • delta appends visible text, reasoning text, or raw Tool input immediately.
  • part updates the complete state of the same tool or text Part.
  • turn.finish updates loading state and aligns with turn.finished.

Do not poll turn.result for streaming content. It becomes the final snapshot only after the Turn ends.

Empty input and errors

Empty strings, empty arrays, and arrays containing only empty text Parts are rejected. Disable empty submission in the UI and still handle errors such as remote connection failure, a missing model, or an archived Session.

Use session.stop() to stop a running Turn.

Manual model-step retry

Every current model-request error permits manual Retry, including errors with retryable: false. ModelError.retryable controls bounded automatic attempts only. Read the current in-process binding from session.status().model_retry and submit it once:

const { model_retry } = await session.status();
if (model_retry) {
  const result = await session.retry_model_step(model_retry);
  if (!result.accepted) console.error(result.reason);
}

The binding contains message_id and error_part_id. Acceptance continues the failed Step in the same Turn and the same canonical Agent Message, using its complete original ModelCall: system, messages, parameters, tool definitions, attachment references, and completed tool results. It adds no user message, input, or recovery prompt. Stable text and completed tools never run again. New tools bind to the current Context, cancellation signal, approvals, and output. Failed input stays in process memory; no dedicated input or attempt history is persisted.

Each ordinary method call has its own result snapshot. The original turn.finished, turn.result, callback, and settled parent Work, Task, and Group results retain their original failure. Retry returns its own accepted and completion result; the Turn current result may change. Completion events follow resource release, and a later call in the same Turn cannot rewrite an old Promise. Acceptance clears the message current error; success leaves only the result in the original canonical Message.

Serialize client submissions. A binding is accepted at most once, and Retry is rejected while the Session is busy. If reception is unknown, read current status and messages instead of resubmitting. Refresh can obtain a binding still held in process memory. New input, configuration changes, Stop, cache release, or process exit can invalidate it; historical errors cannot recreate the original request.

status().state describes current activity: running includes automatic backoff; waiting_input waits for an interaction; waiting_child waits for unfinished child work. After final failure and cleanup, live_execution is false, active_turn_id is absent, occupation is released, and running counts are zero. An idle retryable failure can expose state: "failed" and model_retry; its cached request does not protect resources or block automatic queue dispatch. Queued input continues in order and invalidates an obsolete Retry. Failed child work delivers its failure normally; the parent does not wait for a manual retry, and a later retry cannot revive an ended parent tree. Hosts can use agent.sessions.has_live_execution(workspace_id?) for resource guards. Model-response commit uncertainty and tool-result save uncertainty cannot replay a model request. Original input, configuration, tool definitions, and attachments must still validate before a new request is sent.