# AI API overview

> Send one message to Corfedo AI and read its final answer, citations and usage.

Source: https://docs.corfedo.ai/connect/api/ai/

Corfedo AI runs the model, keeps the conversation and applies the profile's settings. Your application sends a new message or returns [client-tool results](https://docs.corfedo.ai/connect/api/ai/client-tools/).

## Send a message

Use your SDK's authenticated client. This TypeScript example starts a conversation and waits without streaming:

```ts
const result = await client.ai.send({
  clientMessageId: crypto.randomUUID(),
  text: 'How are search requests routed?',
  sources: {
    mode: 'only',
    repositories: [{ kind: 'name', name: 'acme/search' }],
  },
});
console.log(result.conversationId, result.runId, result.status);
if (result.status === 'ended') console.log(result.outcome, result.answer);
```

The HTTP operation is `POST /api/v1/ai/messages`. Set `stream: true` to receive [server-sent events](https://docs.corfedo.ai/connect/api/ai/streaming/). Without it, the request waits until the run ends, needs client results or reaches its time limit. A response with a run still in progress has no answer yet. Use its run ID and sequence to [reattach](https://docs.corfedo.ai/connect/api/ai/streaming/#recover-a-subscription).

Omit `conversationId` for a new conversation. Supply it for the next message in an existing one. The [profile chosen for the API](https://docs.corfedo.ai/connect/api/ai/profiles/) answers.

## Select repositories and context

`sources` limits where the agent reads. Repository selectors accept `id`, `name` or `glob`. Saved contexts accept `contextId` or `name`. With no source selection the run uses accessible repositories. An explicit empty selection selects none.

Names can be full (`github.com/acme/search`) or a unique ending (`acme/search` or `search`). Repository URLs work too. `references` tells the agent what the message is about: a repository, file or directory, with an optional revision and line range. Each reference must match exactly one repository. `ambiguous_repository` (400) and `repository_not_found` (404) list candidate names you can read.

`limits` lowers the profile's run limits, `tools` narrows Corfedo's tools, `clientTools` declares functions in your application, and `outputSchema` asks for a JSON answer that follows a JSON Schema 2020-12 schema. The [message schema](https://docs.corfedo.ai/reference/api/ai/sendAiMessage/) lists every field and bound.

## Repeat safely

Generate one `clientMessageId` per new message and keep it with the request. If the response is lost, send the same request with the same ID: you get the original message's latest run, not a second run. The same ID with a different request returns `client_message_conflict` (409). A deliberate new attempt uses a new ID. The SDKs resend for you after a transient failure.

## Read the final answer

Streamed text is progress. The answer is in `run.completed`, the final `run.snapshot`, the non-streaming result or the conversation history. Do not join streamed text and use it as the answer.

| Outcome | Answer |
| --- | --- |
| `completed` | Complete answer |
| `completedBudgetLimited`, `completedTruncated`, `completedDeadlineLimited` | Answer with a limit indicated by the outcome |
| `structuredOutputInvalid`, `contextExhausted`, `limitReached`, `costCapReached`, `recoveryExhausted`, `failed`, `cancelled` | No answer |

A successful HTTP response does not mean the run completed. Check the outcome, and `failureCategory` when present.

Answers are Markdown, or JSON when you sent an output schema. The `citations` map resolves the answer's `cite:` links to a repository, revision and path. Line ranges stay in the links.

`usage` counts input, output and cached input tokens, model calls and cost. Cost keeps `reported` and `estimated` amounts apart. On the wire, sequences and token counts are decimal strings. The SDKs convert them to integers.

## Endpoints

All paths below are relative to `/api/v1/ai` and require [AI scope](https://docs.corfedo.ai/connect/authentication/).

| Operation | Reference |
| --- | --- |
| Send a message | [POST `/messages`](https://docs.corfedo.ai/reference/api/ai/sendAiMessage/) |
| Return client results | [POST `/conversations/{conversationId}/tool-results`](https://docs.corfedo.ai/reference/api/ai/submitAiToolResults/) |
| Follow a run | [GET `/runs/{runId}/events`](https://docs.corfedo.ai/reference/api/ai/streamAiRunEvents/) |
| Read a snapshot | [GET `/runs/{runId}`](https://docs.corfedo.ai/reference/api/ai/getAiRun/) |
| Request cancellation | [POST `/runs/{runId}/cancel`](https://docs.corfedo.ai/reference/api/ai/cancelAiRun/) |
| Find a profile | [GET `/profiles`](https://docs.corfedo.ai/reference/api/ai/listAiProfiles/) |
| List conversations | [GET `/conversations`](https://docs.corfedo.ai/reference/api/ai/listAiConversations/) |
| Read a conversation | [GET `/conversations/{conversationId}`](https://docs.corfedo.ai/reference/api/ai/getAiConversation/) |
| Delete a conversation | [DELETE `/conversations/{conversationId}`](https://docs.corfedo.ai/reference/api/ai/deleteAiConversation/) |

Closing a stream does not stop the run. Request cancellation to stop it.

While Corfedo AI is off for the API, messages return `permission_denied` (403). When the monthly spending limit is reached, messages return `limit_exceeded` (409, `SpendingLimitReached` in the SDKs) and start no run. [Errors](https://docs.corfedo.ai/reference/errors/) lists the other codes.
