# Start a session

Start an OrchaJS durable session with agent.run() and read sessionId, stream, and result.

Source: https://orcha.sh/docs/sessions/start
Markdown: https://orcha.sh/docs/sessions/start.mdx

Every `.run()` starts a new durable session. Orcha saves its messages, tool
calls, results, and usage automatically.

```ts
const run = orcha.supportAgent.run("Help me resolve order ord_1001.");
const result = await run.result;

if (result.status === "completed") {
  console.log(result.output);
}
```

Save `run.sessionId` when the user may continue this conversation later.

## Add session details

Use the object form to name a session or attach application data:

```ts
const run = orcha.supportAgent.run({
  content: "Help me resolve order ord_1001.",
  name: "Order ord_1001",
  metadata: {
    customerId: "cus_123",
    priority: "high",
  },
});
```

`name` makes the session recognizable in your UI. `metadata` lets your
application associate it with users, orders, workspaces, or other records.

## Read everything run returns

`.run()` returns an execution immediately. The model continues working in the
background.

```ts title="Destructure the execution"
const {
  sessionId,
  stream,
  snapshot,
  result,
  evaluations,
} = orcha.supportAgent.run("Help me with my order.");

const finalResult = await result;
```

- `sessionId` — available immediately; save it to continue or inspect the
  session.
- `stream` — a `ReadableStream` of live output and status snapshots.
- `snapshot` — the latest snapshot emitted by `stream`, or `undefined` before
  the first one arrives.
- `result` — a promise for the final state of this run.
- `evaluations` — a separate promise for evaluations configured on the agent.

Now narrow `finalResult.status` before reading status-specific fields:

```ts
if (finalResult.status === "completed") {
  const { sessionId, output, usage } = finalResult;

  console.log(output);
}
```

## API reference

### Input

```ts
run(input: string | {
  content: string | MessageContent | MessageContent[];
  name?: string;
  metadata?: Record<string, string | number | boolean | null>;
  variables?: Record<string, string>;
  clientCapabilities?: Array<string | { name: string }>;
}): Execution
```

- `content` — the first user message. It can be text or supported multimodal
  content.
- `name` — an optional human-readable session name.
- `metadata` — searchable application data. Do not store secrets here.
- `variables` — values for `{{ variableName }}` placeholders in the agent's
  instructions. They are fixed when the session is created.
- `clientCapabilities` — client action names this caller can handle.

Calling `.run()` again creates a different session. Use
[`resume()`](/docs/sessions/resume) to continue an existing one.

### Execution

```ts
type Execution<TOutput> = {
  sessionId: string;
  stream: ReadableStream<ExecutionSnapshot<TOutput>>;
  snapshot: ExecutionSnapshot<TOutput> | undefined;
  result: Promise<RunResult<TOutput>>;
  evaluations: Promise<EvaluationResult[]>;
};
```

The stream can emit:

- `{ status: "streaming", sessionId, output }` while output is arriving.
- `{ status: "waiting_for_subagent", sessionId, childSessionId, childAgent }`
  while a child agent is running.
- Any final result described below.

### Final result

```ts
type RunResult<TOutput> =
  | {
      status: "completed";
      sessionId: string;
      output: TOutput;
      usage?: Usage;
    }
  | {
      status: "waiting_for_client_action";
      sessionId: string;
      output?: TOutput;
      usage?: Usage;
      clientToolCalls: ClientToolCall[];
    }
  | {
      status: "paused";
      sessionId: string;
      output?: TOutput;
      usage?: Usage;
    }
  | {
      status: "failed";
      sessionId: string;
      error: RunError;
    };
```

- `output` — final text for a text agent or parsed data for a JSON agent. A
  paused run can contain partial output.
- `clientToolCalls` — actions your client must resolve before the run can
  continue.
- `usage` — token usage for the run.
- `error` — structured failure information.

```ts
type Usage = {
  inputTokens: number;
  outputTokens: number;
  reasoningTokens: number | null;
  cacheReadTokens: number;
  cacheWriteTokens: number;
};

type RunError = {
  code:
    | "invalid_input"
    | "unsupported_content_type"
    | "unsupported_provider_capability"
    | "session_not_found"
    | "session_busy"
    | "client_action_required"
    | "missing_tool_results"
    | "unknown_call_id"
    | "invalid_tool_result"
    | "action_result_conflict"
    | "session_completed"
    | "provider_error"
    | "storage_error"
    | "aborted"
    | "execution_failed";
  message: string;
  retryable: boolean;
  details?: Record<string, unknown>;
};
```

### Evaluations

`execution.result` does not wait for evaluations. Await
`execution.evaluations` when your process needs the scores before exiting:

```ts
type EvaluationResult = {
  name: string;
  status: "passed" | "failed" | "error";
  metrics: Array<{
    name: string;
    score: number;
    threshold: number;
    passed: boolean;
    reasoning: string;
    evidence: string[];
  }>;
  usage?: Usage;
  durationMs: number;
  error?: {
    message: string;
  };
};
```
