# システム連携 API リファレンス

マーケットプレイス版のシステム連携 API のエンドポイント仕様とエラーコードのリファレンスです。

> **注記**
>
> マーケットプレイス版で利用できるのは、チャット・会話管理・ファイル管理・成果物取得・検索です。ライブラリ・スキル・プレイブック・ユーザー・マスターデータ・ユーザー管理・ログ・共有メモリ・プロジェクトの各 API は SaaS 版でのみ提供されます。SaaS 版の仕様は [ユーザー API リファレンス（SaaS 版）](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/reference/api-reference.md) と [システム連携 API リファレンス（SaaS 版）](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/reference/admin-api-reference.md) を参照してください。

## ベース URL

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

Marketplace

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

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

## 認証

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

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

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

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

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

## ページネーション

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

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

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

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

## チャット

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

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

SSE ストリーミングガイド

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

[ガイドを見る](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/basic/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（必須）。                                                                                        |
| `outputFormat` | `string` | 応答テキストの形式。"plain"（省略時）は Markdown 記法を除去したプレーンテキスト（図は削除され、コードブロックは本文が残る）。"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",
  "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",
      "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",
    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",
      "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/basic/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件を超過）。または、指定した `conversationId` がアーカイブ済み（`code: "conversation_archived"`） |
| `404` | 指定した input\_file の `fileId` が見つからない                                                                                                                                                     |
| `409` | 指定した会話が現在処理中                                                                                                                                                                            |

### 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/basic/api/guide/streaming-guide.md)を参照してください。

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

| ステータス | 説明                  |
| ----- | ------------------- |
| `400` | conversationId が不正  |
| `404` | 会話が見つからない、または進行中でない |

### 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 が不正、会話がアーカイブ済み（`code: "conversation_archived"`）、`messageId` のメッセージが別の会話のもの（`code: "conversation_mismatch"`）、または接続先のエージェントがキャンセルに対応していない（`code: "unsupported_endpoint"`・`code: "post_processing_not_enabled"`） |
| `404` | 会話が見つからない（`code: "conversation_not_found"`）、`messageId` のメッセージが見つからない（`code: "message_not_found"`）、または `messageId` のメッセージが処理中でない（`code: "not_processing"`）                                                                   |

## 会話管理

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

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

| メソッド   | エンドポイント                                      | 説明           | スコープ (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` |

※ 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[].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": "売上データ分析",
      "createdAt": "2026-03-14T10:30:00Z",
      "updatedAt": "2026-03-14T10:35:00Z"
    }
  ],
  "hasMore": true,
  "cursor": "eyJrIjoiMjAyNi0wMy0xNFQxMDozMDowMC4wMDBaIn0"
}
```

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

| ステータス | 説明                                                           |
| ----- | ------------------------------------------------------------ |
| `400` | limit パラメータが不正（1〜100の範囲外）、または mode が "active" / "archive" 以外 |

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

指定した会話のメッセージ履歴を取得します。カーソルベースのページネーションに対応しています。

#### パスパラメータ

| パラメータ            | 型        | 必須 | 説明          |
| ---------------- | -------- | -- | ----------- |
| `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`   | メッセージの本文テキスト                                                                                      |
| `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"`）。判定できない場合は省略                                    |
| `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` または `pending`）を入れます。値は固定の一覧ではないので、決まった値だけを想定しないでください                                                                       |
| `content`        | `string?` | タスクの実行結果テキスト。存在しない場合は省略される                                                                                                                                                         |
| `metadata`       | `object?` | actionType ごとに異なる補助情報（sub\_event\_type、url、filepath など）。詳細は [ストリーミングガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/basic/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/basic/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
}
```

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

| ステータス | 説明                        |
| ----- | ------------------------- |
| `400` | conversationId が不正なフォーマット |
| `400` | limit が 1-100 の整数でない      |
| `400` | cursor が不正（前回レスポンスの値以外）   |
| `404` | 会話が見つからない                 |

<!-- -->

### 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` | 更新後のタイトル          |
| `createdAt`      | `string` | 会話の作成日時（ISO 8601） |
| `updatedAt`      | `string` | 会話の更新日時（ISO 8601） |

#### レスポンス例

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

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

| ステータス | 説明                                                                            |
| ----- | ----------------------------------------------------------------------------- |
| `400` | title が未指定、空文字、もしくは 200 文字を超える、または会話がアーカイブ済み（`code: "conversation_archived"`） |
| `404` | 会話が見つからない                                                                     |

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

会話を削除します。

#### パスパラメータ

| パラメータ            | 型        | 必須 | 説明          |
| ---------------- | -------- | -- | ----------- |
| `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 }
```

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

| ステータス | 説明                                                                                                              |
| ----- | --------------------------------------------------------------------------------------------------------------- |
| `400` | conversationId が不正、または会話がアーカイブ済み（`code: "conversation_archived"`、復元には `POST /v1/conversations/:id/restore` を使用） |
| `404` | 会話が見つからない                                                                                                       |
| `409` | 会話が現在処理中のため削除できない                                                                                               |

### 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 }
```

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

| ステータス | 説明                                                |
| ----- | ------------------------------------------------- |
| `400` | conversationId が不正                                |
| `404` | アーカイブに該当会話が存在しない、または既に active（archive 状態と区別されません） |

## ファイル管理

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

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

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

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

| ステータス | 説明                                                                           |
| ----- | ---------------------------------------------------------------------------- |
| `400` | file または filename パラメータが未指定、ファイルサイズが 512 MB を超過、またはアップロードされた画像ファイルが破損している/不正 |

### 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` を変更しないでください。条件を変えると対象範囲が変わり、項目の重複や取りこぼしが起きます。
>
> また、ページを取得している間にファイルが追加・削除された場合も、ページ間で重複や取りこぼしが生じることがあります。

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

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

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

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

#### パスパラメータ

| パラメータ     | 型        | 必須 | 説明           |
| --------- | -------- | -- | ------------ |
| `file_id` | `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
```

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

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

### DELETE`/v1/files/:file_id`

ファイルを削除します。

#### パスパラメータ

| パラメータ     | 型        | 必須 | 説明           |
| --------- | -------- | -- | ------------ |
| `file_id` | `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 }
```

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

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

## 成果物取得

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

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

| メソッド | エンドポイント           | 説明         | スコープ (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` | ファイルサイズ（バイト）   |

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

| ステータス | 説明                        |
| ----- | ------------------------- |
| `400` | path パラメータが未指定またはフォーマット不正 |
| `404` | ファイルが見つからない               |

## 検索

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

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

| メソッド | エンドポイント               | 説明         | スコープ (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"`）。判定できない場合は省略                                                                                                                       |
| `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"`）。時間をおいて送り直してください                                                          |

## エラーレスポンス

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

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

| ステータス                       | 説明                                                                                                                                 |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `400 Bad Request`           | リクエストパラメータが不正                                                                                                                      |
| `401 Unauthorized`          | トークンが無効または未指定                                                                                                                      |
| `403 Forbidden`             | リソースへのアクセス権限なし                                                                                                                     |
| `404 Not Found`             | リソースが存在しない                                                                                                                         |
| `409 Conflict`              | リソースが現在処理中など、操作が競合                                                                                                                 |
| `413 Payload Too Large`     | リクエストボディがサイズ上限を超過                                                                                                                  |
| `429 Too Many Requests`     | レート制限または上限を超過。`error.type` は `rate_limit_error` で、`error.code` はエンドポイントにより異なります（例: 月間上限は `monthly_quota_exceeded`）。時間をおいて再試行してください |
| `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.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"
  }
}
```
