# ユーザー API リファレンス（会話・組織）

マーケットプレイス版のユーザー向け API のエンドポイント仕様とエラーコードのリファレンスです。アプリケーション（外部ツールでのログイン）で得た利用者のトークンで呼びます。プロジェクトの API は [ユーザー API リファレンス（プロジェクト）](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/reference/user-api-reference-projects.md) を、システム連携から呼ぶ API は [システム連携 API リファレンス](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/reference/api-reference.md) を参照してください。

## ベース URL

すべての API リクエストは以下のベース URL に対して送信します。`<your-domain>` は導入した環境のドメインに読み替えてください。

Marketplace

`https://<your-domain>/api`

本ドキュメントのエンドポイントパスはベース URL からの相対パスで記載しています。

## 認証

すべてのAPIリクエストには、`Authorization` ヘッダーに Bearer トークンを含める必要があります。

```text
Authorization: Bearer <access_token>
```

トークンが無効または未指定の場合、`401 Unauthorized` が返されます。マーケットプレイス版ではスコープによる制限はありません。

- このページの API は、アプリケーション（外部ツールでのログイン）で得た利用者のトークンで呼びます。外部ツールでのログインは、管理者がその入口を開けた環境でだけ使えます（[API 利用準備ガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/guide/setup-guide.md)）。
- 外部ツールでのログイン以外で得た利用者のトークン（メイン画面にログインしたときのトークンなど）で呼ぶと、どのエンドポイントも `404 Not Found` が返ります。
- チャット・会話管理・ファイル管理・成果物取得・検索・登録 Agent の一覧は、システム連携のトークンでも呼べます（[システム連携 API リファレンス](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/reference/api-reference.md)）。[ユーザー](#user)と[マスターデータ](#master-data)の API をシステム連携のトークンで呼ぶと、`404 Not Found` が返ります。

トークンの取得方法については、[認証ガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/guide/auth-guide.md) および [認証 API リファレンス](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/reference/auth-mp-ref.md) を参照してください。

> **チャット API の注意**
>
> マーケットプレイス版でチャット API を利用する場合、`agentId` パラメータが必須で、`stream: true` 固定で動作します。詳細は[API を呼び出す](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/quickstart/call-api.md)を参照してください。

## 共通の決まり

このページの API に共通の決まりです。

### リクエストの扱い

このページの API は、リクエストを次のように扱います。エンドポイントごとの扱いは、各エンドポイントの説明とエラーレスポンスを参照してください。

| 送ったもの                                                                                        | 扱い                                                                                  |
| -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| 仕様に無いクエリパラメータとボディのフィールド                                                                      | 無視されます。ただし、このページに載っていない項目でも、サービスが受け付けている項目は、型や値が正しくないと `400 Bad Request` になることがあります |
| 仕様にあるクエリパラメータの不正な値                                                                           | `400 Bad Request`                                                                   |
| パスパラメータの値の不正な URL エンコード（`%` の並び）                                                             | `400 Bad Request`（`invalid_parameter`）                                              |
| 壊れた JSON のボディ                                                                                | `400 Bad Request`（`invalid_body`）                                                   |
| JSON のボディを受け付けるエンドポイントへの、`Content-Type: application/json` 以外のボディ、対応していない文字コード（`charset`）のボディ | `415 Unsupported Media Type`（`unsupported_media_type`）                              |
| ファイルのアップロードへの、`multipart/form-data` 以外のボディ                                                   | `415 Unsupported Media Type`                                                        |
| 型の違うボディのフィールド                                                                                | `400 Bad Request`                                                                   |

ボディの読み取りで `400`（壊れた JSON など）や `413`（サイズの上限を超えたなど）になる場合は、`415` よりそちらが先に返ります。

<!-- -->

### ページネーション

一覧取得エンドポイントはカーソルベースのページネーションをサポートしています。

| パラメータ    | 型         | 説明                                                                                   |
| -------- | --------- | ------------------------------------------------------------------------------------ |
| `limit`  | `integer` | 1ページあたりの取得件数（1-100）。デフォルトは 50 件です                                                    |
| `cursor` | `string`  | 次のページを取得するためのカーソル値。前回のレスポンスに含まれる cursor をそのまま指定します                                   |
| `order`  | `string`  | ソート順。"asc"（昇順）または "desc"（降順、デフォルト）。ほかの値を指定すると 400 Bad Request が返ります。対応するエンドポイントは一部です |

レスポンスには `hasMore` フィールドが含まれます。`true` の場合、`cursor` の値を次のリクエストに渡すことで次ページを取得できます。

カーソルベースのページネーションに対応しているのは、[会話一覧](#conversations)・[メッセージ一覧](#conversations)・[ファイル一覧](#file-management)・[メッセージの検索](#search-messages)・[プロジェクト一覧](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/reference/user-api-reference-projects.md#projects) の各一覧エンドポイントです。`cursor` は不透明な値のため、内容を解釈せず、前回レスポンスの値をそのまま次のリクエストに指定してください。

## チャット

OpenAI互換のChat Completions APIです。エージェントとの対話はSSE（Server-Sent Events）ストリーミングで配信されます。

チャットAPIは3つのエンドポイントで構成されます。メッセージの送信、既存会話への再接続、進行中の会話のキャンセルが可能です。

SSE ストリーミングガイド

接続フロー・レスポンスオブジェクト・Delta拡張・実行パターン・再接続・エラーハンドリングの詳細解説

[ガイドを見る](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/guide/streaming-guide.md)

### エンドポイント一覧

| メソッド | エンドポイント                                       | 説明                                | スコープ (SaaS) |
| ---- | --------------------------------------------- | --------------------------------- | ----------- |
| POST | `/v1/chat/completions`                        | チャットメッセージを送信し、SSEストリーミングでレスポンスを取得 | `chat:exec` |
| GET  | `/v1/chat/completions/:conversationId`        | 進行中の会話のSSEストリームに再接続               | `chat:exec` |
| POST | `/v1/chat/completions/:conversationId/cancel` | 進行中の会話をキャンセル                      | `chat:exec` |

※ Marketplace 版はスコープ不要（認証のみ）。

### POST`/v1/chat/completions`

エージェントにメッセージを送信し、SSEストリーミングでレスポンスを受け取ります。レスポンスはOpenAI互換のChat Completion Chunk形式で配信されます。

#### リクエストヘッダー

| ヘッダー            | 必須 | 説明                      |
| --------------- | -- | ----------------------- |
| `Authorization` | 必須 | Bearer \<access\_token> |
| `Content-Type`  | 必須 | application/json        |

#### リクエストボディ

| パラメータ            | 型         | 必須 | 説明                                                                                                                                                                                       |
| ---------------- | --------- | -- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `model`          | `string`  | 必須 | 使用するモデルID。"AGENTIC STAR" を指定してください。                                                                                                                                                      |
| `messages`       | `array`   | 必須 | メッセージオブジェクトの配列。少なくとも 1 つの user ロールメッセージが必要。複数の user メッセージを含めても最後の 1 件のみが処理されます。会話履歴はサーバー側で管理されるため、過去のやり取りを messages 配列で送る必要はありません。既存の会話を継続する場合は conversationId パラメータに前回の会話 ID を指定してください。 |
| `stream`         | `boolean` | 必須 | true を指定してください。現在、ストリーミングモードのみサポートしています。                                                                                                                                                 |
| `conversationId` | `string`  | —  | 既存の会話を継続する場合に会話IDを指定します。省略すると新しい会話が作成されます。                                                                                                                                               |

#### エディション固有のパラメータ

Marketplace

|                |          |                                                                                                                             |
| -------------- | -------- | --------------------------------------------------------------------------------------------------------------------------- |
| `agentId`      | `string` | 使用するエージェントのID（必須）。`GET /v1/marketplace-agents` が返す marketplaceAgentId を指定します。                                               |
| `outputFormat` | `string` | 応答テキストの形式。"plain"（省略時）は Markdown 記法を除去したプレーンテキスト（図は削除され、コードブロックは本文が残り、リンクは「文字 (URL)」になる）。"markdown" は Markdown 記法をそのまま保持する。 |

#### Message オブジェクト

| パラメータ     | 型                 | 必須 | 説明                                                                                      |
| --------- | ----------------- | -- | --------------------------------------------------------------------------------------- |
| `role`    | `string`          | 必須 | "user" を指定。"assistant" / "system" は受理されますが、現状のエージェント実行では "user" のみが対話の起点として使用されます       |
| `content` | `string \| array` | 必須 | メッセージの内容。文字列、または content parts (text / input\_file) の配列。処理対象となるテキストは UTF-8 換算で 1 MB 以下。 |

#### コンテンツパーツ（配列形式の場合）

content を配列で指定する場合、以下のパーツタイプが利用できます。テキストとファイルを組み合わせて送信できます。

| type           | パラメータ             | 説明                                      |
| -------------- | ----------------- | --------------------------------------- |
| `"text"`       | `text (string)`   | テキストメッセージ                               |
| `"input_file"` | `fileId (string)` | アップロード済みファイルの `fileId`。1リクエストあたり合計最大20件 |

#### リクエスト例

**Create chat completion**

**curl**

```curl
curl -X POST https://<your-domain>/api/v1/chat/completions \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{
  "model": "AGENTIC STAR",
  "agentId": "<your-agent-id>",
  "stream": true,
  "messages": [
    {
      "role": "user",
      "content": "売上データを分析してください"
    }
  ]
}'
```

**Python**

```python
import requests

response = requests.post(
  "https://<your-domain>/api/v1/chat/completions",
  headers={
      "Authorization": f"Bearer {token}",
      "Content-Type": "application/json",
  },
  json={
      "model": "AGENTIC STAR",
      "agentId": "<your-agent-id>",
      "stream": True,
      "messages": [{"role": "user", "content": "売上データを分析してください"}],
  },
  stream=True,
)

for line in response.iter_lines():
  if line:
      print(line.decode("utf-8"))
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/chat/completions",
{
  method: "POST",
  headers: {
    "Authorization": "Bearer " + accessToken,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "AGENTIC STAR",
    agentId: "<your-agent-id>",
    stream: true,
    messages: [{ role: "user", content: "売上データを分析してください" }],
  }),
}
);

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(decoder.decode(value));
}
```

**Go**

```go
package main

import (
  "bufio"
  "bytes"
  "encoding/json"
  "fmt"
  "net/http"
  "strings"
)

func main() {
  token := "<access_token>" // Step 1 で取得したアクセストークン

  body, _ := json.Marshal(map[string]interface{}{
      "model":  "AGENTIC STAR",
      "agentId": "<your-agent-id>",
      "stream": true,
      "messages": []map[string]string{
          {"role": "user", "content": "売上データを分析してください"},
      },
  })

  req, _ := http.NewRequest("POST",
      "https://<your-domain>/api/v1/chat/completions",
      bytes.NewReader(body))
  req.Header.Set("Authorization", "Bearer "+token)
  req.Header.Set("Content-Type", "application/json")

  resp, _ := http.DefaultClient.Do(req)
  defer resp.Body.Close()

  scanner := bufio.NewScanner(resp.Body)
  for scanner.Scan() {
      line := scanner.Text()
      if strings.HasPrefix(line, "data: ") {
          data := line[6:]
          if data == "[DONE]" { break }
          var chunk map[string]interface{}
          json.Unmarshal([]byte(data), &chunk)
          choices, _ := chunk["choices"].([]interface{})
          if len(choices) > 0 {
              delta, _ := choices[0].(map[string]interface{})["delta"].(map[string]interface{})
              if content, ok := delta["content"].(string); ok {
                  fmt.Print(content)
              }
          }
      }
  }
}
```

#### レスポンスヘッダー

| ヘッダー                | 説明                              |
| ------------------- | ------------------------------- |
| `Content-Type`      | text/event-stream               |
| `X-Conversation-Id` | 会話ID。新規会話の場合はサーバーが生成したIDが返されます。 |
| `X-Message-Id`      | アシスタントの応答メッセージID。               |

#### SSE レスポンス形式

レスポンスは以下の順序でSSEイベントとして配信されます。各イベントは data: プレフィックス付きのJSON行です。

SSEイベントフロー

1

<!-- -->

. `data: {"choices":[{"delta":{"role":"assistant"}}]}`

2

<!-- -->

. `data: {"choices":[{"delta":{"content":"..."}}]} × N`

3

<!-- -->

. `data: {"choices":[{"finishReason":"stop"}]}`

4

<!-- -->

. `data: [DONE]`

レスポンスは SSE（Server-Sent Events）ストリーミングで配信されます。各チャンクは OpenAI 互換の ChatCompletionChunk 形式です。接続ライフサイクル、レスポンスオブジェクトの詳細、エージェント拡張フィールド、エラーハンドリングについては[ストリーミングガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/guide/streaming-guide.md)を参照してください。

#### レスポンス例

```text
data: {"createdAt":"2026-03-14T10:30:00Z","model":"AGENTIC STAR","choices":[{"index":0,"delta":{"role":"assistant"},"finishReason":null}]}

data: {"createdAt":"2026-03-14T10:30:00Z","model":"AGENTIC STAR","choices":[{"index":0,"delta":{"content":"売上データ"},"finishReason":null}]}

data: {"createdAt":"2026-03-14T10:30:00Z","model":"AGENTIC STAR","choices":[{"index":0,"delta":{"content":"を分析します。"},"finishReason":null}]}

data: {"createdAt":"2026-03-14T10:30:01Z","model":"AGENTIC STAR","choices":[{"index":0,"delta":{},"finishReason":"stop"}]}

data: [DONE]
```

#### エラーレスポンス

SSEストリーム開始前のエラーはJSON形式で返されます。ストリーム中のエラーはSSEチャンクとして配信されます。

| ステータス | 説明                                                                                                                                                                                                                           |
| ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400` | リクエストパラメータ不正（model / messages / stream / conversationId / role / content の欠落・型不一致、または input\_file が1リクエストあたり20件を超過）。ボディが壊れた JSON（`code: "invalid_body"`）。または、指定した `conversationId` がアーカイブ済み（`code: "conversation_archived"`） |
| `400` | messages に user ロールのメッセージが 1 つも無い（`code: "no_user_message"`）                                                                                                                                                                 |
| `415` | ボディの Content-Type が application/json ではない（`code: "unsupported_media_type"`）                                                                                                                                                  |
| `403` | 指定した会話がプロジェクトの会話（`code: "project_conversation"`。プロジェクトの会話には送れません）                                                                                                                                                            |
| `404` | 指定した input\_file の `fileId` が見つからない（`code: "file_not_found"`）                                                                                                                                                                |
| `409` | 指定した会話が現在処理中（`code: "conversation_processing"`）                                                                                                                                                                              |

### GET`/v1/chat/completions/:conversationId`

進行中の会話のSSEストリームに再接続します。エージェントが長時間実行タスクを処理している場合や、ネットワーク切断後の復帰に使用します。

#### パスパラメータ

| パラメータ            | 型        | 必須 | 説明         |
| ---------------- | -------- | -- | ---------- |
| `conversationId` | `string` | 必須 | 再接続する会話のID |

#### リクエスト例

**Resume SSE stream**

**curl**

```curl
curl https://<your-domain>/api/v1/chat/completions/550e8400-e29b-41d4-a716-446655440000 \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
import requests

response = requests.get(
  "https://<your-domain>/api/v1/chat/completions/550e8400-e29b-41d4-a716-446655440000",
  headers={"Authorization": f"Bearer {token}"},
  stream=True,
)

for line in response.iter_lines():
  if line:
      print(line.decode("utf-8"))
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/chat/completions/550e8400-e29b-41d4-a716-446655440000",
{
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(decoder.decode(value));
}
```

**Go**

```go
req, _ := http.NewRequest("GET",
  "https://<your-domain>/api/v1/chat/completions/550e8400-e29b-41d4-a716-446655440000",
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
  fmt.Println(scanner.Text())
}
```

#### レスポンス（200 OK）

SSE ストリームに再接続します。レスポンス形式は [POST /v1/chat/completions](#chat) と同じです。レスポンスヘッダーに `X-Conversation-Id` と `X-Message-Id` が含まれます。再接続の詳細な手順については[ストリーミングガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/guide/streaming-guide.md)を参照してください。

#### エラーレスポンス

| ステータス | code        | 説明                                                       |
| ----- | ----------- | -------------------------------------------------------- |
| `404` | `not_found` | 会話が見つからない、進行中でない、または自分の会話ではない（conversationId が空の値のときも同じ） |

### POST`/v1/chat/completions/:conversationId/cancel`

進行中の会話をキャンセルします。エージェントの実行を中断する場合に使用します。

#### パスパラメータ

| パラメータ            | 型        | 必須 | 説明           |
| ---------------- | -------- | -- | ------------ |
| `conversationId` | `string` | 必須 | キャンセルする会話のID |

#### リクエストボディ（任意）

| パラメータ       | 型        | 必須 | 説明                                    |
| ----------- | -------- | -- | ------------------------------------- |
| `messageId` | `string` | —  | キャンセル対象のメッセージID（UUID）。省略時は会話全体のキャンセル。 |

#### リクエスト例

**Cancel chat**

**curl**

```curl
curl -X POST https://<your-domain>/api/v1/chat/completions/550e8400-e29b-41d4-a716-446655440000/cancel \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json"
```

**Python**

```python
import requests

response = requests.post(
  "https://<your-domain>/api/v1/chat/completions/550e8400-e29b-41d4-a716-446655440000/cancel",
  headers={"Authorization": f"Bearer {token}"},
)

data = response.json()
print(f"Cancelled: {data['cancelled']}")
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/chat/completions/550e8400-e29b-41d4-a716-446655440000/cancel",
{
  method: "POST",
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const data = await response.json();
console.log("Cancelled: " + data.cancelled);
```

**Go**

```go
req, _ := http.NewRequest("POST",
  "https://<your-domain>/api/v1/chat/completions/550e8400-e29b-41d4-a716-446655440000/cancel",
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

#### レスポンスフィールド（200 OK）

| フィールド            | 型         | 説明                  |
| ---------------- | --------- | ------------------- |
| `conversationId` | `string`  | キャンセルされた会話のID（UUID） |
| `cancelled`      | `boolean` | キャンセル成功時は常に true    |

#### レスポンス例

```json
{ "conversationId": "550e8400-...", "cancelled": true }
```

#### エラーレスポンス

| ステータス | 説明                                                                                                                                                                                                      |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400` | conversationId が不正、messageId が文字列ではない、ボディが壊れた JSON または JSON のオブジェクトではない（`code: "invalid_body"`）、または会話がアーカイブ済み（`code: "conversation_archived"`）                                                          |
| `400` | messageId のメッセージが、指定した会話のものではない（`code: "conversation_mismatch"`）                                                                                                                                        |
| `400` | この会話の接続先がキャンセルに対応していない（`code: "unsupported_endpoint"`）、またはこの環境でキャンセルが有効になっていない（`code: "post_processing_not_enabled"`）                                                                                   |
| `415` | ボディの Content-Type が application/json ではない（`code: "unsupported_media_type"`）                                                                                                                             |
| `404` | 会話が見つからない、またはメッセージを止められない（`code: "message_not_found"`）。`message_not_found` は、送った直後で 10 秒ほど待っても止められなかったとき（数秒後にもう一度送れば止まります）と、messageId のメッセージが無い、または自分のものではないとき（送り直しても止まりません。messageId を確かめてください）の 2 つです |
| `404` | messageId のメッセージが処理中ではない（すでに終わっている。`code: "not_processing"`）                                                                                                                                            |

## 登録 Agent の一覧

チャットで動かせる登録 Agent の一覧を取得します。

### エンドポイント一覧

| メソッド | エンドポイント                  | 説明              |
| ---- | ------------------------ | --------------- |
| GET  | `/v1/marketplace-agents` | 登録 Agent の一覧を取得 |

### GET`/v1/marketplace-agents`

チャット（`POST /v1/chat/completions` の `agentId`）で動かせる登録 Agent を、全部返します（有効なものだけ）。MCP の受け口が有効な配備でチャットの組（`?toolsets=chat`。指定が無いときの既定）を使うときは MCP（`execute_chat` の `agentId`）、A2A の受け口が有効な配備では A2A（`/v1/a2a/agents/{agentId}/`）でも、同じ Agent を動かせます。MCP の `list_agents` と同じ一覧です。一覧は最大 5 分前のものです。`marketplaceAgentId` を、チャットでは `agentId` に指定します。

#### リクエスト例

**List registered agents**

**curl**

```curl
curl "https://<your-domain>/api/v1/marketplace-agents" \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
import requests

response = requests.get(
  "https://<your-domain>/api/v1/marketplace-agents",
  headers={"Authorization": f"Bearer {token}"},
)

for agent in response.json()["marketplaceAgents"]:
  print(agent["marketplaceAgentId"], agent["displayName"])
```

**TypeScript**

```typescript
const response = await fetch("https://<your-domain>/api/v1/marketplace-agents", {
headers: { "Authorization": "Bearer " + accessToken },
});

const data = await response.json();
data.marketplaceAgents.forEach((agent) => {
console.log(agent.marketplaceAgentId + ": " + agent.displayName);
});
```

**Go**

```go
req, _ := http.NewRequest("GET", "https://<your-domain>/api/v1/marketplace-agents", nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

#### レスポンスフィールド（200 OK）

| フィールド                                    | 型          | 説明                                  |
| ---------------------------------------- | ---------- | ----------------------------------- |
| `marketplaceAgents`                      | `array`    | 登録 Agent の配列（有効なものの全部）              |
| `marketplaceAgents[].marketplaceAgentId` | `string`   | 登録 Agent の ID。チャットでは agentId に指定します |
| `marketplaceAgents[].displayName`        | `string`   | 表示名                                 |
| `marketplaceAgents[].description`        | `string`   | 説明。説明が無い Agent は表示名                 |
| `marketplaceAgents[].tags`               | `string[]` | タグ                                  |
| `hasMore`                                | `boolean`  | いつも false（全部を返します）                  |

#### レスポンス例

```json
{
  "marketplaceAgents": [
    {
      "marketplaceAgentId": "sales-report",
      "displayName": "売上レポート",
      "description": "売上データを集計して報告書を作ります",
      "tags": ["report"]
    }
  ],
  "hasMore": false
}
```

#### エラーレスポンス

| ステータス | code                        | 説明                   |
| ----- | --------------------------- | -------------------- |
| `401` | `—`                         | トークンが無い・無効（共通のエラーの節） |
| `502` | `upstream_connection_error` | 登録 Agent の一覧を読めなかった  |
| `502` | `upstream_api_error`        | 一覧の読み取り先が誤りを返した      |
| `504` | `upstream_timeout`          | 一覧の読み取りが時間内に終わらなかった  |

## 会話管理

会話の一覧取得・メッセージ履歴参照・削除・タイトル更新を行います。

### エンドポイント一覧

| メソッド   | エンドポイント                                      | 説明           | スコープ (SaaS)    |
| ------ | -------------------------------------------- | ------------ | -------------- |
| GET    | `/v1/conversations`                          | 会話一覧を取得      | `chat:history` |
| GET    | `/v1/conversations/:conversationId/messages` | メッセージ履歴を取得   | `chat:history` |
| PATCH  | `/v1/conversations/:conversationId`          | 会話のタイトルを更新   | `chat:history` |
| DELETE | `/v1/conversations/:conversationId`          | 会話を削除        | `chat:history` |
| POST   | `/v1/conversations/:conversationId/restore`  | アーカイブ済み会話を復元 | `chat:history` |
| POST   | `/v1/conversations/:conversationId/read`     | 会話を既読にする     | `chat:history` |

※ Marketplace 版はスコープ不要（認証のみ）。

**アーカイブ済みの会話は、管理者が保持の期間を決めていると、アーカイブしてからその日数を過ぎたときに自動で削除されます。** メッセージと、その会話だけで使っていた添付・成果物のファイルも一緒に削除されます。保持の期間を決めていなければ、削除されません。

#### アーカイブ会話への操作制約

`mode=archive` で取得できるアーカイブ済み会話は、参照系の操作（一覧取得・メッセージ履歴取得）と復元のみ可能です。以下の操作は 400 エラー（`code: "conversation_archived"`）になります。

| 操作                                     | アーカイブ済みでの動作                                                        |
| -------------------------------------- | ------------------------------------------------------------------ |
| `GET /v1/conversations?mode=archive`   | ✅ 取得可能                                                             |
| `GET /v1/conversations/:id/messages`   | ✅ 取得可能（`messages[].archived: true` 付与）                             |
| `PATCH /v1/conversations/:id`          | ❌ 400 `Archived conversations cannot be modified`                  |
| `DELETE /v1/conversations/:id`         | ❌ 400 `Archived conversations cannot be deleted via this endpoint` |
| `POST /v1/chat/completions`（既存会話継続）    | ❌ 400 `Cannot send messages to an archived conversation`           |
| `POST /v1/chat/completions/:id/cancel` | ❌ 400 `Cannot cancel an archived conversation`                     |
| `POST /v1/conversations/:id/restore`   | ✅ active に戻す                                                       |

### GET`/v1/conversations`

会話一覧を取得します。カーソルベースのページネーションに対応しています。

#### クエリパラメータ

| パラメータ    | 型         | 必須 | デフォルト      | 説明                                                                                      |
| -------- | --------- | -- | ---------- | --------------------------------------------------------------------------------------- |
| `limit`  | `integer` | —  | `50`       | 取得件数（1〜100）                                                                             |
| `cursor` | `string`  | —  | —          | 次ページ取得用カーソル（前回レスポンスの cursor 値）                                                          |
| `order`  | `string`  | —  | `"desc"`   | "asc" または "desc"                                                                        |
| `title`  | `string`  | —  | —          | タイトルで絞り込み                                                                               |
| `mode`   | `string`  | —  | `"active"` | "active"（通常会話）または "archive"（アーカイブ済み会話）。\`mode\` を切り替えると別データストアになるため、\`cursor\` は引き継げません |

#### リクエスト例

**List conversations**

**curl**

```curl
curl "https://<your-domain>/api/v1/conversations?limit=10&order=desc" \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
import requests

response = requests.get(
  "https://<your-domain>/api/v1/conversations",
  headers={"Authorization": f"Bearer {token}"},
  params={"limit": 10, "order": "desc"},
)

data = response.json()
for conv in data["conversations"]:
  print(conv["title"], conv["conversationId"])
```

**TypeScript**

```typescript
const params = new URLSearchParams({ limit: "10", order: "desc" });
const response = await fetch(
"https://<your-domain>/api/v1/conversations?" + params,
{
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const data = await response.json();
data.conversations.forEach((conv) => {
console.log(conv.title, conv.conversationId);
});
```

**Go**

```go
req, _ := http.NewRequest("GET",
  "https://<your-domain>/api/v1/conversations?limit=10&order=desc",
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

#### レスポンスフィールド（200 OK）

| フィールド                            | 型          | 説明                                                                                                                              |
| -------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `conversations`                  | `array`    | 会話オブジェクトの配列                                                                                                                     |
| `conversations[].conversationId` | `string`   | 会話の一意識別子（UUID）                                                                                                                  |
| `conversations[].title`          | `string`   | 会話のタイトル                                                                                                                         |
| `conversations[].type`           | `string?`  | 会話の種類。"chat"（チャット）・"mail"（メールから始めた会話）。プロジェクトの工程の会話は一覧に含まれません（会話 ID を指定すればメッセージを取得できます）。`mode=archive` では返しません                   |
| `conversations[].createdAt`      | `string`   | 作成日時（ISO 8601）                                                                                                                  |
| `conversations[].updatedAt`      | `string`   | 最終更新日時（ISO 8601）                                                                                                                |
| `conversations[].archived`       | `boolean?` | アーカイブ済みかどうか。`mode=archive` で取得した場合は常に `true`。`mode=active` でこのフィールドが `true` で返るのは、archive 状態のまま active 一覧から取得された場合のみで、通常は省略されます |
| `hasMore`                        | `boolean`  | 次のページが存在するかどうか                                                                                                                  |
| `cursor`                         | `string`   | 次ページ取得用カーソル。hasMore が true の場合のみ含まれます                                                                                           |

#### レスポンス例

```json
{
  "conversations": [
    {
      "conversationId": "550e8400-e29b-41d4-a716-446655440000",
      "title": "売上データ分析",
      "type": "chat",
      "createdAt": "2026-03-14T10:30:00Z",
      "updatedAt": "2026-03-14T10:35:00Z"
    }
  ],
  "hasMore": true,
  "cursor": "eyJrIjoiMjAyNi0wMy0xNFQxMDozMDowMC4wMDBaIn0"
}
```

#### エラーレスポンス

| ステータス | code                        | 説明                                                                                                                                         |
| ----- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `400` | `invalid_parameter`         | limit パラメータが不正（1〜100の範囲外）、mode が "active" / "archive" 以外、order が "asc" / "desc" 以外、cursor が不正（前回レスポンスの値以外）、または title が文字列ではない（複数回指定した場合など） |
| `502` | `upstream_connection_error` | 会話の一覧を取得できなかった（時間をおいて再試行してください）                                                                                                            |

### GET`/v1/conversations/:conversationId/messages`

指定した会話のメッセージ履歴を取得します。カーソルベースのページネーションに対応しています。取得しても会話は既読になりません（MCP・A2A で読んでも同じです）。既読にするには[会話を既読にする](#read-conversation)を呼びます。

#### パスパラメータ

| パラメータ            | 型        | 必須 | 説明          |
| ---------------- | -------- | -- | ----------- |
| `conversationId` | `string` | 必須 | 会話のID（UUID） |

#### クエリパラメータ

| パラメータ    | 型         | 必須 | デフォルト    | 説明                             |
| -------- | --------- | -- | -------- | ------------------------------ |
| `limit`  | `integer` | —  | `50`     | 1 ページの取得件数（1-100）              |
| `cursor` | `string`  | —  | —        | 次ページ取得用カーソル（前回レスポンスの cursor 値） |
| `order`  | `string`  | —  | `"desc"` | "asc" または "desc"               |

#### リクエスト例

**Get messages**

**curl**

```curl
curl https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000/messages?order=asc \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
response = requests.get(
  "https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000/messages",
  headers={"Authorization": f"Bearer {token}"},
  params={"order": "asc"},
)

messages = response.json()["messages"]
for msg in messages:
  print(f"[{msg['sender']}] {msg['text'][:50]}")
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000/messages?order=asc",
{
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const { messages } = await response.json();
messages.forEach((msg) => console.log("[" + msg.sender + "] " + msg.text));
```

**Go**

```go
req, _ := http.NewRequest("GET",
  "https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000/messages?order=asc",
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

#### レスポンスフィールド（200 OK）

| フィールド                                 | 型          | 説明                                                                                                |
| ------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------- |
| `messages`                            | `array`    | メッセージオブジェクトの配列                                                                                    |
| `messages[].conversationId`           | `string`   | 会話ID（UUID）                                                                                        |
| `messages[].messageId`                | `string`   | メッセージの一意識別子                                                                                       |
| `messages[].sender`                   | `string`   | 送信者。"User" または "AI"                                                                               |
| `messages[].text`                     | `string`   | メッセージの本文テキスト。本文が空のときは、いちばん新しいタスクの結果（`content`）が入ります                                               |
| `messages[].createdAt`                | `string`   | 作成日時（ISO 8601）                                                                                    |
| `messages[].updatedAt`                | `string`   | 最終更新日時（ISO 8601）                                                                                  |
| `messages[].status`                   | `object`   | メッセージの処理状態                                                                                        |
| `messages[].status.processing`        | `boolean`  | エージェントが現在処理中かどうか                                                                                  |
| `messages[].status.unfinished`        | `boolean`  | エージェントの応答が中断されたかどうか                                                                               |
| `messages[].tasks`                    | `array`    | エージェントが実行したタスクの配列（後述）                                                                             |
| `messages[].deliverables`             | `array`    | エージェントが生成した成果物の配列。存在する場合のみ含まれます                                                                   |
| `messages[].deliverables[].filename`  | `string`   | 成果物のファイル名                                                                                         |
| `messages[].deliverables[].filepath`  | `string`   | 成果物のファイルパス                                                                                        |
| `messages[].deliverables[].source`    | `string`   | `"agent"`（エージェント生成）または `"user"`（ユーザーアップロード）                                                       |
| `messages[].deliverables[].isPrimary` | `boolean`  | 主要成果物かどうか                                                                                         |
| `messages[].deliverables[].createdAt` | `string`   | 作成日時（ISO 8601形式）。分からないときは空文字                                                                      |
| `messages[].deliverables[].mimeType`  | `string`   | MIME タイプ（例: `"application/pdf"`、`"text/markdown"`）。判定できない場合は `"application/octet-stream"`         |
| `messages[].deliverables[].size`      | `number?`  | ファイルサイズ（バイト）。0 以下の場合は省略                                                                           |
| `messages[].files`                    | `array?`   | ユーザーが添付したファイルの配列。`sender: "User"` のメッセージで添付がある場合のみ含まれます                                           |
| `messages[].files[].fileId`           | `string`   | ファイルの一意識別子（UUID）                                                                                  |
| `messages[].files[].mimeType`         | `string`   | MIME タイプ（例: `"image/png"`、`"application/pdf"`）                                                    |
| `messages[].files[].width`            | `number?`  | 画像の幅（ピクセル）。画像ファイルの場合のみ                                                                            |
| `messages[].files[].height`           | `number?`  | 画像の高さ（ピクセル）。画像ファイルの場合のみ                                                                           |
| `messages[].archived`                 | `boolean?` | archive 経由で取得されたメッセージのみ `true`。`GET /v1/conversations?mode=archive` で取得した会話のメッセージ履歴を参照した場合に付与されます |
| `hasMore`                             | `boolean`  | 次のページが存在するかどうか                                                                                    |
| `cursor`                              | `string`   | 次ページ取得用カーソル。hasMore が true の場合のみ含まれます                                                             |

#### Task オブジェクト

| フィールド            | 型         | 説明                                                                                                                                                                           |
| ---------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `messageId`      | `string`  | タスクが属するメッセージのID                                                                                                                                                              |
| `conversationId` | `string`  | タスクが属する会話のID                                                                                                                                                                 |
| `callId`         | `string?` | ツール呼び出しID。Complex Path では複数のタスクが同じ callId を共有し、同一ツール呼び出しのステップ列を識別するために利用される                                                                                                  |
| `actionType`     | `string`  | タスクの種類（例: ツール実行、コード生成）                                                                                                                                                       |
| `title`          | `string?` | タスクのタイトル。存在しない場合は省略される                                                                                                                                                       |
| `description`    | `string?` | タスクの説明。存在しない場合は省略される                                                                                                                                                         |
| `status`         | `string`  | タスクの状態。値は "in\_progress" / "completed" / "failed" / "error" / "pending" のいずれか                                                                                                |
| `content`        | `string?` | タスクの実行結果テキスト。存在しない場合は省略される                                                                                                                                                   |
| `metadata`       | `object?` | actionType ごとに異なる補助情報（sub\_event\_type、url、filepath など）。詳細は [ストリーミングガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/guide/streaming-guide.md) を参照 |
| `files`          | `array?`  | タスクに関連するファイル（`filename` / `size` / `filepath` / `mimeType?` の構造。MIME タイプ判定不能時は `mimeType` を省略）。タスクに関連ファイルがない場合は配列自体が省略される                                                    |
| `timestamp`      | `number`  | タスク実行時のタイムスタンプ（Unix ミリ秒）                                                                                                                                                     |
| `createdAt`      | `string`  | 作成日時（ISO 8601）                                                                                                                                                               |
| `updatedAt`      | `string`  | 更新日時（ISO 8601）                                                                                                                                                               |

<!-- -->

#### ページネーション

`limit` を指定すると、その件数ずつ取得できます。`hasMore` が `true` の間、レスポンスの `cursor` をそのまま次のリクエストに渡してください。

**リクエスト例**

**curl**

```bash
# 1ページ目
curl "https://<your-domain>/api/v1/conversations/<conversation_id>/messages?limit=50" \
-H "Authorization: Bearer <access_token>"

# 2ページ目（1ページ目のレスポンスに含まれる cursor を指定）
curl "https://<your-domain>/api/v1/conversations/<conversation_id>/messages?limit=50&cursor=<cursor>" \
-H "Authorization: Bearer <access_token>"
```

`limit` を省略した場合は 50 件が返ります。全件を取得する場合は、`hasMore` が `false` になるまで `cursor` で続きを取得してください。

> **カーソル利用時の注意**
>
> `cursor` は取得位置を表すため、同じカーソルを使い続ける間は `order` を変更しないでください。条件を変えると対象範囲が変わり、項目の重複や取りこぼしが起きます。
>
> また、ページを取得している間にメッセージが追加・削除された場合も、ページ間で重複や取りこぼしが生じることがあります。

> **未知のフィールドは安全に無視**
>
> 実装は将来 `actionType` / `metadata` に新規フィールドを追加する可能性があります。クライアント実装では、本表に記載されていないフィールドは安全に無視するようにしてください。詳細な metadata 構造は [ストリーミングガイド — Task データモデル](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/guide/streaming-guide.md#task-data-model) を参照してください。

#### レスポンス例

```json
{
  "messages": [
    {
      "conversationId": "550e8400-...",
      "messageId": "msg-abc123",
      "sender": "User",
      "text": "売上データを分析してください",
      "createdAt": "2026-03-14T10:30:00Z",
      "updatedAt": "2026-03-14T10:30:00Z",
      "status": { "processing": false, "unfinished": false },
      "tasks": []
    }
  ],
  "hasMore": false
}
```

#### エラーレスポンス

| ステータス | code                      | 説明                                                                            |
| ----- | ------------------------- | ----------------------------------------------------------------------------- |
| `400` | `invalid_conversation_id` | conversationId が全部 0 の UUID（00000000-0000-0000-0000-000000000000）。この値は受け付けません |
| `400` | `invalid_parameter`       | limit が 1-100 の整数でない、cursor が不正（前回レスポンスの値以外）、または order が "asc" / "desc" 以外    |
| `404` | `conversation_not_found`  | 会話が見つからない、または自分の会話ではない                                                        |

<!-- -->

### PATCH`/v1/conversations/:conversationId`

会話のタイトルを更新します。

#### パスパラメータ

| パラメータ            | 型        | 必須 | 説明          |
| ---------------- | -------- | -- | ----------- |
| `conversationId` | `string` | 必須 | 会話のID（UUID） |

#### リクエストボディ

| パラメータ   | 型        | 必須 | 説明                 |
| ------- | -------- | -- | ------------------ |
| `title` | `string` | 必須 | 新しい会話タイトル（200文字以内） |

#### リクエスト例

**Update conversation**

**curl**

```curl
curl -X PATCH https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000 \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{ "title": "新しいタイトル" }'
```

**Python**

```python
import requests

response = requests.patch(
  "https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000",
  headers={"Authorization": f"Bearer {token}"},
  json={"title": "新しいタイトル"},
)

data = response.json()
print(f"Updated: {data['title']}")
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000",
{
  method: "PATCH",
  headers: {
    "Authorization": "Bearer " + accessToken,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ title: "新しいタイトル" }),
}
);

const data = await response.json();
console.log("Updated: " + data.title);
```

**Go**

```go
payload := map[string]string{"title": "新しいタイトル"}
body, _ := json.Marshal(payload)

req, _ := http.NewRequest("PATCH",
  "https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000",
  bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
```

#### レスポンスフィールド（200 OK）

| フィールド            | 型        | 説明                                          |
| ---------------- | -------- | ------------------------------------------- |
| `conversationId` | `string` | 会話ID（UUID）                                  |
| `title`          | `string` | 更新後のタイトル                                    |
| `type`           | `string` | 会話の種類。"chat"・"mail"・"project"（プロジェクトの工程の会話） |
| `createdAt`      | `string` | 会話の作成日時（ISO 8601）                           |
| `updatedAt`      | `string` | 会話の更新日時（ISO 8601）                           |

#### レスポンス例

```json
{
  "conversationId": "550e8400-...",
  "title": "新しいタイトル",
  "type": "chat",
  "createdAt": "2026-03-14T10:30:00.000Z",
  "updatedAt": "2026-03-14T12:00:00.000Z"
}
```

#### エラーレスポンス

| ステータス | code                      | 説明                                                                            |
| ----- | ------------------------- | ----------------------------------------------------------------------------- |
| `400` | `invalid_conversation_id` | conversationId が全部 0 の UUID（00000000-0000-0000-0000-000000000000）。この値は受け付けません |
| `400` | `missing_parameter`       | title が未指定                                                                    |
| `400` | `invalid_title`           | title が空文字・文字列ではない・200 文字を超える                                                 |
| `400` | `invalid_body`            | ボディが壊れた JSON                                                                  |
| `400` | `conversation_archived`   | 会話がアーカイブ済み                                                                    |
| `415` | `unsupported_media_type`  | ボディの Content-Type が application/json ではない                                     |
| `404` | `conversation_not_found`  | 会話が見つからない、または自分の会話ではない                                                        |

### DELETE`/v1/conversations/:conversationId`

会話を削除します。その会話のメッセージに添付したファイルと成果物のファイルのうち、ほかの会話で使っていないものも削除されます（`GET /v1/files` にも出なくなります）。

#### パスパラメータ

| パラメータ            | 型        | 必須 | 説明          |
| ---------------- | -------- | -- | ----------- |
| `conversationId` | `string` | 必須 | 会話のID（UUID） |

#### リクエスト例

**Delete conversation**

**curl**

```curl
curl -X DELETE https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000 \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
import requests

response = requests.delete(
  "https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000",
  headers={"Authorization": f"Bearer {token}"},
)

data = response.json()
print(f"Deleted: {data['deleted']}")
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000",
{
  method: "DELETE",
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const data = await response.json();
console.log("Deleted: " + data.deleted);
```

**Go**

```go
req, _ := http.NewRequest("DELETE",
  "https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000",
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

#### レスポンスフィールド（200 OK）

| フィールド            | 型         | 説明               |
| ---------------- | --------- | ---------------- |
| `conversationId` | `string`  | 削除された会話のID（UUID） |
| `deleted`        | `boolean` | 削除成功時は常に true    |

#### レスポンス例

```json
{ "conversationId": "550e8400-...", "deleted": true }
```

#### エラーレスポンス

| ステータス | code                      | 説明                                                                            |
| ----- | ------------------------- | ----------------------------------------------------------------------------- |
| `400` | `invalid_conversation_id` | conversationId が全部 0 の UUID（00000000-0000-0000-0000-000000000000）。この値は受け付けません |
| `400` | `conversation_archived`   | 会話がアーカイブ済み。復元には `POST /v1/conversations/:id/restore` を使用                      |
| `404` | `conversation_not_found`  | 会話が見つからない、または自分の会話ではない                                                        |
| `409` | `conversation_processing` | 会話が現在処理中のため削除できない                                                             |
| `409` | `project_conversation`    | プロジェクトの会話。プロジェクトの会話は削除できません                                                   |
| `409` | `legal_hold`              | 保全中の会話。管理者が保全を解除するまで削除できません                                                   |

### POST`/v1/conversations/:conversationId/restore`

アーカイブ済み会話を active に戻します。復元後は通常会話と同様に編集・継続・削除が可能になります。

#### パスパラメータ

| パラメータ            | 型        | 必須 | 説明                 |
| ---------------- | -------- | -- | ------------------ |
| `conversationId` | `string` | 必須 | アーカイブ済み会話のID（UUID） |

#### リクエスト例

**Restore archived conversation**

**curl**

```curl
curl -X POST https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000/restore \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
import requests

response = requests.post(
  "https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000/restore",
  headers={"Authorization": f"Bearer {token}"},
)

data = response.json()
print(f"Restored: {data['restored']}")
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000/restore",
{
  method: "POST",
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const data = await response.json();
console.log("Restored: " + data.restored);
```

**Go**

```go
req, _ := http.NewRequest("POST",
  "https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000/restore",
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

#### レスポンスフィールド（200 OK）

| フィールド            | 型         | 説明               |
| ---------------- | --------- | ---------------- |
| `conversationId` | `string`  | 復元された会話のID（UUID） |
| `restored`       | `boolean` | 復元成功時は常に true    |

#### レスポンス例

```json
{ "conversationId": "550e8400-...", "restored": true }
```

#### エラーレスポンス

| ステータス | code                      | 説明                                                                            |
| ----- | ------------------------- | ----------------------------------------------------------------------------- |
| `400` | `invalid_conversation_id` | conversationId が全部 0 の UUID（00000000-0000-0000-0000-000000000000）。この値は受け付けません |
| `404` | `conversation_not_found`  | アーカイブに該当会話が存在しない、または既に active（archive 状態と区別されません）                             |

### POST`/v1/conversations/:conversationId/read`

会話を既読にします。会話のメッセージを API（REST・MCP・A2A）で読んでも既読にはならないので、読んだことを残すときに呼びます。既読の位置は後ろに戻りません（前のメッセージを指定しても、今より前には戻りません）。

<!-- -->

#### パスパラメータ

| パラメータ            | 型        | 必須 | 説明          |
| ---------------- | -------- | -- | ----------- |
| `conversationId` | `string` | 必須 | 会話のID（UUID） |

#### リクエストボディ（任意）

本文は省けます。付けるときは `Content-Type: application/json` で送ります。

| パラメータ       | 型        | 必須 | 説明                                                                       |
| ----------- | -------- | -- | ------------------------------------------------------------------------ |
| `messageId` | `string` | —  | 読んだ最後のメッセージのID。省くと、その時点の最新のメッセージまで既読にします（読んでいる間に届いたメッセージを既読にしないときに指定します） |

#### リクエスト例

**Mark a conversation as read**

**curl**

```curl
curl -X POST https://<your-domain>/api/v1/conversations/550e8400-e29b-41d4-a716-446655440000/read \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{"messageId": "7c9e6679-7425-40de-944b-e07fc1f90ae7"}'
```

#### レスポンス（204 No Content）

本文はありません。

#### エラーレスポンス

| ステータス | code                      | 説明                                                                            |
| ----- | ------------------------- | ----------------------------------------------------------------------------- |
| `400` | `invalid_conversation_id` | conversationId が全部 0 の UUID（00000000-0000-0000-0000-000000000000）。この値は受け付けません |
| `400` | `invalid_parameter`       | messageId が空・文字列ではない                                                          |
| `400` | `invalid_body`            | 本文が JSON のオブジェクトではない                                                          |
| `400` | `conversation_archived`   | 会話がアーカイブ済み                                                                    |
| `415` | `unsupported_media_type`  | 本文が application/json でない                                                      |
| `404` | `conversation_not_found`  | 会話が存在しない・自分の会話でない                                                             |
| `404` | `message_not_found`       | messageId がその会話に無い                                                            |

## ファイル管理

ファイルのアップロード・取得・削除を行います。

### エンドポイント一覧

| メソッド   | エンドポイント                     | 説明          | スコープ (SaaS) |
| ------ | --------------------------- | ----------- | ----------- |
| GET    | `/v1/files`                 | ファイル一覧を取得   | `chat:file` |
| POST   | `/v1/files`                 | ファイルをアップロード | `chat:file` |
| GET    | `/v1/files/:fileId/content` | ファイルをダウンロード | `chat:file` |
| DELETE | `/v1/files/:fileId`         | ファイルを削除     | `chat:file` |

※ Marketplace 版はスコープ不要（認証のみ）。

### POST`/v1/files`

ファイルをアップロードします。

#### リクエストボディ（multipart/form-data）

| パラメータ      | 型        | 必須 | 説明                         |
| ---------- | -------- | -- | -------------------------- |
| `file`     | `file`   | 必須 | アップロードするファイル。サイズ上限 512 MB。 |
| `filename` | `string` | 必須 | ファイル名                      |

#### リクエスト例

**Upload file**

**curl**

```curl
curl -X POST https://<your-domain>/api/v1/files \
-H "Authorization: Bearer <access_token>" \
-F "file=@report.pdf" \
-F "filename=report.pdf"
```

**Python**

```python
import requests

with open("report.pdf", "rb") as f:
  response = requests.post(
      "https://<your-domain>/api/v1/files",
      headers={"Authorization": f"Bearer {token}"},
      files={"file": f},
      data={"filename": "report.pdf"},
  )
  data = response.json()
  print(data["fileId"])
```

**TypeScript**

```typescript
const formData = new FormData();
formData.append("file", file); // File object from input
formData.append("filename", "report.pdf");

const response = await fetch(
"https://<your-domain>/api/v1/files",
{
  method: "POST",
  headers: { "Authorization": "Bearer " + accessToken },
  body: formData,
}
);

const data = await response.json();
console.log(data.fileId);
```

**Go**

```go
file, _ := os.Open("report.pdf")
defer file.Close()

body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, _ := writer.CreateFormFile("file", "report.pdf")
io.Copy(part, file)
writer.WriteField("filename", "report.pdf")
writer.Close()

req, _ := http.NewRequest("POST",
  "https://<your-domain>/api/v1/files",
  body)
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", writer.FormDataContentType())
```

#### レスポンスフィールド（201 Created）

| フィールド       | 型         | 説明                      |
| ----------- | --------- | ----------------------- |
| `fileId`    | `string`  | ファイルの一意識別子（UUID）        |
| `filename`  | `string`  | ファイル名                   |
| `bytes`     | `integer` | ファイルサイズ（バイト）            |
| `createdAt` | `string`  | 作成日時（ISO 8601）          |
| `width`     | `integer` | 画像の幅（ピクセル）。画像ファイルの場合のみ  |
| `height`    | `integer` | 画像の高さ（ピクセル）。画像ファイルの場合のみ |

#### レスポンス例

```json
{
  "fileId": "550e8400-e29b-41d4-a716-446655440001",
  "filename": "report.pdf",
  "bytes": 1048576,
  "createdAt": "2026-03-14T10:30:00.000Z"
}
```

#### エラーレスポンス

| ステータス | code                              | 説明                                                                              |
| ----- | --------------------------------- | ------------------------------------------------------------------------------- |
| `400` | `missing_parameter`               | file または filename パラメータが未指定                                                     |
| `400` | `file_too_large`                  | ファイルサイズが 512 MB を超過                                                             |
| `400` | `invalid_parameter`               | アップロードされた画像ファイルが破損している/不正                                                       |
| `415` | `unsupported_media_type`          | ボディが multipart/form-data ではない、またはファイルの種類を受け付けていない（環境で受け付けないと決めた拡張子・MIME タイプを含む） |
| `403` | `feature_not_permitted`           | 管理者がファイルの添付を許可していない                                                             |
| `503` | `feature_permissions_unavailable` | 機能の許可を確かめられない。時間をおいて送り直す                                                        |

### GET`/v1/files`

ファイル一覧を取得します。カーソルベースのページネーションに対応しています。

#### クエリパラメータ

| パラメータ    | 型         | 必須 | デフォルト    | 説明                                         |
| -------- | --------- | -- | -------- | ------------------------------------------ |
| `limit`  | `integer` | —  | `50`     | 1 ページの取得件数（1-100）                          |
| `cursor` | `string`  | —  | —        | 次ページ取得用カーソル（前回レスポンスの cursor 値）             |
| `order`  | `string`  | —  | `"desc"` | "asc"（古い順）または "desc"（新しい順）。並びの基準はファイルの更新日時 |

#### リクエスト例

**List files**

**curl**

```curl
curl https://<your-domain>/api/v1/files?order=desc \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
import requests

response = requests.get(
  "https://<your-domain>/api/v1/files",
  headers={"Authorization": f"Bearer {token}"},
  params={"order": "desc"},
)

files = response.json()["files"]
for file in files:
  print(f"{file['filename']} ({file['bytes']} bytes)")
```

**TypeScript**

```typescript
const params = new URLSearchParams({ order: "desc" });
const response = await fetch(
"https://<your-domain>/api/v1/files?" + params,
{
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const data = await response.json();
data.files.forEach((file) => {
console.log(file.filename + " (" + file.bytes + " bytes)");
});
```

**Go**

```go
req, _ := http.NewRequest("GET",
  "https://<your-domain>/api/v1/files?order=desc",
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

#### レスポンスフィールド（200 OK）

| フィールド               | 型         | 説明                                    |
| ------------------- | --------- | ------------------------------------- |
| `files`             | `array`   | ファイルオブジェクトの配列                         |
| `files[].fileId`    | `string`  | ファイルの一意識別子（UUID）                      |
| `files[].filename`  | `string`  | ファイル名                                 |
| `files[].bytes`     | `integer` | ファイルサイズ（バイト）                          |
| `files[].createdAt` | `string`  | 作成日時（ISO 8601）                        |
| `files[].width`     | `integer` | 画像の幅（ピクセル）。画像ファイルの場合のみ                |
| `files[].height`    | `integer` | 画像の高さ（ピクセル）。画像ファイルの場合のみ               |
| `hasMore`           | `boolean` | 次のページが存在するかどうか                        |
| `cursor`            | `string`  | 次ページ取得用カーソル。hasMore が true の場合のみ含まれます |

#### レスポンス例

```json
{
  "files": [
    {
      "fileId": "550e8400-e29b-41d4-a716-446655440001",
      "filename": "report.pdf",
      "bytes": 1048576,
      "createdAt": "2026-03-14T10:30:00.000Z"
    }
  ],
  "hasMore": false
}
```

#### ページネーション

`limit` を指定すると、その件数ずつ取得できます。`hasMore` が `true` の間、レスポンスの `cursor` をそのまま次のリクエストに渡してください。

**リクエスト例**

**curl**

```bash
# 1ページ目
curl "https://<your-domain>/api/v1/files?limit=50&order=desc" \
-H "Authorization: Bearer <access_token>"

# 2ページ目（1ページ目のレスポンスに含まれる cursor を指定）
curl "https://<your-domain>/api/v1/files?limit=50&order=desc&cursor=<cursor>" \
-H "Authorization: Bearer <access_token>"
```

`limit` を省略した場合は 50 件が返ります。全件を取得する場合は、`hasMore` が `false` になるまで `cursor` で続きを取得してください。

> **カーソル利用時の注意**
>
> `cursor` は取得位置を表すため、同じカーソルを使い続ける間は `order` を変更しないでください。条件を変えると対象範囲が変わり、項目の重複や取りこぼしが起きます。
>
> また、ページを取得している間にファイルが追加・削除された場合も、ページ間で重複や取りこぼしが生じることがあります。

#### エラーレスポンス

| ステータス | code                | 説明                        |
| ----- | ------------------- | ------------------------- |
| `400` | `invalid_parameter` | limit が 1-100 の整数でない      |
| `400` | `invalid_parameter` | cursor が不正（前回レスポンスの値以外）   |
| `400` | `invalid_parameter` | order が "asc" / "desc" 以外 |

### GET`/v1/files/:fileId/content`

ファイルをダウンロードします。

#### パスパラメータ

| パラメータ    | 型        | 必須 | 説明           |
| -------- | -------- | -- | ------------ |
| `fileId` | `string` | 必須 | ファイルID（UUID） |

#### リクエスト例

**Download file**

**curl**

```curl
curl https://<your-domain>/api/v1/files/550e8400-e29b-41d4-a716-446655440001/content \
-H "Authorization: Bearer <access_token>" \
-o downloaded_file.pdf
```

**Python**

```python
import requests

response = requests.get(
  "https://<your-domain>/api/v1/files/550e8400-e29b-41d4-a716-446655440001/content",
  headers={"Authorization": f"Bearer {token}"},
  stream=True,
)

with open("downloaded_file.pdf", "wb") as f:
  for chunk in response.iter_content(chunk_size=8192):
      f.write(chunk)
```

**TypeScript**

```typescript
const fs = require("fs");
const response = await fetch(
"https://<your-domain>/api/v1/files/550e8400-e29b-41d4-a716-446655440001/content",
{
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const buffer = await response.arrayBuffer();
fs.writeFileSync("downloaded_file.pdf", new Uint8Array(buffer));
```

**Go**

```go
req, _ := http.NewRequest("GET",
  "https://<your-domain>/api/v1/files/550e8400-e29b-41d4-a716-446655440001/content",
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

file, _ := os.Create("downloaded_file.pdf")
defer file.Close()
io.Copy(file, resp.Body)
```

#### レスポンス（200 OK）

ファイルのバイナリデータがストリームで返されます。

| レスポンスヘッダー             | 説明                                                                        |
| --------------------- | ------------------------------------------------------------------------- |
| `Content-Type`        | ファイルの MIME タイプ                                                            |
| `Content-Length`      | ファイルサイズ（バイト）                                                              |
| `Content-Disposition` | attachment; filename="ファイル名"; filename\*=UTF-8''\<UTF-8 をパーセント符号化したファイル名> |

保存するときのファイル名は、`filename*`（UTF-8 をパーセント符号化した名前）があればそちらを使い、無ければ `filename` を使います。日本語などを含む名前では、`filename` は代わりの名前になり、元の名前は `filename*` にだけ入ります。例えば `売上.pdf` のときは次のようになります（`filename` の代わりの名前は一例です）。

```text
Content-Disposition: attachment; filename="file_1731650000000.pdf"; filename*=UTF-8''%E5%A3%B2%E4%B8%8A.pdf
```

#### エラーレスポンス

| ステータス | code                  | 説明                                                         |
| ----- | --------------------- | ---------------------------------------------------------- |
| `400` | `invalid_parameter`   | fileId が不正なフォーマット                                          |
| `404` | `file_not_found`      | ファイルが見つからない                                                |
| `503` | `service_unavailable` | 認証の仕組みが一時的に使えない。少し待ってから送り直してください。続くときは、サービスの管理者に問い合わせてください |

### DELETE`/v1/files/:fileId`

ファイルを削除します。会話を削除したときも、その会話だけで使っていたファイルは削除されます（[会話を削除](#delete-conversation)）。

#### パスパラメータ

| パラメータ    | 型        | 必須 | 説明           |
| -------- | -------- | -- | ------------ |
| `fileId` | `string` | 必須 | ファイルID（UUID） |

#### リクエスト例

**Delete file**

**curl**

```curl
curl -X DELETE https://<your-domain>/api/v1/files/550e8400-e29b-41d4-a716-446655440001 \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
import requests

response = requests.delete(
  "https://<your-domain>/api/v1/files/550e8400-e29b-41d4-a716-446655440001",
  headers={"Authorization": f"Bearer {token}"},
)

data = response.json()
print(f"File deleted: {data['deleted']}")
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/files/550e8400-e29b-41d4-a716-446655440001",
{
  method: "DELETE",
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const data = await response.json();
console.log("File deleted: " + data.deleted);
```

**Go**

```go
req, _ := http.NewRequest("DELETE",
  "https://<your-domain>/api/v1/files/550e8400-e29b-41d4-a716-446655440001",
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

#### レスポンスフィールド（200 OK）

| フィールド     | 型         | 説明                 |
| --------- | --------- | ------------------ |
| `fileId`  | `string`  | 削除されたファイルのID（UUID） |
| `deleted` | `boolean` | 削除成功時は常に true      |

#### レスポンス例

```json
{ "fileId": "550e8400-e29b-41d4-a716-446655440001", "deleted": true }
```

#### エラーレスポンス

| ステータス | code                | 説明                |
| ----- | ------------------- | ----------------- |
| `400` | `invalid_parameter` | fileId が不正なフォーマット |
| `404` | `file_not_found`    | ファイルが見つからない       |

## 成果物取得

エージェントが生成した成果物ファイルを取得します。

### エンドポイント一覧

| メソッド | エンドポイント           | 説明         | スコープ (SaaS) |
| ---- | ----------------- | ---------- | ----------- |
| GET  | `/v1/files/proxy` | 成果物ファイルを取得 | `chat:exec` |

※ Marketplace 版はスコープ不要（認証のみ）。

### GET`/v1/files/proxy`

メッセージ履歴の `deliverables[].filepath` で取得したパスを指定して、成果物ファイルをダウンロードします。

<!-- -->

マーケットプレイス版ではスコープによる制限はありません。認証済みのトークンがあれば取得できます。

<!-- -->

<!-- -->

#### クエリパラメータ

| パラメータ  | 型        | 必須 | 説明                                                |
| ------ | -------- | -- | ------------------------------------------------- |
| `path` | `string` | 必須 | 成果物のファイルパス（メッセージ履歴の deliverables\[].filepath で取得） |

#### リクエスト例

`filepath` は [メッセージ履歴の取得](#get-messages) の `messages[].deliverables[].filepath` の値です。

**Get artifact file**

**curl**

```curl
FILEPATH='<filepath>'

curl --get "https://<your-domain>/api/v1/files/proxy" \
--data-urlencode "path=$FILEPATH" \
-H "Authorization: Bearer <access_token>" \
-o artifact.xlsx
```

**Python**

```python
import requests

filepath = "<filepath>"

response = requests.get(
  "https://<your-domain>/api/v1/files/proxy",
  headers={"Authorization": "Bearer " + token},
  params={"path": filepath},
  stream=True,
)

with open("artifact.xlsx", "wb") as f:
  for chunk in response.iter_content(chunk_size=8192):
      f.write(chunk)
```

**TypeScript**

```typescript
const filepath = "<filepath>";

const params = new URLSearchParams({
path: filepath,
});
const response = await fetch(
"https://<your-domain>/api/v1/files/proxy?" + params,
{
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const blob = await response.blob();
```

**Go**

```go
import (
  "io"
  "net/http"
  "net/url"
  "os"
)

filepath := "<filepath>"

req, _ := http.NewRequest("GET",
  "https://<your-domain>/api/v1/files/proxy?"+url.Values{"path": {filepath}}.Encode(),
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

out, _ := os.Create("artifact.xlsx")
defer out.Close()
io.Copy(out, resp.Body)
```

#### レスポンス（200 OK）

成果物ファイルのバイナリデータがストリームで返されます。

| レスポンスヘッダー        | 説明             |
| ---------------- | -------------- |
| `Content-Type`   | ファイルの MIME タイプ |
| `Content-Length` | ファイルサイズ（バイト）   |

#### エラーレスポンス

| ステータス | code                  | 説明                                                         |
| ----- | --------------------- | ---------------------------------------------------------- |
| `400` | `missing_parameter`   | path パラメータが未指定                                             |
| `400` | `invalid_parameter`   | path のフォーマットが不正（UUID の形の段が無い）                              |
| `404` | `not_found`           | ファイルが見つからない（保存先の応答に別の code があるときはその code）                  |
| `500` | `unknown`             | 保存先の不明な誤り                                                  |
| `500` | `storage_forbidden`   | 保存先へのアクセスが拒否された。管理者に連絡してください                               |
| `500` | `rejected`            | 保存先がリクエストを断った。管理者に連絡してください                                 |
| `503` | `rate_limited`        | 保存先が一時的に混んでいる。時間をおいて再試行してください                              |
| `503` | `transient`           | 保存先が一時的に使えない。時間をおいて再試行してください                               |
| `503` | `service_unavailable` | 認証の仕組みが一時的に使えない。少し待ってから送り直してください。続くときは、サービスの管理者に問い合わせてください |

## 検索

メッセージを全文検索します。

### エンドポイント一覧

| メソッド | エンドポイント               | 説明         | スコープ (SaaS)    |
| ---- | --------------------- | ---------- | -------------- |
| GET  | `/v1/search/messages` | メッセージを全文検索 | `chat:history` |

※ Marketplace 版はスコープ不要（認証のみ）。

### GET`/v1/search/messages`

メッセージを全文検索します。プロジェクトの工程の会話のメッセージと、アーカイブ済みの会話のメッセージは、検索の対象になりません。検索結果は作成日時の新しい順（`order=asc` で古い順）に、カーソルベースのページネーションで返します。

#### クエリパラメータ

| パラメータ    | 型         | 必須 | 説明                                                                         |
| -------- | --------- | -- | -------------------------------------------------------------------------- |
| `q`      | `string`  | 必須 | 検索クエリ                                                                      |
| `order`  | `string`  | —  | ソート順。"asc"（昇順）または "desc"（降順、デフォルト）                                         |
| `limit`  | `integer` | —  | 1 ページの件数（1〜100）。デフォルトは 50 件です                                              |
| `cursor` | `string`  | —  | 次のページを取得するためのカーソル値。前回のレスポンスに含まれる cursor をそのまま指定します。q と order は前回と同じにしてください |

#### リクエスト例

**Search messages**

**curl**

```curl
curl "https://<your-domain>/api/v1/search/messages?q=売上" \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
import requests
from urllib.parse import quote

query = "売上"
response = requests.get(
  "https://<your-domain>/api/v1/search/messages",
  headers={"Authorization": f"Bearer {token}"},
  params={"q": query, "order": "desc"},
)

messages = response.json()["messages"]
for msg in messages:
  print(f"{msg['title']}: {msg['text'][:50]}")
```

**TypeScript**

```typescript
const query = "売上";
const params = new URLSearchParams({ q: query, order: "desc" });
const response = await fetch(
"https://<your-domain>/api/v1/search/messages?" + params,
{
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const data = await response.json();
data.messages.forEach((msg) => {
console.log(msg.title + ": " + msg.text);
});
```

**Go**

```go
query := "売上"
req, _ := http.NewRequest("GET",
  fmt.Sprintf("https://<your-domain>/api/v1/search/messages?q=%s&order=desc",
      url.QueryEscape(query)),
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

#### レスポンスフィールド（200 OK）

| フィールド                                 | 型         | 説明                                                                                                                                                                                   |
| ------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `messages`                            | `array`   | 検索結果のメッセージ配列（1 ページ分。limit 件まで）                                                                                                                                                       |
| `messages[].conversationId`           | `string`  | 会話ID（UUID）                                                                                                                                                                           |
| `messages[].messageId`                | `string`  | メッセージの一意識別子                                                                                                                                                                          |
| `messages[].text`                     | `string`  | メッセージの本文テキスト                                                                                                                                                                         |
| `messages[].title`                    | `string`  | 会話のタイトル                                                                                                                                                                              |
| `messages[].sender`                   | `string`  | 送信者。"User" または "AI"                                                                                                                                                                  |
| `messages[].createdAt`                | `string`  | 作成日時（ISO 8601）                                                                                                                                                                       |
| `messages[].updatedAt`                | `string`  | 最終更新日時（ISO 8601）                                                                                                                                                                     |
| `messages[].matchedQueries`           | `array`   | 一致した検索クエリの配列                                                                                                                                                                         |
| `messages[].status`                   | `object`  | メッセージの処理状態                                                                                                                                                                           |
| `messages[].status.processing`        | `boolean` | エージェントが現在処理中かどうか                                                                                                                                                                     |
| `messages[].status.unfinished`        | `boolean` | エージェントの応答が中断されたかどうか                                                                                                                                                                  |
| `messages[].tasks`                    | `array`   | エージェントが実行したタスクの配列。フィールド定義は [GET /v1/conversations/:conversationId/messages](#get-messages) の Task オブジェクトを参照                                                                          |
| `messages[].deliverables`             | `array`   | エージェントが生成した成果物の配列。存在する場合のみ含まれます                                                                                                                                                      |
| `messages[].deliverables[].filename`  | `string`  | 成果物のファイル名                                                                                                                                                                            |
| `messages[].deliverables[].filepath`  | `string`  | 成果物のファイルパス                                                                                                                                                                           |
| `messages[].deliverables[].source`    | `string`  | `"agent"`（エージェント生成）または `"user"`（ユーザーアップロード）                                                                                                                                          |
| `messages[].deliverables[].isPrimary` | `boolean` | 主要成果物かどうか                                                                                                                                                                            |
| `messages[].deliverables[].createdAt` | `string`  | 作成日時（ISO 8601形式）。分からないときは空文字                                                                                                                                                         |
| `messages[].deliverables[].mimeType`  | `string`  | MIME タイプ（例: `"application/pdf"`、`"text/markdown"`）。判定できない場合は `"application/octet-stream"`                                                                                            |
| `messages[].deliverables[].size`      | `number?` | ファイルサイズ（バイト）。0 以下の場合は省略                                                                                                                                                              |
| `messages[].files`                    | `array?`  | ユーザーが添付したファイルの配列。`sender: "User"` のメッセージで添付がある場合のみ含まれます。フィールド構造は履歴 API と同じ（`fileId` / `mimeType` / `width?` / `height?`）。詳細は [GET /v1/conversations/:id/messages](#get-messages) を参照 |
| `hasMore`                             | `boolean` | 続きのページがあれば true。true のときは cursor が返ります                                                                                                                                               |
| `cursor`                              | `string`  | 次のページを取得するためのカーソル値。hasMore が true のときだけ含まれます                                                                                                                                         |
| `limitReached`                        | `boolean` | 一致したメッセージが多く、一致の度合いの高い上位の結果（本文の一致と、エージェントの作業の経過の一致のそれぞれ 1,000 件まで）だけを対象にしているときだけ true。そうでないときは含まれません。もれなく探すときは検索クエリを絞ってください                                                          |

#### レスポンス例

```json
{
  "messages": [
    {
      "conversationId": "550e8400-...",
      "messageId": "msg-abc123",
      "text": "売上データを分析した結果...",
      "title": "売上データ分析",
      "sender": "AI",
      "createdAt": "2026-03-14T10:30:00Z",
      "updatedAt": "2026-03-14T10:35:00Z",
      "matchedQueries": ["売上"],
      "tasks": []
    }
  ],
  "hasMore": false
}
```

#### エラーレスポンス

| ステータス | 説明                                                                                                                  |
| ----- | ------------------------------------------------------------------------------------------------------------------- |
| `400` | q パラメータが未指定、または 1 つの文字列として指定されていない（q を複数回指定した場合など）。order が "asc" / "desc" 以外、limit が 1〜100 の整数ではない、または cursor が読めない |
| `501` | 検索の設定が無い環境（`code: "search_not_configured"`）                                                                         |
| `503` | 検索が一時的に使えない（`code: "service_unavailable"`）。時間をおいて送り直してください                                                          |

## ユーザー

ユーザー情報の取得・更新・パスワード変更を行います。

### エンドポイント一覧

| メソッド  | エンドポイント             | 説明        |
| ----- | ------------------- | --------- |
| GET   | `/v1/user`          | ユーザー情報を取得 |
| PATCH | `/v1/user`          | ユーザー情報を更新 |
| POST  | `/v1/user/password` | パスワードを変更  |

### GET`/v1/user`

ユーザー情報を取得します。

#### リクエスト例

**Get user**

**curl**

```curl
curl https://<your-domain>/api/v1/user \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
import requests

response = requests.get(
  "https://<your-domain>/api/v1/user",
  headers={"Authorization": f"Bearer {token}"},
)

user = response.json()
print(f"User: {user['username']} ({user['email']})")
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/user",
{
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const user = await response.json();
console.log("User: " + user.username + " (" + user.email + ")");
```

**Go**

```go
req, _ := http.NewRequest("GET",
  "https://<your-domain>/api/v1/user",
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var user map[string]interface{}
json.NewDecoder(resp.Body).Decode(&user)
fmt.Printf("User: %s (%s)\n", user["username"], user["email"])
```

#### レスポンスフィールド（200 OK）

| フィールド                | 型         | 説明                          |
| -------------------- | --------- | --------------------------- |
| `userId`             | `string`  | ユーザーの一意識別子                  |
| `email`              | `string`  | メールアドレス                     |
| `username`           | `string`  | ユーザー名                       |
| `emailVerified`      | `boolean` | メールアドレスの確認状態                |
| `createdAt`          | `string`  | アカウント作成日時（ISO 8601）         |
| `isApproved`         | `boolean` | アカウントの承認状態                  |
| `role`               | `string`  | ユーザーのロール                    |
| `organization`       | `object`  | 所属組織（設定されている場合のみ）           |
| `organization.value` | `string`  | 組織コード                       |
| `organization.label` | `string`  | 組織名                         |
| `jobType`            | `object`  | 職種（設定されている場合のみ）             |
| `jobType.value`      | `string`  | 職種コード                       |
| `jobType.label`      | `string`  | 職種名                         |
| `bio`                | `string`  | 自己紹介（設定されている場合のみ）           |
| `lastLoginAt`        | `string`  | 最終ログイン日時（ISO 8601、存在する場合のみ） |

#### レスポンス例

```json
{
  "userId": "user-abc123",
  "email": "tanaka@example.com",
  "username": "田中太郎",
  "emailVerified": true,
  "createdAt": "2026-03-10T09:00:00.000Z",
  "isApproved": true,
  "role": "user",
  "organization": { "value": "eng", "label": "エンジニアリング部門" },
  "jobType": { "value": "dev", "label": "開発者" },
  "bio": "AIエンジニア",
  "lastLoginAt": "2026-03-14T10:00:00.000Z"
}
```

#### エラーレスポンス

| ステータス | code             | 説明                               |
| ----- | ---------------- | -------------------------------- |
| `500` | `internal_error` | ユーザー情報を取得できなかった（時間をおいて再試行してください） |

### PATCH`/v1/user`

ユーザー情報を更新します。

#### リクエストボディ

| パラメータ          | 型        | 必須 | 説明                                                                                                                              |
| -------------- | -------- | -- | ------------------------------------------------------------------------------------------------------------------------------- |
| `username`     | `string` | —  | ユーザー名。2〜50 文字で、「<」「>」「"」「'」は使えません                                                                                               |
| `organization` | `string` | —  | 組織コード。100 文字まで。未設定のときだけ設定でき、有効な組織コードだけを設定できます。設定済みの組織を変える（空にするのも）と 403 になります。変更は管理者に依頼してください。IdP から同期しているときは、ID 基盤（IdP）で変えてください |
| `jobType`      | `string` | —  | 職種コード。100 文字まで。未設定のときだけ設定でき、有効な職種コードだけを設定できます。設定済みの職種を変える（空にするのも）と 403 になります。変更は管理者に依頼してください。IdP から同期しているときは、ID 基盤（IdP）で変えてください |
| `bio`          | `string` | —  | 自己紹介。150 文字までで、「<」「>」「"」「'」は使えません                                                                                               |

#### リクエスト例

**Update user**

**curl**

```curl
curl -X PATCH https://<your-domain>/api/v1/user \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{ "username": "田中太郎", "bio": "エンジニアリング部門" }'
```

**Python**

```python
import requests

response = requests.patch(
  "https://<your-domain>/api/v1/user",
  headers={"Authorization": f"Bearer {token}"},
  json={"username": "田中太郎", "bio": "エンジニアリング部門"},
)

user = response.json()
print(f"Updated: {user['username']}")
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/user",
{
  method: "PATCH",
  headers: {
    "Authorization": "Bearer " + accessToken,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    username: "田中太郎",
    bio: "エンジニアリング部門",
  }),
}
);

const user = await response.json();
console.log("Updated: " + user.username);
```

**Go**

```go
payload := map[string]string{
  "username": "田中太郎",
  "bio": "エンジニアリング部門",
}
body, _ := json.Marshal(payload)

req, _ := http.NewRequest("PATCH",
  "https://<your-domain>/api/v1/user",
  bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
```

#### レスポンスフィールド（200 OK）

GET /v1/user と同じユーザーオブジェクトが返されます（更新後の値を含む）。

#### レスポンス例

```json
{
  "userId": "user-abc123",
  "email": "tanaka@example.com",
  "username": "田中太郎",
  "emailVerified": true,
  "createdAt": "2026-03-10T09:00:00.000Z",
  "isApproved": true,
  "role": "user",
  "organization": { "value": "eng", "label": "エンジニアリング部門" },
  "jobType": { "value": "dev", "label": "開発者" },
  "bio": "エンジニアリング部門",
  "lastLoginAt": "2026-03-14T10:00:00.000Z"
}
```

#### エラーレスポンス

| ステータス | code                     | 説明                                                                                                               |
| ----- | ------------------------ | ---------------------------------------------------------------------------------------------------------------- |
| `400` | `invalid_parameter`      | 更新するフィールドが未指定                                                                                                    |
| `400` | `invalid_body`           | ボディが壊れた JSON                                                                                                     |
| `400` | `invalid_parameter`      | 入力の誤り（username / organization / jobType / bio が文字列ではない、文字数・使えない文字、または初めて設定する organization / jobType が有効なコードではない） |
| `403` | `affiliation_locked`     | 設定済みの organization / jobType を変えようとした（空にするのも）。変更は管理者に依頼してください。IdP から同期しているときは、ID 基盤（IdP）で変えてください                 |
| `409` | `conflict`               | 同じユーザーの別の更新を処理している。少し待ってから送り直してください                                                                              |
| `415` | `unsupported_media_type` | ボディの Content-Type が application/json ではない                                                                        |

### POST`/v1/user/password`

パスワードを変更します。

#### リクエストボディ

| パラメータ             | 型        | 必須 | 説明            |
| ----------------- | -------- | -- | ------------- |
| `currentPassword` | `string` | 必須 | 現在のパスワード      |
| `newPassword`     | `string` | 必須 | 新しいパスワード      |
| `confirmPassword` | `string` | 必須 | 新しいパスワード（確認用） |

#### リクエスト例

**Change password**

**curl**

```curl
curl -X POST https://<your-domain>/api/v1/user/password \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{
  "currentPassword": "OldPass123!",
  "newPassword": "NewPass456!",
  "confirmPassword": "NewPass456!"
}'
```

**Python**

```python
import requests

response = requests.post(
  "https://<your-domain>/api/v1/user/password",
  headers={"Authorization": f"Bearer {token}"},
  json={
      "currentPassword": "OldPass123!",
      "newPassword": "NewPass456!",
      "confirmPassword": "NewPass456!",
  },
)

data = response.json()
print(f"Password changed: {data['changed']}")
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/user/password",
{
  method: "POST",
  headers: {
    "Authorization": "Bearer " + accessToken,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    currentPassword: "OldPass123!",
    newPassword: "NewPass456!",
    confirmPassword: "NewPass456!",
  }),
}
);

const data = await response.json();
console.log("Password changed: " + data.changed);
```

**Go**

```go
payload := map[string]string{
  "currentPassword": "OldPass123!",
  "newPassword": "NewPass456!",
  "confirmPassword": "NewPass456!",
}
body, _ := json.Marshal(payload)

req, _ := http.NewRequest("POST",
  "https://<your-domain>/api/v1/user/password",
  bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
```

#### レスポンスフィールド（200 OK）

| フィールド     | 型         | 説明                 |
| --------- | --------- | ------------------ |
| `userId`  | `string`  | ユーザーの一意識別子         |
| `changed` | `boolean` | パスワード変更成功時は常に true |

#### レスポンス例

```json
{ "userId": "user-abc123", "changed": true }
```

パスワードを変えたら、変える前に取ったトークンは使い続けず、もう一度ログインしてトークンを取り直してください。変える前のアクセストークンは、期限まで API に通ります。

パスワードを変えると、本人のチャットの画面のログインも、すべての端末で、次に操作したときに切れます。

#### エラーレスポンス

| ステータス | 説明                                                                                                                                     |
| ----- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `400` | 必須パラメータの不足、currentPassword / newPassword / confirmPassword が文字列ではない、ボディが壊れた JSON（`code: "invalid_body"`）、パスワードバリデーション失敗、または現在のパスワードが不正 |
| `415` | ボディの Content-Type が application/json ではない（`code: "unsupported_media_type"`）                                                            |
| `401` | 認証トークンが無効                                                                                                                              |

## マスターデータ

組織・ジョブタイプ等のマスターデータを取得します。

### エンドポイント一覧

| メソッド | エンドポイント             | 説明          |
| ---- | ------------------- | ----------- |
| GET  | `/v1/organizations` | 組織一覧を取得     |
| GET  | `/v1/job-types`     | ジョブタイプ一覧を取得 |

### GET`/v1/organizations`

組織一覧を取得します。無効化された組織は含まれません。

#### リクエスト例

**List organizations**

**curl**

```curl
curl https://<your-domain>/api/v1/organizations \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
import requests

response = requests.get(
  "https://<your-domain>/api/v1/organizations",
  headers={"Authorization": f"Bearer {token}"},
)

data = response.json()
for org in data["organizations"]:
  print(f"{org['value']}: {org['label']}")
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/organizations",
{
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const data = await response.json();
data.organizations.forEach((org) => {
console.log(org.value + ": " + org.label);
});
```

**Go**

```go
req, _ := http.NewRequest("GET",
  "https://<your-domain>/api/v1/organizations",
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

#### レスポンスフィールド（200 OK）

| フィールド                   | 型         | 説明                    |
| ----------------------- | --------- | --------------------- |
| `organizations`         | `array`   | 組織オブジェクトの配列           |
| `organizations[].value` | `string`  | 組織コード                 |
| `organizations[].label` | `string`  | 組織名                   |
| `hasMore`               | `boolean` | 常に false（ページネーション非対応） |

#### レスポンス例

```json
{
  "organizations": [
    { "value": "eng", "label": "エンジニアリング部門" },
    { "value": "sales", "label": "営業部門" }
  ],
  "hasMore": false
}
```

#### エラーレスポンス

| ステータス | code             | 説明                              |
| ----- | ---------------- | ------------------------------- |
| `500` | `internal_error` | 組織の一覧を取得できなかった（時間をおいて再試行してください） |

### GET`/v1/job-types`

ジョブタイプ一覧を取得します。無効化されたジョブタイプは含まれません。

#### リクエスト例

**List job types**

**curl**

```curl
curl https://<your-domain>/api/v1/job-types \
-H "Authorization: Bearer <access_token>"
```

**Python**

```python
import requests

response = requests.get(
  "https://<your-domain>/api/v1/job-types",
  headers={"Authorization": f"Bearer {token}"},
)

job_types = response.json()["jobTypes"]
for jt in job_types:
  print(f"{jt['value']}: {jt['label']}")
```

**TypeScript**

```typescript
const response = await fetch(
"https://<your-domain>/api/v1/job-types",
{
  headers: { "Authorization": "Bearer " + accessToken },
}
);

const data = await response.json();
data.jobTypes.forEach((jt) => {
console.log(jt.value + ": " + jt.label);
});
```

**Go**

```go
req, _ := http.NewRequest("GET",
  "https://<your-domain>/api/v1/job-types",
  nil)
req.Header.Set("Authorization", "Bearer "+token)

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
```

#### レスポンスフィールド（200 OK）

| フィールド              | 型         | 説明                    |
| ------------------ | --------- | --------------------- |
| `jobTypes`         | `array`   | ジョブタイプオブジェクトの配列       |
| `jobTypes[].value` | `string`  | 職種コード                 |
| `jobTypes[].label` | `string`  | 職種名                   |
| `hasMore`          | `boolean` | 常に false（ページネーション非対応） |

#### レスポンス例

```json
{
  "jobTypes": [
    { "value": "dev", "label": "開発者" },
    { "value": "pm", "label": "プロジェクトマネージャー" }
  ],
  "hasMore": false
}
```

#### エラーレスポンス

| ステータス | code             | 説明                                  |
| ----- | ---------------- | ----------------------------------- |
| `500` | `internal_error` | ジョブタイプの一覧を取得できなかった（時間をおいて再試行してください） |

<!-- -->

## プロジェクト

プロジェクトの API は、[ユーザー API リファレンス（プロジェクト）](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/reference/user-api-reference-projects.md)に載せています。

## エラーレスポンス

### HTTP ステータスコード

すべてのエンドポイントで返される可能性のある HTTP ステータスコードです。

| ステータス                        | 説明                                                                                                                                                                                        |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400 Bad Request`            | リクエストパラメータが不正                                                                                                                                                                             |
| `401 Unauthorized`           | トークンが無効または未指定。管理者に利用を止められた利用者のトークンでも返ります（下の「利用を止められた利用者」）                                                                                                                                 |
| `403 Forbidden`              | リソースへのアクセス権限なし                                                                                                                                                                            |
| `404 Not Found`              | リソースが存在しない、または未定義のパス・メソッド（405 は返しません）                                                                                                                                                     |
| `409 Conflict`               | リソースが現在処理中など、操作が競合                                                                                                                                                                        |
| `409 Conflict`               | 組織の運用の役割（管理コンソールの「管理の役割」で付ける「運用」の役割）の人が、プロジェクトに参加せずに、その役割では使えない操作を呼んだ（`error.code` は `forbidden_role`）。待っても直りません。オーナーだけの操作は、プロジェクトのオーナーに頼んでください。ほかの操作は、オーナーにプロジェクトに加えてもらうと、参加の役割のとおりに呼べます |
| `413 Payload Too Large`      | リクエストボディがサイズ上限を超過                                                                                                                                                                         |
| `415 Unsupported Media Type` | リクエストボディの形式（Content-Type）に対応していない                                                                                                                                                         |
| `429 Too Many Requests`      | レート制限または同時実行の上限を超過。`error.type` は `rate_limit_error` で、`error.code` はエンドポイントにより異なります（例: 月間上限は `monthly_quota_exceeded`、プロジェクトの同時実行は `too_many_active_runs`）。時間をおいて再試行してください               |
| `500 Internal Server Error`  | サーバー内部エラー                                                                                                                                                                                 |
| `502 Bad Gateway`            | 上流サービス（認証基盤・チャット基盤等）との通信エラー                                                                                                                                                               |
| `503 Service Unavailable`    | サービス一時利用不可                                                                                                                                                                                |
| `504 Gateway Timeout`        | 上流サービスの応答タイムアウト                                                                                                                                                                           |

### エラーレスポンス形式

すべてのエラーレスポンスは以下の共通構造で返されます。

| フィールド                    | 型        | 説明                                                                                                                                                                                                                                       |
| ------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `error.type`             | `string` | エラーの分類。"invalid\_request\_error"、"authentication\_error"、"insufficient\_scope\_error"、"forbidden\_error"、"not\_found\_error"、"conflict\_error"、"payload\_too\_large\_error"、"rate\_limit\_error"、"server\_error"、"upstream\_error" のいずれか |
| `error.message`          | `string` | 人間が読めるエラーメッセージ                                                                                                                                                                                                                           |
| `error.code`             | `string` | 機械的に処理可能なエラーコード（例: "missing\_parameter"、"invalid\_parameter"、"invalid\_token"）                                                                                                                                                           |
| `error.param`            | `string` | エラーの原因となったパラメータ名。バリデーションエラー時のみ含まれます                                                                                                                                                                                                      |
| `error.reason`           | `string` | 断りの理由の種類。プロジェクト API の 409（definition\_invalid）のときだけ含まれます                                                                                                                                                                                 |
| `error.suggested_action` | `string` | 推奨される対処方法。一部のエラーでのみ含まれます                                                                                                                                                                                                                 |

```json
{
  "error": {
    "type": "invalid_request_error",
    "message": "Invalid parameter: limit",
    "code": "invalid_parameter",
    "param": "limit",
    "suggested_action": "limit must be between 1 and 100"
  }
}
```

### 利用を止められた利用者

管理者に利用を止められた利用者のトークンで呼ぶと、`401 Unauthorized` が返ります。`error.code` は `account_suspended` です。

次の API は、利用を止められたかどうかを見ません: `GET /v1/organizations`・`GET /v1/job-types`・`GET /v1/user`・`PATCH /v1/user`・`GET /v1/marketplace-agents`、MCP の `list_agents` と、進行中のタスクが無いときの `cancel_chat`、登録 Agent の Agent Card（`GET /api/v1/a2a/agents/{agentId}/.well-known/agent-card.json`）。
