# Agent API Endpoints (https://mosoo.ai/docs/agent-api-endpoints/)



An Agent API Endpoint is the public API entry point for a published mosoo Agent. Your application calls it with `agentId` and a mosoo API token.

## What must exist [#what-must-exist]

A valid Agent API Endpoint has:

* A real Agent ID.
* Agent status `published`.
* A live API endpoint version.
* An owning Project owned by the API token owner.
* Matching Agent owner and Project owner.

If the Agent is not published, mosoo returns `409 agent_not_published`. If the Agent has no live API endpoint version, mosoo returns `409 service_inactive`. If the token owner does not own the Agent's Project, mosoo returns `403 forbidden`.

## `agentId` [#agentid]

Get `agentId` from the Agent API Access panel in mosoo. In v1, `agentId` is a bare ULID:

```text
01J00000000000000000000001
```

Do not add an `agent_` prefix. The same bare-ULID rule applies to `threadId`, `fileId`, and `runId`.

## What the endpoint owns [#what-the-endpoint-owns]

The Agent API Endpoint owns the runtime boundary:

| mosoo owns                                                                                                                                              | Your application owns                                                                                                               |
| ------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| Published Agent configuration, model provider setup, tool execution, sandbox/runtime behavior, Agent memory/runtime state, and public event generation. | Product UI, backend APIs, jobs, app-side users, business logic, storage, `thread.id` persistence, and client-owned correlation IDs. |

Requests cannot override model provider credentials, tools, runtime settings, or Agent configuration. Change those in mosoo, then publish the Agent again.

## First API call [#first-api-call]

Create a Thread on the Agent API Endpoint:

```http
POST /api/v1/agents/{agentId}/threads
```

Use `input` to queue the first Run immediately, or omit `input` to create an empty `IDLE` Thread.

<Cards>
  <Card title="Authentication and access" href="https://mosoo.ai/docs/auth-and-access/">
    API token checks and resource visibility.
  </Card>

  <Card title="Create a Thread" href="https://mosoo.ai/docs/api-reference/create-a-thread-for-an-agent-api-endpoint/">
    Full endpoint reference.
  </Card>

  <Card title="Threads and Runs" href="https://mosoo.ai/docs/threads-and-runs/">
    Thread and Run lifecycle state.
  </Card>
</Cards>

Application keys must belong to the Agent’s Project. See [Authentication and access](https://mosoo.ai/docs/auth-and-access/) for key creation and migration.


# Configure an Agent (https://mosoo.ai/docs/agent-configuration/)





Open an Agent to configure it alongside the live Preview pane.

<img alt="The Agent editor keeps testing and configuration in one workspace." src="__img0" />

## Identity and type [#identity-and-type]

* **Name and description** identify the Agent in lists, Threads, and delivery surfaces.
* **Assistant Agent** keeps a working environment across sessions.
* **Task Agent** starts each Run in a clean environment.

You can change type only before the first publish.

## Runtime and model [#runtime-and-model]

Choose a runtime first, then select a model available through its resolved Provider key. If the model list is empty or a runtime shows **Needs key**, configure the matching Provider in the active Project.

## System prompt [#system-prompt]

Describe the Agent's role, boundaries, answer style, and when it should ask for clarification. Prefer explicit operating rules over vague personality prose. Test both normal and failure cases before publishing.

## Skills [#skills]

Attach reusable instruction packages from the active Project. Skills are loaded for new sessions and read by the Agent when the task calls for them. A missing Skill attachment is reported rather than borrowed from another Project.

## MCP servers [#mcp-servers]

Attach authorized Remote HTTPS MCP connections from the active Project. A connection can be attached before authorization, but its tools are usable only when the connection is enabled and authorized.

## Environment [#environment]

Choose the reusable runtime template for packages, setup script, variables, and network policy. If the Agent has no explicit Environment, the Project default applies. A new session freezes the selected Environment revision. Task Agents support Full or Limited network access; Assistant Agents require Full. See [Environment network policies](https://mosoo.ai/docs/environments/#network-policies).

## Save and publish behavior [#save-and-publish-behavior]

Draft edits affect Preview. Publishing creates a new live version for future sessions. Existing sessions do not silently switch configuration.


# Authentication and access (https://mosoo.ai/docs/auth-and-access/)



Every application API request uses a Project API key:

```http
Authorization: Bearer msp_...
Content-Type: application/json
```

## Create and protect a key [#create-and-protect-a-key]

Open the target **Project settings → Project API keys** and create a key. Copy it when it is shown: the secret is displayed once and only its hash is stored. Keep it on a trusted backend, never in browser or mobile client code.

A Project can have multiple keys. Every key belongs to exactly one Project and has the same supported Agent configuration, Session, and file access; configurable key scopes are not available. Project keys cannot manage accounts, Projects, or other keys. Provider and MCP credentials are configured separately and are not application API keys.

## Agent API Endpoint access [#agent-api-endpoint-access]

The Public Thread API still requires a published Agent with a live API endpoint version. The key must be valid, not revoked, and belong to the Agent's Project. The account owning that Project must also own the Agent. Owning both Projects does not let an application key cross between them.

An unpublished Agent returns `409 agent_not_published`; a missing live endpoint version returns `409 service_inactive`. Access denial can return `403 forbidden` or `404 not_found` depending on the resource boundary.

## Caller identity and execution [#caller-identity-and-execution]

Your backend authenticates its end user and supplies a required opaque `userId` when creating a Thread. mosoo preserves the immutable `(Project, userId)` context for the Thread, Runs, files, and delegated MCP calls; it does not authenticate your end user. Your backend remains responsible for authorizing access to the stored Thread ID.

Runs use the published Agent configuration. Thread API requests cannot override provider credentials, tools, runtime settings, or Agent configuration.

## Rotation and migration [#rotation-and-migration]

Create a replacement key in the same Project, update the integration, then revoke the old key. Revocation rejects future requests from that key but does not stop admitted work or delete Threads. Another active key in the same Project, or the Project owner, can operate existing Threads.

Legacy `mst_` and `grt_pat_` tokens are rejected. They are not assigned to a default Project. Create a new key for each target Project and replace stored integration credentials. CLI users must sign in again with the current CLI; browser/CLI login provides account control-plane access and CLI login credentials use the distinct `mcli_` prefix. A Project key is not an account login replacement.

## Safe retries [#safe-retries]

Reuse the same `Idempotency-Key` for a retry of the same operation and body. Project keys share idempotency receipts and rate limits within the Project, so rotating keys neither creates duplicate work nor resets the limit. Use distinct operation IDs for separate integrations in the same Project.

The same key and request replay the original response. An in-flight request or different body using that key returns `409 idempotency_conflict`.


# mosoo API for coding agents (https://mosoo.ai/docs/coding-agents/)



# mosoo API for coding agents [#mosoo-api-for-coding-agents]

Use this document when integrating an existing, published mosoo Agent into application code through the public API.

## Integration scope [#integration-scope]

This document only covers API calls between application code and an existing mosoo Agent: sending inputs, attaching files, reading outputs, and handling public API errors.

It does not cover:

* Creating, configuring, or publishing Agents.
* Managing mosoo Projects.
* Managing Agent lifecycle, versions, readiness, runtime settings, model providers, or tools.
* Any other mosoo product surface outside the public API used to pass input to an Agent and read output from it.

This document is also not the source for secrets or live resource IDs. Do not invent API tokens, `agentId`, `threadId`, `fileId`, or `runId` values. Use values supplied by the user, environment variables, mosoo UI, or mosoo CLI when available.

This document is not a replacement for the raw OpenAPI document when generating clients or validating every schema detail. Use the raw OpenAPI for code generation and strict schema validation.

## Integration model [#integration-model]

mosoo is the Agent runtime. The published Agent runs inside a mosoo-managed sandbox, and your application backend and product code should call that sandboxed Agent through the public API.

Build the app-side integration layer around mosoo Threads, events, files, and public error handling. Your application can still own backend APIs, jobs, business logic, user flows, and data storage around the sandboxed Agent. For a mosoo Agent integration, do not implement a parallel Agent layer, sandbox, model loop, planner, tool runner, memory system, lifecycle manager, or provider integration in your application.

Primary contract:

* Human docs: `/docs`, `/docs/quickstart`, `/docs/auth-and-access`, `/docs/agent-api-endpoints`, `/docs/threads-and-runs`, `/docs/events-and-streaming`, `/docs/files`, `/docs/errors-and-limits`
* Raw OpenAPI: `/docs/openapi/mosoo-openapi.en.generated.json`
* API version: `v1`
* Base URL used in examples: `https://cloud.mosoo.ai/api/v1`

Do not infer request fields that are not listed here or in the raw OpenAPI. The public API rejects unsupported fields.

## What mosoo exposes [#what-mosoo-exposes]

mosoo exposes published Agents through Thread-based HTTP APIs. If required credentials or resource IDs are missing, get them from the environment, the user, mosoo UI, or mosoo CLI when it is available. Do not guess or synthesize mosoo IDs.

| Concept   | Meaning for callers                                                                                                            |
| --------- | ------------------------------------------------------------------------------------------------------------------------------ |
| Agent     | A configured mosoo Agent. It must be published and have API access enabled before the API can call it.                         |
| `agentId` | The published Agent ID shown in the Agent API Access panel                                                                     |
| API token | Bearer credential used by your code. It authenticates one Project and its owner. Application keys cannot cross Projects.       |
| Thread    | The API conversation container. It records messages, files, run status, and public event history.                              |
| Run       | One execution pass of the Agent on a Thread. A user message can create or resume a Run.                                        |
| Event     | A public timeline entry for Thread inputs, Agent output deltas, tool updates, file changes, status changes, and usage updates. |
| File      | A Thread attachment uploaded by the caller or an Agent artifact produced during execution.                                     |

Resource IDs in v1 are bare ULIDs, not prefixed IDs.

## Authentication and access [#authentication-and-access]

Create a `msp_` key under the Agent’s Project settings → Project API keys. Legacy `mst_` and `grt_pat_` tokens are rejected; replace them per Project. CLI users must sign in again to obtain a distinct `mcli_` account credential. Rotation within one Project preserves Thread access, idempotency receipts, and rate limits.

All API requests require an API token:

```http
Authorization: Bearer msp_...
```

JSON requests also require:

```http
Content-Type: application/json
```

A valid request must pass all of these checks:

1. The Agent exists.
2. The Agent is published and has API access enabled.
3. The API token is valid and not revoked.
4. The Agent has a live API endpoint version.
5. The Project key belongs to the Agent’s Project, whose owner also owns the Agent.
6. The requested Thread or file is visible to the API token owner.

The API token does not switch users, create a multi-user access context, or let a request override model provider, tool, or runtime settings. Configure and publish the Agent in mosoo before calling the API.

## Responsibility boundary [#responsibility-boundary]

| Your application owns                                                                                                                                                                                            | mosoo owns                                                                                                                                                          |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| App UI, app routing, app backend APIs, jobs, app-side user authentication, opaque `userId` mapping, business logic, data storage, `thread.id` persistence, and caller-owned correlation IDs such as `requestId`. | Sandboxed published Agent execution, model/provider configuration, tool execution, Agent runtime behavior, Agent memory/runtime state, and public event generation. |

## Quick start workflow [#quick-start-workflow]

Use this workflow when implementing the quickstart in application code. It is based on the human quickstart, but it starts after the Agent already exists, is published, and has API access enabled.

| Step                      | Call                                                                                                                          | Persist or read                                                                                | Stop condition                                                                   |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| 1. Load credentials       | No API call. Read `MOSOO_API_TOKEN` and `MOSOO_AGENT_ID` from the user, environment, mosoo UI, or mosoo CLI.                  | Keep the token in secret storage. Keep `agentId` as configuration.                             | Missing token or `agentId`; do not invent either value.                          |
| 2. Create a Thread        | `POST /agents/{agentId}/threads` with the authenticated application's required opaque `userId` and optional first user input. | Persist `thread.id` with the same app-user mapping.                                            | A Thread exists and the first Run has been queued when input was provided.       |
| 3. Continue the Thread    | `POST /threads/{threadId}/events` with `user_message`, `permission_decision`, or `user_interrupt` events.                     | Persist caller-owned references such as `requestId` if your app needs correlation.             | The follow-up input has been accepted by the API.                                |
| 4. Read output            | `GET /threads/{threadId}/events` for the event log, or `GET /threads/{threadId}/events/stream` for streaming.                 | Read public Agent output, run status, usage updates, tool status, and file events from events. | The app has enough public events to render the Agent response or current status. |
| 5. Attach files if needed | Upload with `POST /agents/{agentId}/files`, then mount the returned file through `resources`.                                 | Persist returned `file.id` when the app needs to reference or remove the file later.           | The file is mounted into the first or later message that depends on it.          |

Implementation rules:

* Build the app-side integration layer around the published mosoo Agent running in mosoo's sandbox; do not implement a local Agent runtime or replacement sandbox.
* Do not call model providers directly for this mosoo Agent integration.
* Do not send provider credentials, model configuration, tool configuration, or Agent configuration through this public API.
* Use `Idempotency-Key` for Thread creation and event submission.
* Treat Thread events as the integration contract and `GET /threads/{threadId}/events` as the stable source for results.
* Keep Agent creation, Project management, and Agent lifecycle operations outside this workflow.
* On failure, branch on `error.code` and follow the error handling table below.

## Minimal call sequence [#minimal-call-sequence]

Set credentials:

```bash
export MOSOO_API_TOKEN="msp_..."
export MOSOO_AGENT_ID="01J00000000000000000000001"
```

Create a Thread and queue the initial Run:

```bash
curl -X POST "https://cloud.mosoo.ai/api/v1/agents/$MOSOO_AGENT_ID/threads" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: ticket-182-create-thread" \
  -d '{
    "userId": "customer-123",
    "input": {
      "type": "user.message",
      "content": [
        {
          "type": "text",
          "text": "Triage this customer escalation and suggest next steps."
        }
      ]
    }
  }'
```

Store `thread.id`:

```bash
export MOSOO_THREAD_ID="01J00000000000000000000002"
```

Send a follow-up message:

```bash
curl -X POST "https://cloud.mosoo.ai/api/v1/threads/$MOSOO_THREAD_ID/events" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: ticket-182-follow-up-1" \
  -d '{
    "events": [
      {
        "type": "user_message",
        "requestId": "ticket-182-message-1",
        "text": "Give me the three highest-priority next actions."
      }
    ]
  }'
```

Read the public event log:

```bash
curl "https://cloud.mosoo.ai/api/v1/threads/$MOSOO_THREAD_ID/events?limit=100" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN"
```

## File upload flow [#file-upload-flow]

Use this flow when a Thread or user message needs a file attachment. Uploads are scoped to the Agent API Endpoint Project, so the file can be uploaded before the Thread exists. Public uploads use `multipart/form-data` and accept files up to 67108864 bytes.

Upload the file:

```bash
printf 'Customer asks for an implementation plan.' > brief.txt

curl -X POST "https://cloud.mosoo.ai/api/v1/agents/$MOSOO_AGENT_ID/files" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -F "file=@brief.txt;type=text/plain"
```

The response is a `PublicFileResponse`. Store `file.id`.

```bash
export MOSOO_FILE_ID="01J0000000000000000000000J"
```

Use the file in the first user message by adding top-level `resources` to the create-Thread request:

```bash
curl -X POST "https://cloud.mosoo.ai/api/v1/agents/$MOSOO_AGENT_ID/threads" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "customer-123",
    "resources": [
      {
        "type": "file",
        "file_id": "01J0000000000000000000000J"
      }
    ],
    "input": {
      "type": "user.message",
      "content": [
        {
          "type": "text",
          "text": "Summarize the attached file."
        }
      ]
    }
  }'
```

Use the file in a later user message with event-level `resources`:

```bash
curl -X POST "https://cloud.mosoo.ai/api/v1/threads/$MOSOO_THREAD_ID/events" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: ticket-182-file-question-1" \
  -d '{
    "events": [
      {
        "type": "user_message",
        "resources": [
          {
            "type": "file",
            "file_id": "01J0000000000000000000000J"
          }
        ],
        "text": "Summarize the attached file."
      }
    ]
  }'
```

After a file is mounted into a Thread, `GET /threads/{threadId}/files` lists it and `GET /files/{fileId}/content` downloads its bytes when visible to the API token caller.

## Idempotency [#idempotency]

`Idempotency-Key` is supported on:

* `POST /agents/{agentId}/threads`
* `POST /threads/{threadId}/events`

Rules:

* For Project keys, the idempotency key is scoped to the Project, method, and route; the body is checked for conflicts. Keys in the same Project share receipts and rate limits, including after rotation. Account CLI credentials use their own credential boundary.
* Reusing the same key with the same request replays the stored response.
* Reusing the same key with a different request returns `409 idempotency_conflict`.
* Reusing the key while the first request is still processing returns `409 idempotency_conflict`.
* Keys must be non-empty and 128 characters or fewer.
* Conflict responses can include `Retry-After`.

Generate stable keys from your own operation IDs, such as `ticket-182-create-thread` or `job-2026-06-23-run-1-message-3`.

## Reading results [#reading-results]

The stable read surface is the Thread event log.

Use `GET /threads/{threadId}/events` for polling and snapshots. Use `GET /threads/{threadId}/events/stream` for long-running consumer UX.

Do not expect event APIs to expose raw runtime payloads, private transcripts, or internal diagnostics. Each event entry has public fields:

| Field        | Meaning                                                                                                 |
| ------------ | ------------------------------------------------------------------------------------------------------- |
| `id`         | Event ID, bare ULID, monotonically increasing in chronological order.                                   |
| `type`       | Public event type such as `run.started`, `agent.message.delta`, `tool.use.started`, or `usage.updated`. |
| `status`     | `available`, `error`, or `unsupported`.                                                                 |
| `content`    | Public event content or a reference to the associated payload.                                          |
| `occurredAt` | RFC 3339 timestamp.                                                                                     |
| `durationMs` | Duration in milliseconds when applicable, otherwise `null`.                                             |
| `tokens`     | Token count when applicable, otherwise `null`.                                                          |

Important event types:

* `user.message`
* `agent.message.delta`
* `agent.thinking.delta`
* `tool.confirmation.required`
* `tool.use.started`
* `tool.use.completed`
* `file.changed`
* `session_files.updated`
* `run.started`
* `run.completed`
* `run.failed`
* `session.status`
* `usage.updated`

## Status values [#status-values]

Thread status:

| Status         | Meaning                                       |
| -------------- | --------------------------------------------- |
| `IDLE`         | No active Run. A user message can queue work. |
| `RUNNING`      | A Run is executing.                           |
| `RESCHEDULING` | The Thread is between runs.                   |
| `TERMINATED`   | The Thread has ended.                         |

Run status:

| Status          | Meaning                                                         |
| --------------- | --------------------------------------------------------------- |
| `queued`        | Run exists but has not started.                                 |
| `booting`       | Runtime is preparing.                                           |
| `running`       | Run is executing.                                               |
| `waiting_input` | Run is blocked on caller/user input, often permission decision. |
| `completed`     | Terminal success.                                               |
| `failed`        | Terminal failure.                                               |
| `cancelled`     | Terminal cancellation.                                          |
| `expired`       | Terminal timeout or expiry.                                     |

## Error handling [#error-handling]

All non-2xx public API JSON errors use this envelope:

```json
{
  "error": {
    "code": "invalid_request",
    "message": "Request body must be an object."
  }
}
```

Branch on `error.code`, not `error.message`. The message is for developers and should not be displayed directly to end users.

| HTTP | `error.code`           | Meaning                                                                                            | Caller action                                                                                |
| ---- | ---------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| 400  | `invalid_request`      | Request shape, field value, body size, limit, or unsupported field is invalid.                     | Fix the request. Do not retry unchanged.                                                     |
| 400  | `invalid_json`         | Body is not valid JSON.                                                                            | Fix serialization or `Content-Type`. Do not retry unchanged.                                 |
| 401  | `unauthenticated`      | Missing, invalid, or revoked API token.                                                            | Re-read `Authorization`; rotate or recreate the API token.                                   |
| 403  | `forbidden`            | API token is valid but the operation is not allowed for this Agent, Thread, or file.               | Check that the request uses the expected token and a resource from the same mosoo workspace. |
| 404  | `not_found`            | Agent, Thread, or file is not visible in the current mosoo workspace or does not exist.            | Check the ID and use resource IDs returned by the API.                                       |
| 409  | `agent_not_published`  | Agent exists but is not published as an active API service.                                        | Ask the user to publish the Agent and enable API access.                                     |
| 409  | `service_inactive`     | Published API service has no live published version.                                               | Ask the user to republish or repair the Agent in mosoo.                                      |
| 409  | `readiness_blocked`    | Agent is not ready to run.                                                                         | Do not blindly retry; ask the user to fix Agent readiness or configuration in mosoo.         |
| 409  | `idempotency_conflict` | Same `Idempotency-Key` is processing or was used for a different request.                          | If still processing, wait for `Retry-After`; if body differs, use a new key.                 |
| 429  | `rate_limited`         | Project exceeded shared public API rate limits (account CLI credentials have a separate boundary). | Back off and retry after `Retry-After`.                                                      |
| 500  | `internal_error`       | mosoo failed internally.                                                                           | Retry briefly with backoff; persist failure details if it repeats.                           |

Retry policy:

* Safe to retry with the same `Idempotency-Key`: network timeouts, 5xx from create-thread or send-events, and `idempotency_conflict` caused by in-flight processing.
* Safe to retry after delay: `rate_limited`, using `Retry-After`.
* Do not retry unchanged: `invalid_request`, `invalid_json`, `unauthenticated`, `forbidden`, `not_found`, `agent_not_published`, `service_inactive`, `readiness_blocked`.

{/* BEGIN GENERATED OPENAPI REFERENCE */}

## API contract [#api-contract]

This section is generated from `/docs/openapi/mosoo-openapi.en.generated.json`. Do not edit it manually; run `npm run openapi:sync`.

All endpoints below are relative to `/api/v1`.

| Method   | Path                                 | Purpose                                                             |
| -------- | ------------------------------------ | ------------------------------------------------------------------- |
| `POST`   | `/agents/{agentId}/threads`          | Create a Thread for an Agent API Endpoint                           |
| `GET`    | `/agents/{agentId}/threads`          | List Threads for an Agent API Endpoint                              |
| `GET`    | `/threads/{threadId}`                | Retrieve Thread summary                                             |
| `POST`   | `/threads/{threadId}/events`         | Send user messages, permission decisions, or interrupts to a Thread |
| `GET`    | `/threads/{threadId}/events`         | List Thread events                                                  |
| `GET`    | `/threads/{threadId}/events/stream`  | Stream Thread events                                                |
| `POST`   | `/agents/{agentId}/files`            | Upload an Agent file                                                |
| `GET`    | `/files/{fileId}`                    | Retrieve file metadata                                              |
| `GET`    | `/threads/{threadId}/files`          | List Thread files                                                   |
| `GET`    | `/files/{fileId}/content`            | Download Thread file content                                        |
| `DELETE` | `/files/{fileId}`                    | Delete a file                                                       |
| `DELETE` | `/threads/{threadId}/files/{fileId}` | Remove a Thread file                                                |
| `POST`   | `/threads/{threadId}/archive`        | Archive a Thread                                                    |
| `POST`   | `/threads/{threadId}/unarchive`      | Unarchive a Thread                                                  |
| `DELETE` | `/threads/{threadId}`                | Delete a Thread                                                     |

Common error response envelope:

```json
{
  "error": {
    "code": "invalid_request",
    "message": "Request body must be an object."
  }
}
```

### `POST /agents/{agentId}/threads` [#post-agentsagentidthreads]

Purpose: Creates a Thread and the backing AgentSession for the required application `userId`. If input is present, mosoo also queues the initial Run. If input is omitted, the Thread is immediately visible with IDLE status and no run.

Path params:

* `agentId` required, `string(ulid)`. Agent API Endpoint ID from the Agent's API Access panel. v1 IDs are bare ULIDs.

Headers:

* `Idempotency-Key` optional, `string`. Optional key for retry-safe create-thread and send-events calls. Reusing the same key with the same request returns the original response. Reusing the key while the original request is still processing returns 409.

Request body:

* `application/json`: `CreateThreadRequest`

Example `emptyThread`:

```json
{
  "userId": "customer-123"
}
```

Example `accessTokenWithFile`:

```json
{
  "input": {
    "content": [
      {
        "text": "Summarize the attached launch plan and list follow-ups.",
        "type": "text"
      }
    ],
    "type": "user.message"
  },
  "resources": [
    {
      "file_id": "01J0000000000000000000000J",
      "type": "file"
    }
  ],
  "userId": "customer-123"
}
```

Example `accessTokenBasic`:

```json
{
  "input": {
    "content": [
      {
        "text": "Say hello from the API.",
        "type": "text"
      }
    ],
    "type": "user.message"
  },
  "userId": "customer-123"
}
```

Example `cattleAgentSameShape`:

```json
{
  "input": {
    "content": [
      {
        "text": "Run this one-off Public Thread API request.",
        "type": "text"
      }
    ],
    "type": "user.message"
  },
  "userId": "automation"
}
```

Success responses:

* `201`: Created Thread. (`application/json` -> `CreateThreadResponse`)

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `GET /agents/{agentId}/threads` [#get-agentsagentidthreads]

Purpose: Returns Threads created by the authenticated API token.

Path params:

* `agentId` required, `string(ulid)`. Agent API Endpoint ID from the Agent's API Access panel. v1 IDs are bare ULIDs.

Query params:

* `archived` optional, `boolean`. Filter by archived state: true returns only archived Threads, false only active ones. Omit to return all Threads.

Success responses:

* `200`: Thread list. (`application/json` -> `object`)

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `GET /threads/{threadId}` [#get-threadsthreadid]

Purpose: Returns the current Thread summary, its most recent Run, and links.

Path params:

* `threadId` required, `string(ulid)`. Thread ID returned by create thread. v1 IDs are bare ULIDs.

Success responses:

* `200`: Thread summary. (`application/json` -> `RetrieveThreadResponse`)

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `POST /threads/{threadId}/events` [#post-threadsthreadidevents]

Purpose: Applies a batch of events to the Thread: send user messages, answer pending permission requests, or interrupt the current Run. A user message queues a new Run when the Thread is idle.

Path params:

* `threadId` required, `string(ulid)`. Thread ID returned by create thread. v1 IDs are bare ULIDs.

Headers:

* `Idempotency-Key` optional, `string`. Optional key for retry-safe create-thread and send-events calls. Reusing the same key with the same request returns the original response. Reusing the key while the original request is still processing returns 409.

Request body:

* `application/json`: `SendEventsRequest`

Example:

```json
{
  "events": [
    {
      "text": "Say hello from the API.",
      "type": "user_message"
    }
  ]
}
```

Success responses:

* `200`: Accepted event batch. (`application/json` -> `SendEventsResponse`)

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `GET /threads/{threadId}/events` [#get-threadsthreadidevents]

Purpose: Returns the latest public event log entries for this Thread in chronological order. If older public entries are omitted because the limit was reached, `truncated` is true. Event IDs are stable, so callers can retry or poll without treating the same ID as a new event. This is the stable snapshot read surface for CLI and API consumers; it does not expose raw runtime payloads, transcript, or diagnostics.

Path params:

* `threadId` required, `string(ulid)`. Thread ID returned by create thread. v1 IDs are bare ULIDs.

Query params:

* `limit` optional, `integer`. Maximum number of latest Thread events to return.

Success responses:

* `200`: Thread event list. (`application/json` -> `ThreadEventListResponse`)

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `GET /threads/{threadId}/events/stream` [#get-threadsthreadideventsstream]

Purpose: Streams public Thread event log entries as Server-Sent Events. Each `thread.event` data payload uses the same ThreadEventLogEntry shape as GET /threads/\{threadId}/events. Events are emitted by stable event ID and the stream suppresses duplicate IDs observed during polling. The stream is for long-running consumer UX and does not expose raw runtime payloads, internal diagnostics, or private transcripts.

Path params:

* `threadId` required, `string(ulid)`. Thread ID returned by create thread. v1 IDs are bare ULIDs.

Query params:

* `limit` optional, `integer`. Maximum number of latest Thread events to return.

Success responses:

* `200`: Thread event stream. (`text/event-stream` -> `string`)

Example `200`:

```json
": connected\n\nevent: thread.event\nid: 01J00000000000000000000010\ndata: {\"id\":\"01J00000000000000000000010\",\"runId\":\"01J0000000000000000000000A\",\"type\":\"run.started\",\"status\":\"available\",\"content\":\"01J0000000000000000000000A\",\"occurredAt\":\"2026-05-19T00:00:01.000Z\",\"durationMs\":null,\"tokens\":null}\n\n"
```

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `POST /agents/{agentId}/files` [#post-agentsagentidfiles]

Purpose: Uploads a file into the Agent API Endpoint's Project draft scope before a Thread exists. Use the returned file ID in create-thread or send-events resources.

Path params:

* `agentId` required, `string(ulid)`. Agent API Endpoint ID from the Agent's API Access panel. v1 IDs are bare ULIDs.

Request body:

* `multipart/form-data`: `object`

Success responses:

* `201`: Uploaded file. (`application/json` -> `PublicFileResponse`)

Example `201`:

```json
{
  "file": {
    "createdAt": "2026-05-19T00:02:00.000Z",
    "id": "01J0000000000000000000000J",
    "mimeType": "text/plain",
    "name": "brief.txt",
    "size": 19
  }
}
```

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `GET /files/{fileId}` [#get-filesfileid]

Purpose: Returns public file metadata for a pre-Thread uploaded file or a file attached to a public Thread visible to the API token.

Path params:

* `fileId` required, `string(ulid)`. File ID returned by add or list Thread files. v1 IDs are bare ULIDs.

Success responses:

* `200`: File metadata. (`application/json` -> `PublicFileResponse`)

Example `200`:

```json
{
  "file": {
    "createdAt": "2026-05-19T00:02:00.000Z",
    "id": "01J0000000000000000000000J",
    "mimeType": "text/plain",
    "name": "brief.txt",
    "size": 19
  }
}
```

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `GET /threads/{threadId}/files` [#get-threadsthreadidfiles]

Purpose: Lists files attached to the Thread, including caller attachments and Agent artifacts.

Path params:

* `threadId` required, `string(ulid)`. Thread ID returned by create thread. v1 IDs are bare ULIDs.

Success responses:

* `200`: Thread file list. (`application/json` -> `ThreadFileListResponse`)

Example `200`:

```json
{
  "files": [
    {
      "committed": true,
      "createdAt": "2026-05-19T00:02:00.000Z",
      "id": "01J0000000000000000000000J",
      "kind": "attachment",
      "mimeType": "text/plain",
      "name": "brief.txt",
      "size": 19
    }
  ]
}
```

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `GET /files/{fileId}/content` [#get-filesfileidcontent]

Purpose: Downloads bytes for a ready Thread attachment or Agent artifact. The file must belong to a public Thread visible to the API token.

Path params:

* `fileId` required, `string(ulid)`. File ID returned by add or list Thread files. v1 IDs are bare ULIDs.

Query params:

* `disposition` optional, `"attachment" | "inline"`. Controls the Content-Disposition response header. Use attachment for downloads or inline for previewable content.

Success responses:

* `200`: Thread file content. (`application/octet-stream` -> `string(binary)`)

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `DELETE /files/{fileId}` [#delete-filesfileid]

Purpose: Deletes a pre-Thread uploaded file or a file attached to a public Thread visible to the API token.

Path params:

* `fileId` required, `string(ulid)`. File ID returned by add or list Thread files. v1 IDs are bare ULIDs.

Success responses:

* `200`: Deleted. (`application/json` -> `object`)

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `DELETE /threads/{threadId}/files/{fileId}` [#delete-threadsthreadidfilesfileid]

Purpose: Detaches a file from the Thread.

Path params:

* `threadId` required, `string(ulid)`. Thread ID returned by create thread. v1 IDs are bare ULIDs.
* `fileId` required, `string(ulid)`. File ID returned by add or list Thread files. v1 IDs are bare ULIDs.

Success responses:

* `200`: Removed. (`application/json` -> `object`)

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `POST /threads/{threadId}/archive` [#post-threadsthreadidarchive]

Purpose: Archives the Thread so it is hidden from default Thread lists.

Path params:

* `threadId` required, `string(ulid)`. Thread ID returned by create thread. v1 IDs are bare ULIDs.

Success responses:

* `200`: Archived. (`application/json` -> `object`)

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `POST /threads/{threadId}/unarchive` [#post-threadsthreadidunarchive]

Purpose: Restores a previously archived Thread to active Thread lists.

Path params:

* `threadId` required, `string(ulid)`. Thread ID returned by create thread. v1 IDs are bare ULIDs.

Success responses:

* `200`: Unarchived. (`application/json` -> `object`)

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

### `DELETE /threads/{threadId}` [#delete-threadsthreadid]

Purpose: Permanently deletes the Thread and its backing AgentSession.

Path params:

* `threadId` required, `string(ulid)`. Thread ID returned by create thread. v1 IDs are bare ULIDs.

Success responses:

* `200`: Deleted. (`application/json` -> `object`)

Error responses:

* `400` `InvalidRequest`: The request shape or query value is invalid.
* `401` `Unauthenticated`: A valid API token is required.
* `403` `Forbidden`: This operation is not allowed for this Agent.
* `404` `NotFound`: The resource was not found in the current mosoo workspace.
* `409` `Conflict`: The Agent/session state rejects this action, or an Idempotency-Key is already processing or was reused for a different request.
* `429` `RateLimited`: The API token exceeded the public API request budget for the current window.
* `500` `InternalError`: The request failed unexpectedly.

## Schema quick reference [#schema-quick-reference]

### `ThreadEventInput` [#threadeventinput]

A single event posted to a Thread. Exactly one variant applies: send a user message, answer a pending permission request, or interrupt a running Run.

Variants:

1. `object`: Send a new user message into the Thread, optionally with file attachments.
   * `resources` optional, `FileResource[]`. Files to attach to this message. Each file must be a ready draft file uploaded through the Agent file endpoint by the same API token.
   * `requestId` optional, `string | null`. Optional caller-supplied request ID echoed back on the matching event result so you can pair responses with the message you sent.
   * `text` required, `string`. The user message text. Must not be empty.
   * `type` required, `"user_message"`. Discriminator selecting the send-user-message variant.

2. `object`: Answer a permission request the Agent raised while waiting for input (for example a tool confirmation).
   * `decision` required, `"allow_once" | "reject_once"`. Whether to allow or reject the requested action for this single occurrence. `allow_once` permits it now; `reject_once` denies it now.
   * `requestId` required, `string`. ID of the permission request being answered, taken from the corresponding `tool.confirmation.required` event.
   * `type` required, `"permission_decision"`. Discriminator selecting the permission-decision variant.

3. `object`: Interrupt a Run that is currently executing on the Thread.
   * `runId` optional, `string(ulid) | null`. Run ID (bare ULID) to interrupt. Omit or send null to interrupt the Thread's current Run.
   * `type` required, `"user_interrupt"`. Discriminator selecting the interrupt variant.

### `SendEventsRequest` [#sendeventsrequest]

Request body for posting a batch of events to a Thread.

Fields:

* `events` required, `ThreadEventInput[]`. Ordered list of events to apply to the Thread. At least one is required.

### `FileResource` [#fileresource]

A file resource to mount into a Thread or user message.

Fields:

* `file_id` required, `string(ulid)`. ID of a ready draft file uploaded through the Agent file endpoint.
* `type` required, `"file"`. Resource discriminator. Only `file` is supported today.

### `PublicFile` [#publicfile]

Public file metadata.

Fields:

* `createdAt` required, `string(date-time)`. Timestamp (RFC 3339) at which the file record was created.
* `id` required, `string(ulid)`. File ID (bare ULID).
* `mimeType` required, `string | null`. Detected MIME type of the file, or null when unknown.
* `name` required, `string`. Original file name.
* `size` required, `integer`. File size in bytes.

### `PublicFileResponse` [#publicfileresponse]

A single public file.

Fields:

* `file` required, `PublicFile`. Public file metadata.

### `ErrorResponse` [#errorresponse]

Standard error envelope returned for any non-2xx public API response.

Fields:

* `error` required, `object`. Details about why the request failed.
  * `code` required, `"agent_not_published" | "forbidden" | "idempotency_conflict" | "internal_error" | "invalid_json" | "invalid_request" | "not_found" | "rate_limited" | "readiness_blocked" | "service_inactive" | "unauthenticated"`. Stable, machine-readable error code you can branch on.
  * `message` required, `string`. Human-readable explanation of the error. Not intended for end users.

### `SendEventsResponse` [#sendeventsresponse]

Result of accepting a batch of events posted to a Thread.

Fields:

* `acceptedAt` required, `string(date-time)`. Timestamp (RFC 3339) at which the event batch was accepted for processing.
* `events` required, `ThreadEventResult[]`. Per-event outcomes, in the same order as the submitted events.
* `thread` required, `ThreadSummary`. The Thread state after applying the batch.
* `warnings` required, `UserWarning[]`. Non-fatal warnings raised while accepting the batch (for example a partially honored request). Empty when there are none.

### `ThreadEventLogEntry` [#threadeventlogentry]

A single public event log entry for a Thread. This is the stable read surface and never exposes raw runtime payloads, transcripts, or diagnostics.

Fields:

* `content` required, `string`. Public content of the event — typically a reference to the associated payload (such as a message ID) rather than the raw runtime data.
* `durationMs` required, `integer | null`. Wall-clock duration of the event in milliseconds, when applicable (for example a completed Run). Null when not measured.
* `id` required, `string(ulid)`. Unique event ID (bare ULID), monotonically increasing in chronological order.
* `occurredAt` required, `string(date-time)`. Timestamp (RFC 3339) at which the event occurred.
* `runId` required, `string(ulid) | null`. Run ID (bare ULID) associated with this event, or null when the event is not run-scoped. Use this to reconstruct output for one current Run without mixing earlier Thread output.
* `status` required, `"available" | "error" | "unsupported"`. Delivery status of the event: `available` when the event is fully populated, `error` when it failed, `unsupported` when this event type cannot be rendered on the public surface.
* `toolCallId` optional, `string`. Opaque, durable ID shared by lifecycle events for one logical tool invocation. Use this value, not the event `id`, to correlate start, confirmation, and terminal events.
* `toolInput` optional, `object`. Structured tool arguments when this event carries a complete canonical input object.
* `toolName` optional, `string`. Harness-neutral tool name when supplied by the runtime.
* `tokens` required, `integer | null`. Token count associated with the event when applicable (for example model usage). Null when not measured.
* `type` required, `"agent.message.delta" | "agent.thinking.delta" | "file.changed" | "run.completed" | "run.failed" | "run.started" | "session.status" | "session_files.updated" | "tool.confirmation.required" | "tool.use.completed" | "tool.use.started" | "usage.updated" | "user.message"`. Event type, such as `run.started`, `run.completed`, `agent.message.delta`, or `tool.use.started`.

### `ThreadEventListResponse` [#threadeventlistresponse]

A page of the latest Thread event log entries in chronological order.

Fields:

* `events` required, `ThreadEventLogEntry[]`. The returned event log entries, oldest first within the requested window.
* `truncated` required, `boolean`. True when older events exist beyond the returned window because the requested limit was reached.

### `ThreadEventResult` [#threadeventresult]

Outcome of a single submitted event.

Fields:

* `requestId` required, `string | null`. The `requestId` echoed from the submitted user message, or null when none was provided or the event type does not carry one.
* `run` required, `RunSummary | null`. The Run created or affected by this event, or null when the event did not start or change a Run.
* `type` required, `"permission_decision" | "user_interrupt" | "user_message"`. The kind of event this result corresponds to.

### `CreateThreadRequest` [#createthreadrequest]

Request body for creating a Thread. `userId` is required. Omit `input` to create an empty IDLE Thread, or include it to queue the initial Run.

Fields:

* `userId` required, `string`. Opaque application-user identifier supplied by the trusted backend. It is immutable for the lifetime of the Thread and is delegated to MCP servers during Runs.
* `resources` optional, `FileResource[]`. Files uploaded through the Agent file endpoint and mounted into the first Run.
* `input` optional, `object`. Initial user message that seeds the Thread and queues the first Run. Omit to create an empty Thread with no run.
  * `content` required, `object[]`. Ordered content parts that make up the initial message.
  * `type` required, `"user.message"`. Discriminator for the initial input. Always `user.message`.

### `CreateThreadResponse` [#createthreadresponse]

Result of creating a Thread.

Fields:

* `links` required, `ThreadLinks`. Convenience links for the created Thread.
* `run` required, `RunSummary | null`. The initial Run queued when `input` was provided, or null when an empty Thread was created.
* `thread` required, `ThreadSummary`. The created Thread.

### `RetrieveThreadResponse` [#retrievethreadresponse]

Current state of a Thread.

Fields:

* `links` required, `ThreadLinks`. Convenience links for the Thread.
* `run` required, `RunSummary | null`. The Thread's most recent Run, or null when no Run has been created yet.
* `thread` required, `ThreadSummary`. The Thread summary.

### `ThreadFile` [#threadfile]

A file associated with a Thread.

Fields:

* `committed` required, `boolean`. True once the file is durably attached to the Thread; false while it is still a draft handle.
* `createdAt` required, `string(date-time)`. Timestamp (RFC 3339) at which the file was created.
* `id` required, `string(ulid)`. Unique file ID (bare ULID).
* `kind` required, `"attachment" | "artifact"`. Files added through the public API are attachments; artifacts are files produced by the Agent.
* `mimeType` required, `string | null`. Detected MIME type of the file, or null when unknown.
* `name` required, `string`. Original file name.
* `size` required, `integer`. File size in bytes.

### `ThreadFileListResponse` [#threadfilelistresponse]

List of files attached to a Thread.

Fields:

* `files` required, `ThreadFile[]`. The Thread's files.

### `ThreadFileResponse` [#threadfileresponse]

A single Thread file.

Fields:

* `file` required, `ThreadFile`. The Thread file metadata, including its identifier, name, MIME type, and origin.

### `ThreadLinks` [#threadlinks]

Convenience links for a Thread.

Fields:

* `thread` required, `string`. Absolute API URL of the Thread resource.

### `ThreadSummary` [#threadsummary]

Summary of a Thread on a Agent API Endpoint.

Fields:

* `agent_id` required, `string(ulid)`. ID (bare ULID) of the Agent API Endpoint this Thread belongs to.
* `created_at` required, `string(date-time)`. Timestamp (RFC 3339) at which the Thread was created.
* `id` required, `string(ulid)`. Unique Thread ID (bare ULID).
* `kind` required, `"pet" | "cattle"`. Agent kind backing this Thread (for example a persistent or one-off Agent API Endpoint).
* `last_run_id` required, `string(ulid) | null`. ID (bare ULID) of the most recent Run, or null when no Run exists yet.
* `source` required, `"api"`. Origin of the Thread. Always `api` for Threads created via this API.
* `status` required, `"IDLE" | "RUNNING" | "RESCHEDULING" | "TERMINATED"`. Lifecycle status of the Thread: `IDLE` (no active run), `RUNNING` (a Run is executing), `RESCHEDULING` (between runs), or `TERMINATED` (ended).
* `title` required, `string | null`. Human-readable Thread title, or null when one has not been derived yet.
* `updated_at` required, `string(date-time)`. Timestamp (RFC 3339) of the most recent change to the Thread.
* `userId` required, `string`. Immutable opaque application-user identifier supplied when the Thread was created.

### `RunSummary` [#runsummary]

Summary of a single Agent Run on a Thread.

Fields:

* `completedAt` required, `string | null(date-time)`. Timestamp (RFC 3339) at which the Run reached a terminal state, or null while it has not finished.
* `createdAt` required, `string(date-time)`. Timestamp (RFC 3339) at which the Run was created.
* `error` required, `RunError | null`. Structured failure summary when status is `failed`; null for successful, active, cancelled, or expired Runs.
* `finalOutput` required, `RunFinalOutput | null`. Public-safe canonical final assistant answer for a completed Run. It is derived from the persisted final assistant message, not reconstructed from public `agent.message.delta` events. Null until that final message is persisted or when the Run has no final assistant answer.
* `id` required, `string(ulid)`. Unique Run ID (bare ULID).
* `startedAt` required, `string | null(date-time)`. Timestamp (RFC 3339) at which the Run began executing, or null while it is still queued.
* `status` required, `"queued" | "booting" | "running" | "waiting_input" | "completed" | "failed" | "cancelled" | "expired"`. Current Run status. `queued` and `booting` precede execution; `running` and `waiting_input` are active; `completed`, `failed`, `cancelled`, `expired` are terminal.
* `trigger` required, `"user_prompt" | "retry" | "resume" | "system"`. What started the Run: `user_prompt` (a user message), `retry`, `resume`, or `system`.
* `updatedAt` required, `string(date-time)`. Timestamp (RFC 3339) of the most recent change to the Run.

### `RunError` [#runerror]

Public-safe Run failure summary exposed on failed public Runs.

Fields:

* `code` required, `string`. Stable, machine-readable failure code.
* `message` required, `string`. Human-readable failure summary.
* `retryable` required, `boolean`. Whether retrying the Run may succeed without changing input.

### `RunFinalOutput` [#runfinaloutput]

Final assistant answer for a completed public Thread Run.

Fields:

* `text` required, `string`. Public-safe text derived from the Run's persisted final assistant message. Provider-private control markup is omitted and reported through warnings.
* `warnings` optional, `RunFinalOutputWarning[]`. Non-fatal warnings raised while making provider output safe for public consumption.

### `RunFinalOutputWarning` [#runfinaloutputwarning]

A non-fatal warning attached to canonical final output.

Fields:

* `code` required, `"unresolved_provider_citation"`. Stable code identifying provider citation markup that could not be resolved.
* `count` required, `integer`. Number of private citation envelopes removed from the public text.

### `UserWarning` [#userwarning]

A non-fatal warning surfaced to the caller.

Fields:

* `code` required, `string`. Stable, machine-readable warning code.
* `message` required, `string`. Human-readable explanation of the warning.

{/* END GENERATED OPENAPI REFERENCE */}

## Implementation guardrails for coding agents [#implementation-guardrails-for-coding-agents]

* Always send `Authorization: Bearer $MOSOO_API_TOKEN`.
* Always treat `agentId`, `threadId`, `fileId`, and `runId` as bare ULIDs.
* Use `Idempotency-Key` for create-thread and send-events retries.
* Use event log APIs as the source for public results.
* Do not assume raw model output, private runtime payloads, or internal diagnostics are exposed.
* Do not send provider credentials, model configuration, or Agent configuration through this public API.
* Do not retry invalid requests unchanged.
* Do not treat `403` as an authentication problem; `403` means the token was understood but the operation is not allowed for that resource.
* Do not treat a published Agent as ready unless create-thread succeeds or the user confirms Agent readiness in mosoo.
* Always supply the authenticated application's opaque `userId` when creating a Thread; use `requestId` for optional per-message correlation.


# Projects, Agents, and runtimes (https://mosoo.ai/docs/concepts/)



mosoo is an open-source agent runtime for coding agents. It runs Claude Agent SDK, OpenAI Runtime, and OpenCode agents behind one product model, then exposes durable Threads, Runs, events, files, and API access so applications do not rebuild their own sandbox, lifecycle, or provider layer.

## Projects are isolation boundaries [#projects-are-isolation-boundaries]

A Project keeps its Agents, files, configuration resources, and usage separate. Switching Projects changes the resources visible in the console. The current Alpha is single-owner: organization team roles, invitations, and ownership transfer are not available.

## Agent types control continuity [#agent-types-control-continuity]

| Type                | Runtime state                                                                                                                                                     | Best for                                                                       |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| **Assistant Agent** | Keeps a stable working environment across sessions. Rebuilds preserve selected workspace and memory, but may lose local sign-ins or caches.                       | Ongoing assistants, copilots, and repeated work that benefits from continuity. |
| **Task Agent**      | Isolates state by Thread. Successful Runs checkpoint the working directory and provider resume state; later Runs in the same Thread restore that committed state. | Reviews, triage, webhooks, and isolated batch tasks.                           |

A new Thread starts with isolated state. A successful Task Run commits its complete Thread working directory and provider resume state before a follow-up can start. Cold continuation restores that checkpoint; a failed commit blocks follow-up rather than silently starting empty. Checkpoints remain restorable for at least 20 days, survive archive, and are removed on permanent Thread deletion. Live processes, sockets, temporary credentials, and attachment mounts are not checkpointed. Threads predating the checkpoint rollout can restore recorded artifacts until their first successful checkpointed turn.

New Agents start as Assistant Agents. You can switch type while the Agent is a draft; the first publish locks it. Fork the Agent to change type later without changing the original.

## Runtimes are Agent drivers [#runtimes-are-agent-drivers]

The runtime determines how the Agent executes and which Provider credential it resolves. Runtime choice is separate from Agent type:

* **Claude Agent SDK** uses Anthropic.
* **OpenAI Runtime** uses OpenAI or a compatible Responses API endpoint.
* **OpenCode** supports its own runtime and compatible Provider configurations.

## Threads and Runs [#threads-and-runs]

A Thread is the durable interaction record for one Agent. Each new task or resumed reply may start a Run. A Thread keeps its history and can be reopened asynchronously. A Run is one execution with status, events, files, logs, and usage.

## Published versions [#published-versions]

Publishing snapshots Agent configuration. New sessions use the current live version; an existing session stays on the version it began with. Version history is read-only today: complete historical restore and side-by-side comparison are not available.


# Deploy mosoo on Cloudflare (https://mosoo.ai/docs/deploy-mosoo/)



mosoo runs as two Cloudflare Workers: an API Worker backed by D1, R2, Queues, Durable Objects, and Containers, plus a Web Worker that serves the console and binds to the API service.

This guide covers the two deployment paths used by the reference deployment:

* **Cloud deployment** — GitHub Actions builds and publishes to Cloudflare.
* **Local toolchain deployment** — an operator publishes the same configuration with Wrangler from a local checkout.

Both paths use `apps/api/wrangler.toml`, `apps/web/wrangler.toml`, and the repository deployment scripts. Prepare the Cloudflare resources once, then choose either release path.

## Prerequisites [#prerequisites]

* A Cloudflare account with Workers, D1, R2, Queues, Durable Objects, and Containers available.
* A domain in Cloudflare DNS, such as `console.example.com`.
* Git, Docker, [Bun](https://bun.sh/), [just](https://just.systems/), and the repository submodules.
* A Cloudflare API token with the account and zone permissions required to deploy the resources above. Keep tokens and secret values outside Git. Use the least privilege that covers the operations below.

| Scope                             | Required operations                                                                               |
| --------------------------------- | ------------------------------------------------------------------------------------------------- |
| Account                           | Workers scripts, versions, deployments, custom domains, and Containers; D1 migrations; R2; Queues |
| Zone that owns the console domain | Workers Routes changes for the `<console-domain>/api/*` API route                                 |
| R2 S3 credentials                 | Read and write the sandbox-state bucket used for Agent runtime backups                            |

Cloudflare's token labels can change; verify that the token permits these exact API operations rather than granting account-wide administrator access.

Clone your fork and install the pinned dependencies:

```bash
git clone --recurse-submodules https://github.com/<owner>/mosoo.git
cd mosoo
bun install --frozen-lockfile
```

## 1. Prepare Cloudflare resources [#1-prepare-cloudflare-resources]

Authenticate Wrangler when provisioning from your workstation:

```bash
cd apps/api
../../node_modules/.bin/vp exec wrangler login
../../node_modules/.bin/vp exec wrangler whoami
```

Create one production D1 database and copy the returned database ID:

```bash
../../node_modules/.bin/vp exec wrangler d1 create mosoo-prod
```

Create the R2 buckets referenced by the production configuration:

```bash
../../node_modules/.bin/vp exec wrangler r2 bucket create mosoo-file
../../node_modules/.bin/vp exec wrangler r2 bucket create mosoo-sandbox-state
```

Create the queues used by API commands, artifact builds, and final channel delivery:

```bash
for queue in \
  api-command \
  api-command-dlq \
  environment-artifact-build \
  channel-final-delivery \
  channel-final-delivery-dlq
do
  ../../node_modules/.bin/vp exec wrangler queues create "$queue"
done
```

If you change any resource name, update every matching producer, consumer, and binding in `apps/api/wrangler.toml`.

## 2. Configure domains and bindings [#2-configure-domains-and-bindings]

Edit the `[env.prod]` sections in both Wrangler files. At minimum:

1. In `apps/api/wrangler.toml`:
   * set `WEB_ORIGIN` to the public HTTPS console URL;
   * set the API route to `<console-domain>/api/*` and its `zone_name`;
   * set the D1 `database_id` returned by `wrangler d1 create`;
   * update D1, R2, and Queue names if you did not use the defaults;
   * update `AUTH_EMAIL_FROM` to a sender authorized by your Cloudflare zone.
2. In `apps/web/wrangler.toml`:
   * set the production custom domain to the same console domain;
   * keep the `API` service binding pointed at the production API Worker name.

For example, the routing shape is:

```text
https://console.example.com/*      -> Web Worker
https://console.example.com/api/*  -> API Worker
```

Choose names that are unused in each resource's Cloudflare namespace. Workers, D1 databases, Queues, R2 buckets, and hostnames have different naming and uniqueness rules. Do not copy database IDs, account IDs, zone IDs, or hostnames from another deployment.

## 3. Store production secrets [#3-store-production-secrets]

The current production configuration requires these API Worker secrets:

* `BETTER_AUTH_SECRET`
* `RUNTIME_ACTION_TOKEN_SECRET`
* `VAULT_ROOT_SECRET`
* `R2_ACCESS_KEY_ID`
* `R2_SECRET_ACCESS_KEY`
* `CLOUDFLARE_ACCOUNT_ID`
* `GOOGLE_OAUTH_CLIENT_ID`
* `GOOGLE_OAUTH_CLIENT_SECRET`

Generate independent random values for the first three secrets. Copy the account ID and create the R2 S3 credentials in the Cloudflare dashboard. Configure the Google OAuth client with the public mosoo origin and the exact callback URL `https://console.example.com/api/auth/callback/google`, replacing the example domain with `WEB_ORIGIN`.

Store each value with Wrangler; do not add it to `wrangler.toml` or a committed `.env` file:

```bash
cd apps/api
../../node_modules/.bin/vp exec wrangler secret put BETTER_AUTH_SECRET --env prod
# Repeat for every required secret listed above.
```

If you use email login, configure Cloudflare Email Routing and authorize the sender used by the `AUTH_EMAIL` binding. PostHog analytics is optional; omit its project key to keep analytics disabled.

## 4A. Cloud deployment with GitHub Actions [#4a-cloud-deployment-with-github-actions]

The reference cloud path is `.github/workflows/deploy-try.yml`. It verifies the repository, exercises the D1 migration chain locally, reads the remote D1 migration ledger and Queue list, dry-runs both Workers, deploys the API and Web Workers, and then probes the public endpoints. It does not separately preflight every R2, Container, or binding resource.

For a fork:

1. Update the workflow's repository guard, environment URL, public health-check URLs, and any deployment-specific build variables.
2. Create the GitHub Environment used by the workflow and restrict it to the release branch.
3. Add `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` as GitHub Environment secrets. These authenticate CI; the runtime secrets from the previous section remain in Cloudflare.
4. Protect the release branch from force-push and deletion.
5. Advance the release branch only to a reviewed commit from `main`.

The reference workflow deploys pushes to `deploy/try`:

```bash
git fetch origin
git push origin origin/main:deploy/try
```

Watch the GitHub Actions run until the repository checks, dry runs, deployment, and public verification all pass. The workflow serializes releases because D1 migrations, Queue updates, and Worker publication are not one atomic transaction.

<Callout type="warning">
  The checked-in workflow refuses to deploy from repositories other than its configured upstream. A fork must deliberately change that guard before expecting CI deployment to run.
</Callout>

## 4B. Local deployment with Wrangler [#4b-local-deployment-with-wrangler]

Use the same committed configuration from a clean, reviewed checkout. Wrangler can authenticate through `wrangler login`; exporting an API token instead makes the local command match CI more closely.

<Callout type="warning">
  Do not treat `just check` as the whole deployment preflight. The API deploy script applies pending remote D1 migrations as its first remote operation, before build and bundle validation. Complete every non-mutating check below on the exact release commit before running `just deploy`.
</Callout>

First export production credentials and confirm that the repository, submodules, and build-input directories are clean:

```bash
export CLOUDFLARE_ACCOUNT_ID="<your-account-id>"
export CLOUDFLARE_API_TOKEN="<your-api-token>"

git status --short --branch
test -z "$(git status --porcelain=v1 --untracked-files=all)"
git submodule foreach --recursive \
  'test -z "$(git status --porcelain=v1 --untracked-files=all)"'
test -z "$(git ls-files -v | grep -E '^[a-zS]')"
test -z "$(git ls-files --others --ignored --exclude-standard -- apps/web/src apps/web/public)"

just check
```

Exercise the complete migration chain against an isolated local D1 database, then inspect the production migration ledger and Queue list without changing them:

```bash
(
  cd apps/api
  persist_dir="$(mktemp -d)"
  trap 'rm -rf "$persist_dir"' EXIT
  ../../node_modules/.bin/vp exec wrangler d1 migrations apply DB \
    --local --env prod --persist-to "$persist_dir"
)

(
  cd apps/api
  ../../node_modules/.bin/vp exec wrangler d1 migrations list DB --remote --env prod
  ../../node_modules/.bin/vp exec wrangler queues list
)
```

Stop if the local migration chain fails. If the remote ledger reports pending migrations, inspect the exact SQL and proceed only when the migration is additive or explicitly approved. Confirm that all five Queues created in step 1 are present.

Build the Driver and Web assets and dry-run both Worker uploads. These commands validate configuration and bundles without publishing a Worker or applying a remote migration:

```bash
./node_modules/.bin/vp run --filter agent-driver build

(
  cd apps/api
  ../../node_modules/.bin/vp exec wrangler deploy --env prod --minify --dry-run
)

./node_modules/.bin/vp run --filter @mosoo/web build

(
  cd apps/web
  ../../node_modules/.bin/vp exec wrangler deploy --env prod --dry-run
)

git status --short
```

Only after every check above passes on the same clean commit should you publish:

```bash
just deploy
```

`just deploy` runs the full repository gate, then deploys the API before the Web Worker. The API deployment applies pending remote D1 migrations, verifies the expected schema, ensures required queues, builds the Driver container, and publishes the API Worker. The Web deployment then builds and publishes the console Worker.

To release only one side after diagnosing a partial failure:

```bash
just deploy-api
just deploy-web
```

These partial commands publish directly and do not run the full gate. Keep the same clean release commit, rerun the relevant build and dry-run steps above, and never rewrite an already-applied D1 migration. Add a new migration for every production schema change.

## 5. Verify the deployment [#5-verify-the-deployment]

Replace the example domain, then verify all three public paths:

```bash
curl --fail --silent --show-error https://console.example.com/ >/dev/null
curl --fail --silent --show-error https://console.example.com/api/health
curl --fail --silent --show-error https://console.example.com/api/graphql \
  -H 'content-type: application/json' \
  --data '{"query":"query { __typename }"}'
```

The console must load over HTTPS, `/api/health` must report an OK mosoo service, and GraphQL must return `Query`. Also inspect both Workers' logs and confirm that D1 migrations and Queue consumers are healthy before sending users to the deployment.

For the authoritative stop conditions, recovery guidance, and release acceptance checks, follow [`docs/production-deploy-verification.md`](https://github.com/langgenius/mosoo/blob/main/docs/production-deploy-verification.md) in the mosoo source repository.


# Environments (https://mosoo.ai/docs/environments/)





An Environment makes Agent sessions start with a consistent package set, setup script, and variables.

<img alt="The Environment editor defines packages, setup, variables, and network policy." src="__img0" />

## Create an Environment [#create-an-environment]

Open **Config → Environments → Create environment**, then configure:

* **Name and description** for the reusable template.
* **Packages** from public npm or PyPI with exact versions.
* **Setup script** that runs after prepared packages are restored.
* **Environment variables**, whose values are encrypted after save.
* **Network policy**: Full internet access or Limited access with a domain allowlist for Task Agents.

You can also create one from project dependency files with:

```bash
mosoo console environments create-environment
```

## Assign and revise [#assign-and-revise]

Make an Environment the Project default or select one on a specific Agent. A new session captures the selected Environment revision. Later edits apply only to sessions created afterward; in-flight sessions are unchanged.

## Network policies [#network-policies]

* **Full** keeps direct internet access enabled.
* **Limited** disables direct internet access and filters outbound HTTP/HTTPS traffic through a domain allowlist. The allowlist includes the Environment's allowed domains and the endpoints mosoo needs for runtime control and artifact storage.

Limited is supported only for **Task Agents** with session-scoped sandboxes. **Assistant Agents** share a sandbox across sessions and require Full. The runtime applies the policy before starting the sandbox and keeps it fixed for that session; start a new session to use a different policy.

If Limited cannot be enforced, the runtime rejects sandbox startup rather than falling back to unrestricted access. This includes local development with HTTPS interception disabled. Limited also rejects `HTTP_PROXY`, `HTTPS_PROXY`, and `ALL_PROXY` environment variables, including lowercase variants.

<Callout type="warning">
  A network allowlist controls destinations. It does not make allowed APIs or MCP tools read-only; use appropriate tool permissions and read-only credentials when accessing production systems.
</Callout>

## Package behavior [#package-behavior]

npm package CLIs are exposed through `PATH`, CommonJS packages through `NODE_PATH`, and PyPI modules through `PYTHONPATH`. Node ESM bare imports require a project-local install. OS packages, Cargo, RubyGems, and Go modules are not Environment package options.

The Project default and any Environment still selected by an Agent are protected from deletion.


# Errors and limits (https://mosoo.ai/docs/errors-and-limits/)



All non-2xx JSON errors use the same envelope:

```json
{
  "error": {
    "code": "invalid_request",
    "message": "Request body must be an object."
  }
}
```

Branch on `error.code`, not `error.message`. The message is for developers and should not be shown directly to end users.

## Error codes [#error-codes]

| HTTP | `error.code`           | Caller action                                                                            |
| ---- | ---------------------- | ---------------------------------------------------------------------------------------- |
| 400  | `invalid_request`      | Fix request shape, field value, body size, or unsupported field. Do not retry unchanged. |
| 400  | `invalid_json`         | Fix serialization or `Content-Type`.                                                     |
| 401  | `unauthenticated`      | Check `Authorization`; rotate or recreate the API token.                                 |
| 403  | `forbidden`            | Check that the API token can access this Agent, Thread, or file.                         |
| 404  | `not_found`            | Check that the ID exists and is visible to this API token.                               |
| 409  | `agent_not_published`  | Publish the Agent and enable API access.                                                 |
| 409  | `service_inactive`     | Republish or repair the Agent in mosoo.                                                  |
| 409  | `readiness_blocked`    | Fix Agent readiness or configuration in mosoo.                                           |
| 409  | `idempotency_conflict` | Wait for `Retry-After` if in-flight, or use a new key when the body differs.             |
| 429  | `rate_limited`         | Back off and retry after `Retry-After`.                                                  |
| 500  | `internal_error`       | Retry briefly with backoff; persist failure details if it repeats.                       |

## Idempotency [#idempotency]

`Idempotency-Key` is supported on:

* `POST /agents/{agentId}/threads`
* `POST /threads/{threadId}/events`

Rules:

* For Project keys, the idempotency key is scoped to the Project, method, and route; the body is checked for conflicts. Keys in the same Project share receipts and rate limits, including after rotation. Account CLI credentials use their own credential boundary.
* Reusing the same key with the same request replays the stored response.
* Reusing the same key with a different request returns `409 idempotency_conflict`.
* Reusing the key while the first request is still processing returns `409 idempotency_conflict`.
* Keys must be non-empty and 128 characters or fewer.
* Conflict responses can include `Retry-After`.

## Public limits [#public-limits]

| Limit                    | Value            |
| ------------------------ | ---------------- |
| Create Thread input text | 32000 characters |
| `userId`                 | 255 characters   |
| File ID                  | 26 characters    |
| File upload              | 67108864 bytes   |
| Event list default       | 100 events       |
| Event list maximum       | 1000 events      |
| Thread list maximum      | 100 Threads      |

<Cards>
  <Card title="API Reference" href="https://mosoo.ai/docs/api-reference/">
    Generated endpoint-level request and response details.
  </Card>

  <Card title="Authentication and access" href="https://mosoo.ai/docs/auth-and-access/">
    API token and Agent access checks.
  </Card>
</Cards>


# Events and streaming (https://mosoo.ai/docs/events-and-streaming/)



Thread events are the stable read surface for mosoo API integrations. They expose public state only. Raw runtime payloads, private transcripts, and internal diagnostics are not part of this API.

## Read snapshots [#read-snapshots]

Use snapshots for polling, jobs, and backend state reconciliation:

```http
GET /api/v1/threads/{threadId}/events?limit=100
```

The response returns `events` oldest first within the requested window. `truncated` is true when older public events were omitted because the limit was reached. The default limit is 100 and the maximum is 1000.

Each event has:

| Field        | Meaning                                                             |
| ------------ | ------------------------------------------------------------------- |
| `id`         | Stable event ID, bare ULID.                                         |
| `runId`      | Run ID for run-scoped events, or `null`.                            |
| `type`       | Public event type such as `agent.message.delta` or `run.completed`. |
| `status`     | `available`, `error`, or `unsupported`.                             |
| `content`    | Public event content or a reference to the associated payload.      |
| `occurredAt` | RFC 3339 timestamp.                                                 |
| `durationMs` | Duration when applicable.                                           |
| `tokens`     | Token count when applicable.                                        |

## Stream updates [#stream-updates]

Use SSE for long-running user experiences:

```http
GET /api/v1/threads/{threadId}/events/stream?limit=100
```

The stream starts with a comment heartbeat:

```text
: connected
```

Each public event is emitted as:

```text
event: thread.event
id: 01J00000000000000000000010
data: {"id":"01J00000000000000000000010","runId":"01J0000000000000000000000A","type":"run.started","status":"available","content":"01J0000000000000000000000A","occurredAt":"2026-05-19T00:00:01.000Z","durationMs":null,"tokens":null}
```

The stream suppresses duplicate event IDs observed during polling. Keepalive comments are sent while no new events are available. If the stream fails after it starts, mosoo emits `event: thread.error` with the standard error envelope.

## Submitted events [#submitted-events]

Send caller input to a Thread with:

```http
POST /api/v1/threads/{threadId}/events
```

Supported submitted event variants:

```json
{
  "events": [
    {
      "type": "user_message",
      "requestId": "ticket-182-message-1",
      "resources": [
        {
          "type": "file",
          "file_id": "01J0000000000000000000000J"
        }
      ],
      "text": "Summarize the attached file."
    },
    {
      "type": "permission_decision",
      "requestId": "tool-request-1",
      "decision": "allow_once"
    },
    {
      "type": "user_interrupt",
      "runId": null
    }
  ]
}
```

Use `Idempotency-Key` on submitted events so a network retry does not send the same user input twice.

## Reconstruct output [#reconstruct-output]

For current UI rendering, group public events by `runId`. Concatenate `agent.message.delta` events for the target Run in chronological order. After a Run is `completed`, prefer `run.finalOutput.text` from Thread or send-event responses when it is present.

<Cards>
  <Card title="List Thread events" href="https://mosoo.ai/docs/api-reference/list-thread-events/">
    Snapshot endpoint reference.
  </Card>

  <Card title="Stream Thread events" href="https://mosoo.ai/docs/api-reference/stream-thread-events/">
    SSE endpoint reference.
  </Card>

  <Card title="Send events" href="https://mosoo.ai/docs/api-reference/send-user-messages-permission-decisions-or-interrupts-to-a-thread/">
    Submitted event schema.
  </Card>
</Cards>


# Files (https://mosoo.ai/docs/files/)



Files uploaded through the public API are draft file resources scoped to an Agent API Endpoint Project. Mount them when creating a Thread or sending a user message. Files produced by the Agent are artifacts. Both appear in the Thread file list when visible to the API token caller.

## Upload flow [#upload-flow]

Public uploads use `multipart/form-data` and accept files up to 67108864 bytes.

1. Upload the file to the Agent with `POST /agents/{agentId}/files`.
2. Store the returned `file.id`.
3. Mount the file with `resources` when creating a Thread or sending a later user message.

## Upload a file [#upload-a-file]

```bash
printf 'Customer asks for an implementation plan.' > brief.txt

curl -X POST "https://cloud.mosoo.ai/api/v1/agents/$MOSOO_AGENT_ID/files" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -F "file=@brief.txt;type=text/plain"
```

The response is a `PublicFileResponse`. Store `file.id`:

```json
{
  "file": {
    "id": "01J0000000000000000000000J",
    "name": "brief.txt",
    "mimeType": "text/plain",
    "size": 41,
    "createdAt": "2026-05-19T00:02:00.000Z"
  }
}
```

## Use a file in the first message [#use-a-file-in-the-first-message]

```bash
curl -X POST "https://cloud.mosoo.ai/api/v1/agents/$MOSOO_AGENT_ID/threads" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "customer-123",
    "resources": [
      {
        "type": "file",
        "file_id": "01J0000000000000000000000J"
      }
    ],
    "input": {
      "type": "user.message",
      "content": [
        {
          "type": "text",
          "text": "Summarize the attached file."
        }
      ]
    }
  }'
```

## Use a file in a later message [#use-a-file-in-a-later-message]

Send the file ID in `resources` on a later user message:

```json
{
  "events": [
    {
      "type": "user_message",
      "resources": [
        {
          "type": "file",
          "file_id": "01J0000000000000000000000J"
        }
      ],
      "text": "Summarize the attached file."
    }
  ]
}
```

<Cards>
  <Card title="Upload Agent file" href="https://mosoo.ai/docs/api-reference/upload-an-agent-file/">
    Upload a file before creating or continuing a Thread.
  </Card>

  <Card title="Retrieve file metadata" href="https://mosoo.ai/docs/api-reference/retrieve-file-metadata/">
    Read metadata for an uploaded or attached file.
  </Card>

  <Card title="Download content" href="https://mosoo.ai/docs/api-reference/download-thread-file-content/">
    Download bytes for an attached file or Agent artifact.
  </Card>

  <Card title="Delete file" href="https://mosoo.ai/docs/api-reference/delete-a-file/">
    Delete a pre-Thread upload or visible Thread file.
  </Card>
</Cards>


# Create your first Agent (https://mosoo.ai/docs/first-agent/)







This guide takes you from an empty Project to a published Agent.

## 1. Open a Project [#1-open-a-project]

Sign in at [cloud.mosoo.ai](https://cloud.mosoo.ai). mosoo creates a **Default Project** for a new account. Use the Project switcher to create or open another Project when you need a separate resource and usage boundary.

## 2. Add a Provider key [#2-add-a-provider-key]

Open **Config → Providers**. Add a key for the runtime you plan to use and run the optional connection test. A ready runtime appears at the top of the page.

<Callout type="warning">
  Provider credentials belong to the active Project. Saved keys are masked; exported Agent packages do not contain them.
</Callout>

## 3. Create the Agent [#3-create-the-agent]

Open **Agents → Create agent**, enter a name, and choose a runtime.

<img alt="The New Agent dialog offers Claude Agent SDK, OpenAI Runtime, and OpenCode." src="__img0" />

* **Claude Agent SDK** resolves an Anthropic key.
* **OpenAI Runtime** resolves an OpenAI-compatible key and requires a compatible Responses API endpoint.
* **OpenCode** can use supported provider credentials, including custom OpenAI-compatible endpoints.

## 4. Configure behavior [#4-configure-behavior]

In **Preview**, choose **Assistant Agent** or **Task Agent**, then set the model and system prompt. Add Skills, MCP servers, or a custom Environment only when the Agent needs them.

<img alt="Agent Preview combines live testing with the configuration editor." src="__img1" />

## 5. Test before publishing [#5-test-before-publishing]

Send a representative task in the left Preview pane. Verify the answer, tool calls, files, and failure behavior. Use **Logs** for execution details and **Cost** for model usage. Assistant Agents also expose a **Terminal** and reset controls for their working environment.

## 6. Publish [#6-publish]

Open **Publish** and publish the draft. The first publish locks the Agent type. Later sessions start on the current published version; existing sessions keep the version they started with.

After publishing, choose a delivery surface:

* **Thread** — start work inside the mosoo console.
* **API Access** — obtain the Agent ID and call the Public Thread API.
* **Instruction for LLM** — copy Agent instructions for supported coding-agent workflows.

<Cards>
  <Card title="Configure an Agent" href="https://mosoo.ai/docs/agent-configuration/">
    Understand every configuration field.
  </Card>

  <Card title="Preview and debug" href="https://mosoo.ai/docs/test-and-debug/">
    Test realistic tasks and diagnose failures.
  </Card>

  <Card title="Publish and API access" href="https://mosoo.ai/docs/publish-and-api-access/">
    Choose a delivery surface.
  </Card>
</Cards>


# Import, export, fork, and versions (https://mosoo.ai/docs/import-export-versions/)





## Export an Agent [#export-an-agent]

Open Agent settings and choose **Export agent**. mosoo downloads a `.agent` package containing portable Agent setup and packaged Skills.

## Import a package [#import-a-package]

On the Agents page, choose **Import package**, select a `.agent` file, and review any reported repairs. The result is an editable draft in the active Project.

<img alt="Import creates a new draft from a portable .agent package." src="__img0" />

## Fork an Agent [#fork-an-agent]

Open Agent settings and choose **Fork agent**. Forking creates a separate draft in the same Project and leaves the original unchanged. Use it to change a published Agent's locked type or test a different configuration.

## What does not travel [#what-does-not-travel]

A `.agent` package is not a Project backup or running-state snapshot. It does not contain:

* Provider or MCP credentials;
* conversations, logs, or usage history;
* live runtime state or working files.

Reconnect external services and reselect missing Environment or secret values in the destination Project.

## Version history [#version-history]

Open the draft or live-version badge to view versions newest first. The list identifies the live version and summarizes runtime, model, changes, and publish time. New sessions use the live version; existing sessions retain the version they started with.

Version history is read-only. Complete historical configuration, side-by-side comparison, publisher identity, and restore are not available today.


# mosoo documentation (https://mosoo.ai/docs/)



mosoo gives you one workspace to configure AI Agents, test them against real tasks, publish stable versions, operate their Runs and files, and integrate them through a Public Thread API.

<Cards>
  <Card title="Create your first Agent" href="https://mosoo.ai/docs/first-agent/">
    Configure a Provider, build an Agent, test it, and publish.
  </Card>

  <Card title="Product tour" href="https://mosoo.ai/docs/product-tour/">
    Understand Projects, Agents, Threads, Runs, and delivery surfaces.
  </Card>

  <Card title="CLI setup" href="https://mosoo.ai/docs/cli/overview/">
    Install the CLI, sign in, and inspect cloud readiness.
  </Card>

  <Card title="API quickstart" href="https://mosoo.ai/docs/quickstart/">
    Call a published Agent from your backend with curl.
  </Card>
</Cards>

## Direct answers [#direct-answers]

* **What is mosoo?** mosoo is an open-source Agent runtime and API for coding agents. It gives product teams hosted Threads, files, sandboxed execution, tool events, and API access around published Agents.
* **What should I read first?** Start with [Create your first Agent](https://mosoo.ai/docs/first-agent/), then use the [API quickstart](https://mosoo.ai/docs/quickstart/) when you are ready to call a published Agent from a trusted backend.
* **What is the Public Thread API?** It is the backend API for interacting with an already published Agent. It creates and resumes Threads, reads or streams events, and transfers files.
* **Where should credentials live?** Use a Project API key (`msp_`) from the same Project as the Agent. Keep it on a trusted server or automation runner; legacy account tokens are rejected. Browser and mobile clients should call your backend, which then calls Mosoo.

## Sources and verification [#sources-and-verification]

* [GitHub source](https://github.com/langgenius/mosoo) shows the open-source runtime and license.
* [API reference](https://mosoo.ai/docs/api-reference/) documents the Public Thread API generated from the OpenAPI contract.
* [OpenAPI 3.1](https://cloud.mosoo.ai/api/v1/openapi.json) is the machine-readable API source.
* [llms.txt](https://mosoo.ai/docs/llms.txt) and [llms-full.txt](https://mosoo.ai/docs/llms-full.txt) expose concise and complete documentation indexes for AI answer engines.

## Build [#build]

* Choose an [Project boundary and Agent type](https://mosoo.ai/docs/concepts/).
* Add [Provider credentials and models](https://mosoo.ai/docs/providers-and-models/).
* Configure the Agent's [identity, runtime, instructions, Skills, MCP, and Environment](https://mosoo.ai/docs/agent-configuration/).
* [Preview and debug](https://mosoo.ai/docs/test-and-debug/) before publishing.

## Publish and operate [#publish-and-operate]

* [Publish the Agent and enable API access](https://mosoo.ai/docs/publish-and-api-access/).
* Track [Runs, files, and usage](https://mosoo.ai/docs/operations/).
* Reuse setup through [import, export, fork, and version history](https://mosoo.ai/docs/import-export-versions/).

## Integrate [#integrate]

The Public Thread API is for interacting with an already published Agent. It creates and resumes Threads, reads or streams events, and transfers files. Agent creation and configuration remain console or CLI operations.

<Cards>
  <Card title="Core API concepts" href="https://mosoo.ai/docs/threads-and-runs/">
    Understand Thread and Run lifecycle.
  </Card>

  <Card title="API reference" href="https://mosoo.ai/docs/api-reference/">
    Browse generated request and response schemas.
  </Card>

  <Card title="Errors and limits" href="https://mosoo.ai/docs/errors-and-limits/">
    Build safe retries and handle failure states.
  </Card>
</Cards>


# Runs, files, and usage (https://mosoo.ai/docs/operations/)









## Runs and Threads [#runs-and-threads]

Open **Runs** to dispatch Agents and track work. Filter All, Unread, Pinned, or Failed Threads. A Thread can be reopened by replying asynchronously; its Runs preserve status and event history.

<img alt="The Runs page groups active and completed Agent Threads." src="__img0" />

Browser notifications can alert you when an Agent finishes. Notification permission belongs to the browser and is optional.

## Files [#files]

Open **Files** to review Project files, Thread attachments, and runtime artifacts. Filter by Agent, Thread, or file role, then search or preview an item.

<img alt="Files are grouped by Project, Agent, Thread, attachment, and artifact role." src="__img1" />

Deleting or changing an Agent does not turn a `.agent` export into a file backup; runtime files and conversation history have separate lifecycles.

## Project usage [#project-usage]

Open **Project Settings → Project usage**. Filter All, Production, or Debug and choose 7 days, 30 days, month to date, or 90 days. Review Overview, By Agent, and By Model, or export the current tab as CSV.

<img alt="Project Usage shows estimated spend, model calls, token trends, Agents, and models." src="__img2" />

<Callout type="info">
  Dollar values are estimates from recorded model calls and reference prices. They are not Provider invoices or mosoo charges and can be understated for unknown models without reported cost.
</Callout>

Budgets, alerts, invoices, payment controls, and per-user usage are not available in the current single-owner product.


# Product tour (https://mosoo.ai/docs/product-tour/)



mosoo is a managed workspace for building, running, publishing, and operating AI Agents. You configure an Agent once, test it in the console, then use it through a Thread or an API endpoint.

## The product model [#the-product-model]

| Resource         | What it owns                                                                                                                  |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| **Organization** | Your account-level container. The current product is a single-owner experience; team roles and invitations are not available. |
| **Project**      | The isolation boundary for Agents, files, configuration, and usage. A new account starts with a Default Project.              |
| **Agent**        | A reusable worker with a type, runtime, model, instructions, Skills, MCP connections, and an Environment.                     |
| **Thread**       | The durable conversation and work record for one Agent. Replies can resume work asynchronously.                               |
| **Run**          | One execution inside a Thread. Runs produce events, logs, usage, and files.                                                   |

## A typical workflow [#a-typical-workflow]

1. Open or create a Project.
2. Add a model Provider key.
3. Create an Agent and choose its runtime.
4. Configure its identity, instructions, Skills, MCP servers, and Environment.
5. Test in **Preview**; inspect **Logs**, **Cost**, and **Terminal** when applicable.
6. Publish the Agent.
7. Start Threads in mosoo or enable API access.
8. Monitor Runs, files, versions, and usage.

<Callout type="info">
  Most configuration belongs to the active Project. Provider keys, MCP credentials, Skills, and Environments do not automatically cross Project boundaries.
</Callout>

<Cards>
  <Card title="Create your first Agent" href="https://mosoo.ai/docs/first-agent/">
    Follow the complete console path.
  </Card>

  <Card title="Projects, Agents, and runtimes" href="https://mosoo.ai/docs/concepts/">
    Choose the right boundaries and execution model.
  </Card>

  <Card title="CLI setup" href="https://mosoo.ai/docs/cli/overview/">
    Install the CLI and connect it to mosoo Cloud.
  </Card>
</Cards>


# Providers and models (https://mosoo.ai/docs/providers-and-models/)





Provider credentials are stored inside the active Project and resolved when an Agent starts.

<img alt="The Providers page shows runtime readiness and Project-level credentials." src="__img0" />

## Add a Provider key [#add-a-provider-key]

1. Open **Config → Providers**.
2. Find a built-in Provider and select **Add key**, or choose **Add custom model**.
3. Enter a name, API key, optional base URL, and supported model names when requested.
4. Select **Test** to verify connectivity, then save.
5. Return to the Agent and select the runtime and model.

Keys can be named, edited, tested, made default, and deleted. Saving is not conditional on a successful optional test.

## Runtime readiness [#runtime-readiness]

The **Runtime availability** card explains which credential a runtime will resolve. A missing matching key stops setup or the Run with a configuration error; mosoo never borrows a credential from another Project.

## Custom endpoints [#custom-endpoints]

Custom OpenAI-compatible credentials can run through OpenCode. OpenAI Runtime additionally requires the endpoint to implement the Responses API used by that runtime.

## Credential boundary [#credential-boundary]

* Saved keys are encrypted and shown only in masked form.
* Raw values are not included in Agent settings, logs, diagnostics, or `.agent` exports.
* Provider credentials do not inherit across Projects.
* Deleting a key can make dependent Agents unable to start; inspect affected runtime readiness before removing it.


# Publish and API access (https://mosoo.ai/docs/publish-and-api-access/)







Publishing snapshots the draft configuration and makes delivery surfaces available.

<img alt="The Publish menu exposes Thread, API Access, and coding-agent instructions." src="__img0" />

## Publish a draft [#publish-a-draft]

1. Finish Preview tests.
2. Open **Publish** and publish the draft.
3. Review the live-version badge and version summary.

The first publish locks the Agent type. New sessions use the current live version; sessions already in progress keep their original version.

## Start a Thread [#start-a-thread]

Choose **Thread** or open **Runs → New thread**, select the Agent, enter the task, and dispatch it. Reply later to resume the same Thread asynchronously.

<img alt="A new Thread assigns one Agent and one initial task." src="__img1" />

## Enable API access [#enable-api-access]

Choose **API Access** from the Publish menu and copy the bare ULID Agent ID. Open that Agent’s **Project settings → Project API keys**, create a Project key (`msp_`), and copy its secret when shown. A key from another Project cannot call this Agent.

Use the token only in an `Authorization: Bearer` header. API access creates and resumes Threads; it does not create, edit, or publish Agents.

<Cards>
  <Card title="API quickstart" href="https://mosoo.ai/docs/quickstart/">
    Create a Thread with curl.
  </Card>

  <Card title="Authentication and access" href="https://mosoo.ai/docs/auth-and-access/">
    Understand tokens and Agent access.
  </Card>

  <Card title="API reference" href="https://mosoo.ai/docs/api-reference/">
    Browse every Public Thread API operation.
  </Card>
</Cards>


# Quickstart (https://mosoo.ai/docs/quickstart/)



Create a Thread on a published Agent, send one follow-up message, read the public event log, and attach a file.

## Before you start [#before-you-start]

You need:

* A published Agent with API access enabled in mosoo.
* The `agentId` from the Agent API Access panel.
* A mosoo API token that is allowed to call that Agent.
* An opaque `userId` for the application user authenticated by your backend.

```bash
export MOSOO_API_BASE="https://cloud.mosoo.ai/api/v1"
export MOSOO_API_TOKEN="msp_..."
export MOSOO_AGENT_ID="01J00000000000000000000001"
```

<Callout type="info">
  v1 resource IDs are bare ULIDs, not prefixed IDs such as `agent_...` or `thread_...`.
</Callout>

## 1. Create a Thread [#1-create-a-thread]

A Thread is the API conversation container for a published Agent. Creating one with `input` also queues the first Run.

```bash
curl -X POST "$MOSOO_API_BASE/agents/$MOSOO_AGENT_ID/threads" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-create-thread" \
  -d '{
    "userId": "customer-123",
    "input": {
      "type": "user.message",
      "content": [
        {
          "type": "text",
          "text": "Say hello and explain what you can help with."
        }
      ]
    }
  }'
```

Copy `thread.id` from the response:

```bash
export MOSOO_THREAD_ID="01J00000000000000000000009"
```

## 2. Send another message [#2-send-another-message]

Use `thread.id` to continue the same Agent interaction.

```bash
curl -X POST "$MOSOO_API_BASE/threads/$MOSOO_THREAD_ID/events" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-send-message-1" \
  -d '{
    "events": [
      {
        "type": "user_message",
        "requestId": "quickstart-message-1",
        "text": "Give me the three most important next steps."
      }
    ]
  }'
```

You can also send `permission_decision` or `user_interrupt` events when the current Run is waiting for input or still executing.

## 3. Read the event log [#3-read-the-event-log]

Read public events in chronological order.

```bash
curl "$MOSOO_API_BASE/threads/$MOSOO_THREAD_ID/events?limit=100" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN"
```

The event log is the stable place to read results. It can include user messages, Agent message deltas, thinking deltas, tool status, file changes, usage updates, and run status.

## 4. Attach a file [#4-attach-a-file]

Upload the file to the Agent first:

```bash
printf 'Customer asks for an implementation plan.' > brief.txt

curl -X POST "$MOSOO_API_BASE/agents/$MOSOO_AGENT_ID/files" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -F "file=@brief.txt;type=text/plain"
```

Copy `file.id` from the response:

```bash
export MOSOO_FILE_ID="01J0000000000000000000000J"
```

Send the file with a later user message:

```bash
curl -X POST "$MOSOO_API_BASE/threads/$MOSOO_THREAD_ID/events" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-file-message-1" \
  -d '{
    "events": [
      {
        "type": "user_message",
        "requestId": "quickstart-file-message-1",
        "resources": [
          {
            "type": "file",
            "file_id": "01J0000000000000000000000J"
          }
        ],
        "text": "Summarize the attached file."
      }
    ]
  }'
```

To include a file in the first user message, upload it before step 1 and add the same `resources` array to the create-Thread request.

<Cards>
  <Card title="Threads and Runs" href="https://mosoo.ai/docs/threads-and-runs/">
    Understand Thread and Run lifecycle states.
  </Card>

  <Card title="Events and streaming" href="https://mosoo.ai/docs/events-and-streaming/">
    Read snapshots or stream Thread events with SSE.
  </Card>

  <Card title="Files" href="https://mosoo.ai/docs/files/">
    Upload files and mount them into Thread messages.
  </Card>

  <Card title="Errors and limits" href="https://mosoo.ai/docs/errors-and-limits/">
    Handle retries, idempotency conflicts, rate limits, and invalid requests.
  </Card>
</Cards>


# Skills and MCP servers (https://mosoo.ai/docs/skills-and-mcp/)







Skills and MCP servers are Project-owned resources that can be attached to selected Agents.

## Skills [#skills]

A Skill packages trusted instructions and supporting files so you do not have to copy them into every prompt.

1. Open **Config → Skills → Add skill**.
2. Upload a `.md`, `.zip`, or `.skill` file, upload a folder whose root contains `SKILL.md`, or import from GitHub or skills.sh.
3. Review the detected name, description, and author.
4. Open an Agent and choose **Add skill**.

<img alt="Skills can be uploaded from a file or folder, or imported from a URL." src="__img0" />

The current console can download, fork, and uninstall a Skill, but it has no in-app editor or update action. Forks are independent copies. Uninstalling can leave existing Agent attachments marked **Missing**.

## MCP servers [#mcp-servers]

1. Open **Config → MCP servers → Add MCP**.
2. Enter a name and Remote HTTPS URL.
3. Choose OAuth or bearer-token authorization and save.
4. Finish authorization, then attach the connection in the Agent editor.
5. Test it by asking the Agent to use the tool in Preview or a new Thread.

<img alt="An MCP connection uses OAuth or a bearer token with a Remote HTTPS server." src="__img1" />

<Callout type="warning">
  **Connected** means mosoo has a stored credential; it does not prove the remote server or every tool works. Failures currently surface when an Agent uses the server.
</Callout>

MCP credentials are encrypted and never shown again after entry. Local-process MCP, cross-Project sharing, a connector marketplace, and per-tool selection are not available.


# Preview and debug (https://mosoo.ai/docs/test-and-debug/)



Use the Agent workspace to test draft configuration before publishing.

## Preview [#preview]

Enter a representative task in the left pane. Test:

* a normal request and expected output;
* a request that uses each attached Skill or MCP server;
* file input and generated artifacts;
* missing information and clarification behavior;
* tool, credential, or Environment failure paths.

Draft changes affect Preview immediately. A green **Ready** state means the editor is ready to accept a task; it is not proof that every external dependency works.

## Logs [#logs]

Open **Logs** to inspect session and execution history. Use it to correlate runtime startup, tool use, and failures. Secrets should not appear in logs; if a raw credential is present in user-authored content, remove it before sharing diagnostics.

## Cost [#cost]

Open **Cost** for Agent-level spend estimates, model mix, and recent usage events. Filter production and debug use separately. Cost values are estimates from recorded model calls, not Provider invoices.

## Terminal and reset [#terminal-and-reset]

Assistant Agents expose a Terminal and working-state controls because their environment can persist across sessions. Use reset when you intentionally want a clean state; it can remove local workspace state, caches, or sign-ins. Task Agents start clean for every Run and do not expose the same persistent controls.

## Diagnose common failures [#diagnose-common-failures]

1. **Runtime needs a key:** configure the matching Provider in this Project.
2. **Model is unavailable:** verify the Provider's model list and endpoint compatibility.
3. **MCP tool fails:** confirm the connection is enabled and authorized, then retry a direct tool task.
4. **Environment startup fails:** check exact package versions, setup script, and required variables.
5. **Old session behaves differently:** start a new session to use the current published version.


# Threads and Runs (https://mosoo.ai/docs/threads-and-runs/)



mosoo exposes a published Agent through Thread-based APIs. Your application creates or reuses a Thread, then sends user events that queue Runs. mosoo executes each Run inside the published Agent configuration and writes public events back to the Thread.

## Resource model [#resource-model]

| Concept            | Meaning                                                                                               |
| ------------------ | ----------------------------------------------------------------------------------------------------- |
| Agent API Endpoint | The published Agent entry point from the Agent API Access panel. `agentId` is a bare ULID in v1.      |
| Thread             | The conversation container created through the API. Store `thread.id` in your application.            |
| Run                | One execution pass of the Agent on a Thread. A create-thread input or user message can queue a Run.   |
| Event              | A public timeline entry for input, Agent output, tool state, files, usage, and Run lifecycle changes. |

Resource IDs in v1 are bare ULIDs. Do not add prefixes such as `agent_`, `thread_`, `file_`, or `run_`.

## Create and retrieve [#create-and-retrieve]

Create a Thread for a published Agent:

```http
POST /api/v1/agents/{agentId}/threads
```

If `input` is present, mosoo queues the initial Run. If `input` is omitted, mosoo creates an empty `IDLE` Thread with no Run.

Retrieve current Thread state:

```http
GET /api/v1/threads/{threadId}
```

The response includes `thread`, the latest `run` when one exists, and convenience `links`.

## Thread status [#thread-status]

| Status         | Meaning                                       |
| -------------- | --------------------------------------------- |
| `IDLE`         | No active Run. A user message can queue work. |
| `RUNNING`      | A Run is executing.                           |
| `RESCHEDULING` | The Thread is between Runs.                   |
| `TERMINATED`   | The Thread has ended.                         |

## Run status [#run-status]

| Status          | Meaning                                                      |
| --------------- | ------------------------------------------------------------ |
| `queued`        | Run exists but has not started.                              |
| `booting`       | Runtime is preparing.                                        |
| `running`       | Run is executing.                                            |
| `waiting_input` | Run is blocked on caller input, often a permission decision. |
| `completed`     | Terminal success. `finalOutput.text` is stable when present. |
| `failed`        | Terminal failure. Inspect `run.error`.                       |
| `cancelled`     | Terminal cancellation.                                       |
| `expired`       | Terminal timeout or expiry.                                  |

## Lifecycle operations [#lifecycle-operations]

Use lifecycle endpoints to keep your app-side Thread list clean:

| Operation                 | Endpoint                                    |
| ------------------------- | ------------------------------------------- |
| List Threads for an Agent | `GET /api/v1/agents/{agentId}/threads`      |
| Archive a Thread          | `POST /api/v1/threads/{threadId}/archive`   |
| Unarchive a Thread        | `POST /api/v1/threads/{threadId}/unarchive` |
| Delete a Thread           | `DELETE /api/v1/threads/{threadId}`         |

Archive hides a Thread from default active lists. Delete permanently deletes the Thread and its backing AgentSession.

<Cards>
  <Card title="Create a Thread" href="https://mosoo.ai/docs/api-reference/create-a-thread-for-an-agent-api-endpoint/">
    Full request and response schema.
  </Card>

  <Card title="Send events" href="https://mosoo.ai/docs/api-reference/send-user-messages-permission-decisions-or-interrupts-to-a-thread/">
    Queue a Run, answer a permission request, or interrupt execution.
  </Card>

  <Card title="List Thread events" href="https://mosoo.ai/docs/api-reference/list-thread-events/">
    Read public events for rendering output and status.
  </Card>
</Cards>


# Common Agent patterns (https://mosoo.ai/docs/use-cases/)



Use these patterns as starting points, then test with your own data and failure cases.

## Ongoing research assistant [#ongoing-research-assistant]

* **Type:** Assistant Agent
* **Why:** repeated research benefits from a continuing workspace.
* **Configuration:** a citation-focused prompt, relevant research Skills, optional Remote HTTPS MCP sources, and a reusable Environment for analysis packages.
* **Delivery:** mosoo Threads for interactive work; API access for embedding in another product.

## Pull-request reviewer [#pull-request-reviewer]

* **Type:** Task Agent
* **Why:** each review should start in clean temporary state.
* **Configuration:** repository-review Skill, GitHub MCP connection, strict output format, and a minimal Environment.
* **Delivery:** one Thread per review or an external system calling the Public Thread API.

## Ticket triage worker [#ticket-triage-worker]

* **Type:** Task Agent
* **Why:** tickets are independent jobs and should not leak temporary state.
* **Configuration:** triage rubric in a Skill, issue-tracker MCP, and explicit rules for labels and escalation.
* **Operations:** filter failed Threads, inspect Logs, and monitor production usage separately from Preview.

## Team copilot [#team-copilot]

* **Type:** Assistant Agent
* **Why:** the copilot benefits from a stable working directory across sessions.
* **Configuration:** product and operations Skills plus authorized MCP connections.
* **Boundary:** mosoo's current console is single-owner; team roles and shared administration are not available. Expose the Agent through an appropriate external surface rather than sharing owner credentials.

## Public application [#public-application]

Publish the Agent, then use the Public Thread API from your backend to create or resume a Thread for each application user.


# Archive a Thread (https://mosoo.ai/docs/api-reference/archive-a-thread/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Create a Thread for an Agent API Endpoint (https://mosoo.ai/docs/api-reference/create-a-thread-for-an-agent-api-endpoint/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Delete a file (https://mosoo.ai/docs/api-reference/delete-a-file/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Delete a Thread (https://mosoo.ai/docs/api-reference/delete-a-thread/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Download Thread file content (https://mosoo.ai/docs/api-reference/download-thread-file-content/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# API Reference (https://mosoo.ai/docs/api-reference/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}

## Threads [#threads]

<Cards>
  <Card href="https://mosoo.ai/docs/api-reference/create-a-thread-for-an-agent-api-endpoint/" title="Create a Thread for an Agent API Endpoint" />

  <Card href="https://mosoo.ai/docs/api-reference/list-threads-for-an-agent-api-endpoint/" title="List Threads for an Agent API Endpoint" />

  <Card href="https://mosoo.ai/docs/api-reference/retrieve-thread-summary/" title="Retrieve Thread summary" />

  <Card href="https://mosoo.ai/docs/api-reference/archive-a-thread/" title="Archive a Thread" />

  <Card href="https://mosoo.ai/docs/api-reference/unarchive-a-thread/" title="Unarchive a Thread" />

  <Card href="https://mosoo.ai/docs/api-reference/delete-a-thread/" title="Delete a Thread" />
</Cards>

## Events [#events]

<Cards>
  <Card href="https://mosoo.ai/docs/api-reference/send-user-messages-permission-decisions-or-interrupts-to-a-thread/" title="Send user messages, permission decisions, or interrupts to a Thread" />

  <Card href="https://mosoo.ai/docs/api-reference/list-thread-events/" title="List Thread events" />

  <Card href="https://mosoo.ai/docs/api-reference/stream-thread-events/" title="Stream Thread events" />
</Cards>

## Files [#files]

<Cards>
  <Card href="https://mosoo.ai/docs/api-reference/upload-an-agent-file/" title="Upload an Agent file" />

  <Card href="https://mosoo.ai/docs/api-reference/retrieve-file-metadata/" title="Retrieve file metadata" />

  <Card href="https://mosoo.ai/docs/api-reference/list-thread-files/" title="List Thread files" />

  <Card href="https://mosoo.ai/docs/api-reference/download-thread-file-content/" title="Download Thread file content" />

  <Card href="https://mosoo.ai/docs/api-reference/delete-a-file/" title="Delete a file" />

  <Card href="https://mosoo.ai/docs/api-reference/remove-a-thread-file/" title="Remove a Thread file" />
</Cards>


# List Thread events (https://mosoo.ai/docs/api-reference/list-thread-events/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# List Thread files (https://mosoo.ai/docs/api-reference/list-thread-files/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# List Threads for an Agent API Endpoint (https://mosoo.ai/docs/api-reference/list-threads-for-an-agent-api-endpoint/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Remove a Thread file (https://mosoo.ai/docs/api-reference/remove-a-thread-file/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Retrieve file metadata (https://mosoo.ai/docs/api-reference/retrieve-file-metadata/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Retrieve Thread summary (https://mosoo.ai/docs/api-reference/retrieve-thread-summary/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Send user messages, permission decisions, or interrupts to a Thread (https://mosoo.ai/docs/api-reference/send-user-messages-permission-decisions-or-interrupts-to-a-thread/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Stream Thread events (https://mosoo.ai/docs/api-reference/stream-thread-events/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Unarchive a Thread (https://mosoo.ai/docs/api-reference/unarchive-a-thread/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Upload an Agent file (https://mosoo.ai/docs/api-reference/upload-an-agent-file/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# CLI (https://mosoo.ai/docs/cli/overview/)



The `mosoo` CLI exposes the Public Thread API, Console GraphQL operations, console REST operations, and a machine-readable command catalog.

## Install [#install]

```bash
curl -fsSL https://install.mosoo.ai/install.sh | bash
```

The installer places the CLI in `~/.local/bin`, installs the `@mosoo` coding-agent Skill, signs in to [cloud.mosoo.ai](https://cloud.mosoo.ai), and runs `doctor`. Review options without changing your system:

```bash
curl -fsSL https://install.mosoo.ai/install.sh | bash -s -- --dry-run
```

## Authenticate and verify [#authenticate-and-verify]

Interactive browser login:

```bash
mosoo auth login --hostname cloud.mosoo.ai
mosoo auth status --hostname cloud.mosoo.ai
mosoo doctor --json
```

Project keys (`msp_`) do not authorize account management. Use browser login for account-wide Console operations and sign in again after the key cutover to replace legacy credentials with `mcli_` credentials. See [Authentication and access](https://mosoo.ai/docs/auth-and-access/).

For non-interactive login, pipe a token through standard input instead of placing it in shell history:

```bash
printf '%s' "$MOSOO_API_TOKEN" | \
  mosoo auth login --hostname cloud.mosoo.ai --with-token
```

## Discover commands [#discover-commands]

```bash
mosoo --help
mosoo commands --json
mosoo commands show console environments create-environment
mosoo search "create environment"
```

`commands --json` is intended for tools and coding Agents. `commands show` provides the precise schema for one generated command.

## Common operations [#common-operations]

```bash
mosoo ls -o json
mosoo run --help
mosoo console environments create-environment --help
```

CLI commands are generated from the contract. Update the CLI and inspect its command help first; an older CLI exposing `--input-app-id` does not match the current Project contract. Use the [API quickstart](https://mosoo.ai/docs/quickstart/) for a complete execution example.

Use `--target local|cloud|custom`, `--base-url`, or `--hostname` to control endpoint resolution. Output formats are `table`, `json`, `yaml`, and `raw`.

<Callout type="warning">
  Never paste tokens into command arguments, source files, or Agent prompts. Use interactive login or pipe the token to `--with-token`.
</Callout>


# Agent API 端点 (https://mosoo.ai/docs/zh-Hans/agent-api-endpoints/)



Agent API Endpoint 是已发布 mosoo Agent 的公开 API 入口。你的应用使用 `agentId` 和 mosoo API token 调用它。

## 必须存在的条件 [#必须存在的条件]

一个有效的 Agent API Endpoint 需要：

* 真实的 Agent ID。
* Agent 状态为 `published`。
* 存在 live API endpoint version。
* API token 所有者拥有该 Agent 所属的 Project。
* Agent owner 与 Project owner 一致。

如果 Agent 未发布，mosoo 返回 `409 agent_not_published`。如果 Agent 没有 live API endpoint version，mosoo 返回 `409 service_inactive`。如果 token owner 不拥有该 Agent 所属的 Project，mosoo 返回 `403 forbidden`。

## `agentId` [#agentid]

从 mosoo 的 Agent API Access 面板获取 `agentId`。v1 中，`agentId` 是不带前缀的 ULID：

```text
01J00000000000000000000001
```

不要添加 `agent_` 前缀。同样的裸 ULID 规则也适用于 `threadId`、`fileId` 和 `runId`。

## API 端点负责什么 [#api-端点负责什么]

Agent API Endpoint 负责 runtime 边界：

| mosoo 负责                                                                          | 你的应用负责                                                                |
| --------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| 已发布 Agent 配置、模型服务商设置、工具执行、sandbox/runtime 行为、Agent memory/runtime state，以及公开事件生成。 | 产品 UI、后端 API、任务、应用侧用户、业务逻辑、存储、`thread.id` 持久化，以及客户端自有 correlation ID。 |

请求不能覆盖模型服务商凭据、工具、runtime settings 或 Agent 配置。需要修改这些内容时，在 mosoo 中修改并重新发布 Agent。

## 第一个 API 调用 [#第一个-api-调用]

在 Agent API Endpoint 上创建 Thread：

```http
POST /api/v1/agents/{agentId}/threads
```

带上 `input` 可以立即排队第一个 Run；省略 `input` 则会创建一个没有 Run 的空 `IDLE` Thread。

<Cards>
  <Card title="认证和访问控制" href="https://mosoo.ai/docs/zh-Hans/auth-and-access/">
    API token 检查和资源可见性。
  </Card>

  <Card title="创建 Thread" href="https://mosoo.ai/docs/zh-Hans/api-reference/create-a-thread-for-an-agent-api-endpoint/">
    完整端点参考。
  </Card>

  <Card title="对话与运行" href="https://mosoo.ai/docs/zh-Hans/threads-and-runs/">
    Thread 和 Run 的生命周期状态。
  </Card>
</Cards>

应用密钥必须属于 Agent 所在的 Project。创建和迁移方式见[认证和访问控制](https://mosoo.ai/docs/zh-Hans/auth-and-access/)。


# 配置 Agent (https://mosoo.ai/docs/zh-Hans/agent-configuration/)





打开 Agent 后，可以在同一个工作区中编辑配置并即时 Preview。

<img alt="Agent editor 将测试区与配置区并列展示。" src="__img0" />

## 身份与类型 [#身份与类型]

* **Name 与 description** 用于 Agent 列表、Thread 和交付界面。
* **Assistant Agent** 在 session 间保留工作环境。
* **Task Agent** 每次 Run 都从干净环境开始。

Agent type 只能在首次发布前修改。

## 运行时与模型 [#运行时与模型]

先选择 runtime，再选择其 Provider key 可用的模型。如果模型列表为空或 runtime 显示 **Needs key**，请在当前 Project 中配置对应 Provider。

## 系统提示词 [#系统提示词]

明确描述 Agent 的角色、边界、回答风格，以及何时应该追问。相比模糊的人设文案，应优先写清可执行规则。发布前同时测试正常与失败路径。

## 技能 [#技能]

从当前 Project 绑定可复用的指令包。新 session 会获得这些 Skills，Agent 在任务需要时读取。若 Skill 缺失，mosoo 会报告问题，而不会从其他 Project 借用。

## MCP 服务器 [#mcp-服务器]

绑定当前 Project 中已授权的 Remote HTTPS MCP 连接。未授权时也可以先绑定，但只有启用且授权完成的连接才能在 Run 中提供工具。

## 环境 [#环境]

选择用于 packages、setup script、variables 和网络策略的 runtime template。Agent 未显式选择时使用 Project default。新 session 会冻结启动时选中的 Environment revision。Task Agent 支持 Full 或 Limited 网络访问；Assistant Agent 必须使用 Full。详见 [Environment 网络策略](https://mosoo.ai/docs/zh-Hans/environments/#%E7%BD%91%E7%BB%9C%E7%AD%96%E7%95%A5)。

## 保存与发布 [#保存与发布]

Draft 改动影响 Preview；发布会创建供未来 session 使用的新 live version。已有 session 不会静默切换配置。


# 认证和访问控制 (https://mosoo.ai/docs/zh-Hans/auth-and-access/)



应用 API 请求使用所属 Project 的 API key：

```http
Authorization: Bearer msp_...
Content-Type: application/json
```

## 创建和保管密钥 [#创建和保管密钥]

打开目标 **Project settings → Project API keys** 创建密钥。密钥只显示一次，服务端只存储哈希；请保存到可信后端，不要放入浏览器或移动客户端代码。

一个 Project 可有多个密钥，每个密钥只属于一个 Project。所有密钥具有相同的 Agent 配置、Session 和文件访问能力，不提供可配置权限范围。Project key 不能管理账号、Project 或其他密钥。模型服务商和 MCP 凭据需要单独配置，不是应用 API key。

## Agent API 端点访问 [#agent-api-端点访问]

Public Thread API 仍要求 Agent 已发布且存在 live API endpoint version。密钥必须有效、未撤销，并属于 Agent 所在的 Project；Project 所有者也必须是 Agent 所有者。即使同一个账号拥有两个 Project，应用密钥也不能跨 Project 访问。

Agent 未发布时返回 `409 agent_not_published`，缺少 live endpoint version 时返回 `409 service_inactive`。根据资源边界，拒绝访问可能返回 `403 forbidden` 或 `404 not_found`。

## 用户身份和执行 [#用户身份和执行]

你的后端负责认证终端用户，并在创建 Thread 时传入必填的不透明 `userId`。mosoo 为 Thread、Run、文件和委托 MCP 调用保留不可变的 `(Project, userId)` 上下文，但不认证终端用户。后端仍需检查用户是否有权访问保存的 Thread ID。

Run 使用已发布的 Agent 配置。Thread API 请求不能覆盖服务商凭据、工具、runtime settings 或 Agent 配置。

## 密钥轮换和迁移 [#密钥轮换和迁移]

在同一 Project 创建替代密钥、更新集成，然后撤销旧密钥。撤销会拒绝旧密钥的新请求，但不会停止已接收的工作或删除 Thread。同一 Project 的其他有效密钥或 Project 所有者可以继续操作已有 Thread。

旧 `mst_` 和 `grt_pat_` token 已被拒绝，不会自动归入默认 Project。请为每个目标 Project 创建新密钥并替换集成配置。CLI 用户需使用当前 CLI 重新登录；浏览器和 CLI 登录提供账号级控制面访问，CLI 登录凭据使用独立的 `mcli_` 前缀。Project key 不能替代账号登录。

## 安全重试 [#安全重试]

重试同一操作和请求体时复用 `Idempotency-Key`。同一 Project 的密钥共享幂等记录和限流范围，因此轮换密钥不会重复创建工作或重置限额。同一 Project 的不同集成应使用不同的操作标识。

同一个 key 和请求返回原始响应。原请求仍在处理，或相同 key 对应不同请求体时，返回 `409 idempotency_conflict`。


# Project、Agent 与运行时 (https://mosoo.ai/docs/zh-Hans/concepts/)



mosoo 是面向 Coding Agent 的开源 Agent runtime。它把 Claude Agent SDK、OpenAI Runtime 和 OpenCode Agent 放进同一个产品模型中运行，并通过持久 Thread、Run、事件、文件和 API 访问，让应用无需自行重建 sandbox、生命周期或模型服务商层。

## Project 是隔离边界 [#project-是隔离边界]

Project 将自己的 Agents、文件、配置资源和用量保持独立。切换 Project 会改变控制台中可见的资源。当前 Alpha 是单所有者模式，暂不提供组织团队角色、邀请或所有权转移。

## Agent 类型决定连续性 [#agent-类型决定连续性]

| 类型                  | Runtime state                                                      | 适合场景                           |
| ------------------- | ------------------------------------------------------------------ | ------------------------------ |
| **Assistant Agent** | 在 session 之间保留稳定工作环境。重建会保留选定 workspace 与 memory，但本地登录或缓存可能丢失。      | 持续助手、copilot，以及受益于连续状态的重复工作。   |
| **Task Agent**      | 按 Thread 隔离状态。成功的 Run 会保存工作目录和服务商续接状态；同一 Thread 的后续 Run 恢复已提交的检查点。 | Review、分流、webhook 和相互隔离的批处理任务。 |

新 Thread 使用隔离状态。Task Run 成功后，必须先提交完整的 Thread 工作目录和服务商续接状态，才能开始下一轮。冷启动会恢复检查点；提交失败会阻止后续轮次，不会静默启动空环境。检查点至少可恢复 20 天，归档不删除，永久删除 Thread 时一并删除。运行中的进程、socket、临时凭据和附件挂载不包含在检查点中。检查点功能上线前的 Thread 可先恢复已记录的产物，直到首次成功提交检查点。

新 Agent 默认为 Assistant Agent。在 draft 阶段可以切换类型；首次发布后类型锁定。之后如需改类型，请 fork 出新的 Agent，原 Agent 不受影响。

## 运行时是 Agent 驱动 [#运行时是-agent-驱动]

Runtime 决定 Agent 如何执行，以及解析哪一种 Provider credential。它与 Agent type 是两个独立维度：

* **Claude Agent SDK** 使用 Anthropic。
* **OpenAI Runtime** 使用 OpenAI 或兼容 Responses API 的 endpoint。
* **OpenCode** 使用自身 runtime 和兼容的 Provider 配置。

## 对话与运行 [#对话与运行]

Thread 是一个 Agent 的持久交互记录。新的任务或恢复回复都可能启动一个 Run。Thread 保存历史并可异步重新打开；Run 是单次执行，具有状态、事件、文件、日志和用量。

## 已发布版本 [#已发布版本]

发布会快照 Agent 配置。新 session 使用当前 live version，已有 session 保持开始时的版本。当前版本历史只读，尚不能完整恢复旧配置或进行并排比较。


# 在 Cloudflare 上部署 mosoo (https://mosoo.ai/docs/zh-Hans/deploy-mosoo/)



mosoo 由两个 Cloudflare Workers 组成：API Worker 使用 D1、R2、Queues、Durable Objects 和 Containers；Web Worker 提供控制台，并通过服务绑定连接 API。

本指南介绍参考部署所采用的两种发布方式：

* **云端部署**：由 GitHub Actions 构建并发布到 Cloudflare。
* **本地工具链部署**：运维人员在本地代码仓库中通过 Wrangler 发布同一套配置。

两种方式共用 `apps/api/wrangler.toml`、`apps/web/wrangler.toml` 和仓库内的部署脚本。Cloudflare 资源只需准备一次，之后任选一种发布方式。

## 前置要求 [#前置要求]

* Cloudflare 账号已开通 Workers、D1、R2、Queues、Durable Objects 和 Containers。
* 一个由 Cloudflare DNS 托管的域名，例如 `console.example.com`。
* 已安装 Git、Docker、[Bun](https://bun.sh/)、[just](https://just.systems/)，并能拉取仓库子模块。
* 一个具备上述账号资源和域名区域部署权限的 Cloudflare API 令牌。令牌和密钥不得提交到 Git，并应按以下操作范围配置最小权限。

| 范围           | 必需操作                                               |
| ------------ | -------------------------------------------------- |
| 账号           | Workers 脚本、版本、部署、自定义域名与 Containers；D1 迁移；R2；Queues |
| 控制台域名所在的域名区域 | 修改 `<控制台域名>/api/*` API 路由使用的 Workers Routes        |
| R2 S3 凭据     | 读写 Agent runtime 备份使用的 sandbox-state 存储桶           |

Cloudflare 控制台中的权限名称可能调整，应核对令牌是否允许这些具体 API 操作，而不是直接授予账号管理员权限。

克隆你的 fork，并安装仓库锁定的依赖：

```bash
git clone --recurse-submodules https://github.com/<owner>/mosoo.git
cd mosoo
bun install --frozen-lockfile
```

## 1. 准备 Cloudflare 资源 [#1-准备-cloudflare-资源]

从本地工作站创建资源时，先登录 Wrangler：

```bash
cd apps/api
../../node_modules/.bin/vp exec wrangler login
../../node_modules/.bin/vp exec wrangler whoami
```

创建生产 D1 数据库，并记录命令返回的数据库 ID：

```bash
../../node_modules/.bin/vp exec wrangler d1 create mosoo-prod
```

创建生产配置引用的 R2 存储桶：

```bash
../../node_modules/.bin/vp exec wrangler r2 bucket create mosoo-file
../../node_modules/.bin/vp exec wrangler r2 bucket create mosoo-sandbox-state
```

创建 API 指令、构建产物和渠道最终投递所需的队列：

```bash
for queue in \
  api-command \
  api-command-dlq \
  environment-artifact-build \
  channel-final-delivery \
  channel-final-delivery-dlq
do
  ../../node_modules/.bin/vp exec wrangler queues create "$queue"
done
```

如果修改了资源名称，请同步修改 `apps/api/wrangler.toml` 中所有对应的生产者、消费者和绑定。

## 2. 配置域名与绑定 [#2-配置域名与绑定]

编辑两个 Wrangler 配置中的 `[env.prod]`。至少完成以下设置：

1. 在 `apps/api/wrangler.toml` 中：
   * 将 `WEB_ORIGIN` 设为公开的 HTTPS 控制台地址；
   * 将 API 路由改为 `<控制台域名>/api/*`，并设置对应的 `zone_name`；
   * 填入 `wrangler d1 create` 返回的 D1 `database_id`；
   * 如果没有采用默认名称，同步更新 D1、R2 和 Queue 名称；
   * 将 `AUTH_EMAIL_FROM` 改为 Cloudflare 域名区域已授权的发件地址。
2. 在 `apps/web/wrangler.toml` 中：
   * 将生产自定义域名改为同一个控制台域名；
   * 保持 `API` 服务绑定指向生产 API Worker 名称。

推荐的路由结构如下：

```text
https://console.example.com/*      -> Web Worker
https://console.example.com/api/*  -> API Worker
```

请分别按照 Cloudflare 各类资源的命名空间选择尚未使用的名称；Workers、D1 数据库、Queues、R2 存储桶和域名的命名与唯一性规则并不相同。不要复制其他部署的数据库 ID、账号 ID、区域 ID 或域名。

## 3. 保存生产密钥 [#3-保存生产密钥]

当前生产配置要求 API Worker 具备以下密钥：

* `BETTER_AUTH_SECRET`
* `RUNTIME_ACTION_TOKEN_SECRET`
* `VAULT_ROOT_SECRET`
* `R2_ACCESS_KEY_ID`
* `R2_SECRET_ACCESS_KEY`
* `CLOUDFLARE_ACCOUNT_ID`
* `GOOGLE_OAUTH_CLIENT_ID`
* `GOOGLE_OAUTH_CLIENT_SECRET`

前三项应分别生成独立的随机值。在 Cloudflare 控制台复制账号 ID 并创建 R2 S3 凭据；为 Google OAuth 客户端配置公开的 mosoo 来源地址，并将回调地址精确设置为 `https://console.example.com/api/auth/callback/google`，其中示例域名应替换为 `WEB_ORIGIN`。

通过 Wrangler 保存每一项，不要把密钥写入 `wrangler.toml` 或提交到仓库的 `.env` 文件：

```bash
cd apps/api
../../node_modules/.bin/vp exec wrangler secret put BETTER_AUTH_SECRET --env prod
# 对上面列出的每一项生产密钥重复执行。
```

如需使用邮件登录，请配置 Cloudflare Email Routing，并授权 `AUTH_EMAIL` 绑定使用的发件地址。PostHog 分析是可选项；不设置项目密钥时，分析功能保持关闭。

## 4A. 通过 GitHub Actions 云端部署 [#4a-通过-github-actions-云端部署]

参考实现使用 `.github/workflows/deploy-try.yml`。工作流会检查仓库、在本地执行 D1 迁移链、读取远程 D1 迁移账本与 Queue 列表、试运行两个 Worker、依次部署 API 与 Web Worker，最后探测公开地址；它不会逐项预检所有 R2、Container 或绑定资源。

在 fork 中部署时：

1. 修改工作流中的仓库限制、Environment 地址、公开健康检查地址和部署相关构建变量。
2. 创建工作流所使用的 GitHub Environment，并限制为仅允许发布分支部署。
3. 在 GitHub Environment 中添加 `CLOUDFLARE_ACCOUNT_ID` 和 `CLOUDFLARE_API_TOKEN`。它们用于 CI 身份验证；上一节保存的运行时密钥仍由 Cloudflare 管理。
4. 禁止对发布分支执行强制推送或删除。
5. 只将经过评审的 `main` 提交推进到发布分支。

参考工作流在推送到 `deploy/try` 时发布：

```bash
git fetch origin
git push origin origin/main:deploy/try
```

持续观察 GitHub Actions，直到仓库检查、试运行、部署和公开验证全部通过。工作流会串行执行发布，因为 D1 迁移、Queue 更新和 Worker 发布并不是一个原子事务。

<Callout type="warning">
  仓库内置工作流默认拒绝从配置之外的仓库发布。fork 必须明确修改该限制，否则 CI 部署任务不会执行。
</Callout>

## 4B. 在本地使用 Wrangler 工具链部署 [#4b-在本地使用-wrangler-工具链部署]

请在干净且经过评审的代码仓库中使用同一套已提交配置。Wrangler 可以通过 `wrangler login` 登录；导出 API 令牌则能让本地命令更接近 CI 环境。

<Callout type="warning">
  不要把 `just check` 当成完整部署预检。API 部署脚本的第一个远程操作就是应用待执行的 D1 迁移，早于构建和产物校验。运行 `just deploy` 前，必须在同一个发布提交上完成下面全部非破坏性检查。
</Callout>

先导出生产凭据，并确认仓库、子模块与构建输入目录均无本地改动：

```bash
export CLOUDFLARE_ACCOUNT_ID="<你的账号 ID>"
export CLOUDFLARE_API_TOKEN="<你的 API 令牌>"

git status --short --branch
test -z "$(git status --porcelain=v1 --untracked-files=all)"
git submodule foreach --recursive \
  'test -z "$(git status --porcelain=v1 --untracked-files=all)"'
test -z "$(git ls-files -v | grep -E '^[a-zS]')"
test -z "$(git ls-files --others --ignored --exclude-standard -- apps/web/src apps/web/public)"

just check
```

在隔离的本地 D1 数据库上执行完整迁移链，再以只读方式检查生产迁移账本和 Queue 列表：

```bash
(
  cd apps/api
  persist_dir="$(mktemp -d)"
  trap 'rm -rf "$persist_dir"' EXIT
  ../../node_modules/.bin/vp exec wrangler d1 migrations apply DB \
    --local --env prod --persist-to "$persist_dir"
)

(
  cd apps/api
  ../../node_modules/.bin/vp exec wrangler d1 migrations list DB --remote --env prod
  ../../node_modules/.bin/vp exec wrangler queues list
)
```

本地迁移链失败时必须停止。如果远程账本显示有待执行迁移，应先检查确切 SQL，只有迁移是增量操作或已经得到明确生产批准时才能继续；同时确认第 1 步创建的五个 Queue 均存在。

构建 Driver 和 Web 产物，并试运行两个 Worker 的上传。以下命令只验证配置与产物，不会发布 Worker，也不会应用远程迁移：

```bash
./node_modules/.bin/vp run --filter agent-driver build

(
  cd apps/api
  ../../node_modules/.bin/vp exec wrangler deploy --env prod --minify --dry-run
)

./node_modules/.bin/vp run --filter @mosoo/web build

(
  cd apps/web
  ../../node_modules/.bin/vp exec wrangler deploy --env prod --dry-run
)

git status --short
```

只有以上检查在同一个干净提交上全部通过后，才能执行真实发布：

```bash
just deploy
```

`just deploy` 会先执行完整仓库检查，再依次部署 API 和 Web Worker。API 部署会应用待执行的远程 D1 迁移、检查数据库结构、确保必要队列存在、构建 Driver 容器并发布 API Worker；随后构建并发布控制台 Web Worker。

排查局部失败后，也可以只重新发布一侧：

```bash
just deploy-api
just deploy-web
```

这两个局部命令会直接发布，不会运行完整检查。必须保留同一个干净的发布提交，并重新执行上面对应的构建与 dry-run 步骤。不要修改已经应用到生产环境的 D1 迁移；每次生产数据库结构变更都应新增迁移文件。

## 5. 验证部署 [#5-验证部署]

替换示例域名后，检查三个公开入口：

```bash
curl --fail --silent --show-error https://console.example.com/ >/dev/null
curl --fail --silent --show-error https://console.example.com/api/health
curl --fail --silent --show-error https://console.example.com/api/graphql \
  -H 'content-type: application/json' \
  --data '{"query":"query { __typename }"}'
```

控制台应通过 HTTPS 正常加载，`/api/health` 应返回 mosoo 服务正常状态，GraphQL 应返回 `Query`。在对外开放前，还应检查两个 Worker 的日志，并确认 D1 迁移和 Queue 消费者均正常。

权威的停止条件、故障恢复和发布验收步骤见 mosoo 源码仓库中的 [`docs/production-deploy-verification.md`](https://github.com/langgenius/mosoo/blob/main/docs/production-deploy-verification.md)。


# 环境 (https://mosoo.ai/docs/zh-Hans/environments/)





Environment 让 Agent session 以一致的 package、setup script 和 variable 启动。

<img alt="Environment editor 用于配置 packages、setup、variables 和网络策略。" src="__img0" />

## 创建 Environment [#创建-environment]

打开 **Config → Environments → Create environment**，然后配置：

* **Name 与 description**：标识可复用 template。
* **Packages**：来自公共 npm 或 PyPI，必须指定精确版本。
* **Setup script**：prepared packages 恢复后执行。
* **Environment variables**：保存后 value 会加密。
* **Network policy**：Full 允许访问互联网，Limited 为 Task Agent 提供基于域名白名单的访问限制。

也可以根据项目依赖文件从终端创建：

```bash
mosoo console environments create-environment
```

## 分配与修订 [#分配与修订]

可以设为 Project default，也可以为特定 Agent 单独选择。新 session 会捕获当时的 Environment revision。后续修改只影响后来创建的 session，in-flight session 不会改变。

## 网络策略 [#网络策略]

* **Full**：保持直接访问互联网的能力。
* **Limited**：关闭直接联网，通过域名白名单过滤出站 HTTP/HTTPS 流量。白名单包含 Environment 配置的允许域名，以及 mosoo 运行时控制和 artifact 存储所需的端点。

Limited 仅支持使用 session 独立沙箱的 **Task Agent**。**Assistant Agent** 在 session 间共享沙箱，必须使用 Full。运行时会在沙箱启动前应用策略，并在该 session 内保持不变；更换策略需要创建新 session。

如果无法执行 Limited 限制，运行时会拒绝启动沙箱，不会回退到无限制访问。禁用 HTTPS 拦截的本地开发环境也会被拒绝。Limited 还会拒绝 `HTTP_PROXY`、`HTTPS_PROXY` 和 `ALL_PROXY` 环境变量，包括小写形式。

<Callout type="warning">
  网络白名单控制访问目标，不会让已允许的 API 或 MCP 工具自动变成只读。访问生产系统时，仍需配置适当的工具权限和只读凭据。
</Callout>

## 软件包行为 [#软件包行为]

npm CLI 通过 `PATH` 暴露，CommonJS package 通过 `NODE_PATH`，PyPI module 通过 `PYTHONPATH`。Node ESM bare import 仍需在项目内安装依赖。OS package、Cargo、RubyGems 和 Go module 不是 Environment package 选项。

Project default 或仍被 Agent 使用的 Environment 会受到删除保护。


# 错误与限制 (https://mosoo.ai/docs/zh-Hans/errors-and-limits/)



所有非 2xx JSON 错误都使用同一个 envelope：

```json
{
  "error": {
    "code": "invalid_request",
    "message": "Request body must be an object."
  }
}
```

按 `error.code` 分支处理，不要按 `error.message`。`message` 面向开发者，不应直接展示给最终用户。

## 错误码 [#错误码]

| HTTP | `error.code`           | 调用方动作                                            |
| ---- | ---------------------- | ------------------------------------------------ |
| 400  | `invalid_request`      | 修正请求形状、字段值、body size 或 unsupported field。不要原样重试。 |
| 400  | `invalid_json`         | 修正序列化或 `Content-Type`。                           |
| 401  | `unauthenticated`      | 检查 `Authorization`；轮换或重新创建 API token。            |
| 403  | `forbidden`            | 检查 API token 是否能访问该 Agent、Thread 或 file。         |
| 404  | `not_found`            | 检查 ID 是否存在且对该 API token 可见。                      |
| 409  | `agent_not_published`  | 发布 Agent 并启用 API access。                         |
| 409  | `service_inactive`     | 在 mosoo 中重新发布或修复 Agent。                          |
| 409  | `readiness_blocked`    | 修复 mosoo 中的 Agent readiness 或配置。                 |
| 409  | `idempotency_conflict` | 如果原请求仍在处理，按 `Retry-After` 等待；如果 body 不同，使用新 key。 |
| 429  | `rate_limited`         | Back off，并在 `Retry-After` 后重试。                   |
| 500  | `internal_error`       | 带 backoff 短暂重试；重复失败时记录故障详情。                      |

## 幂等 [#幂等]

`Idempotency-Key` 支持：

* `POST /agents/{agentId}/threads`
* `POST /threads/{threadId}/events`

规则：

* 使用 Project key 时，幂等 key 按 Project、method 和 route 隔离，并检查请求体冲突。同一 Project 的密钥共享幂等记录和限流范围，轮换后仍然如此。账号 CLI 凭据使用自身的凭据边界。
* 同一个 key 搭配同一个请求会 replay 已存响应。
* 同一个 key 搭配不同请求会返回 `409 idempotency_conflict`。
* 第一个请求仍在处理时复用同一个 key 会返回 `409 idempotency_conflict`。
* key 必须非空，且不超过 128 字符。
* 冲突响应可能包含 `Retry-After`。

## 公开限制 [#公开限制]

| 限制                       | 值           |
| ------------------------ | ----------- |
| Create Thread input text | 32000 字符    |
| `userId`                 | 255 字符      |
| File ID                  | 26 字符       |
| File upload              | 67108864 字节 |
| Event list 默认值           | 100 events  |
| Event list 最大值           | 1000 events |
| Thread list 最大值          | 100 Threads |

<Cards>
  <Card title="API 参考" href="https://mosoo.ai/docs/zh-Hans/api-reference/">
    端点级请求和响应详情。
  </Card>

  <Card title="认证和访问控制" href="https://mosoo.ai/docs/zh-Hans/auth-and-access/">
    API token 和 Agent access 检查。
  </Card>
</Cards>


# 事件与流式传输 (https://mosoo.ai/docs/zh-Hans/events-and-streaming/)



Thread events 是 mosoo API 集成的稳定读取面。它只暴露公开状态。原始 runtime payload、私有 transcript 和内部诊断不属于这个 API。

## 读取快照 [#读取快照]

轮询、任务和后端状态对账使用快照：

```http
GET /api/v1/threads/{threadId}/events?limit=100
```

响应按时间顺序返回 `events`。当因为 limit 达到上限而省略更早的公开事件时，`truncated` 为 true。默认 limit 是 100，最大是 1000。

每个 event 包含：

| 字段           | 含义                                                 |
| ------------ | -------------------------------------------------- |
| `id`         | 稳定事件 ID，裸 ULID。                                    |
| `runId`      | Run 相关事件的 Run ID；否则为 `null`。                       |
| `type`       | 公开事件类型，例如 `agent.message.delta` 或 `run.completed`。 |
| `status`     | `available`、`error` 或 `unsupported`。               |
| `content`    | 公开事件内容，或相关 payload 的引用。                            |
| `occurredAt` | RFC 3339 时间戳。                                      |
| `durationMs` | 适用时的持续时间。                                          |
| `tokens`     | 适用时的 token 数。                                      |

## 流式读取 [#流式读取]

长时间运行的用户体验使用 SSE：

```http
GET /api/v1/threads/{threadId}/events/stream?limit=100
```

Stream 会先发送注释 heartbeat：

```text
: connected
```

每个公开事件按以下格式发送：

```text
event: thread.event
id: 01J00000000000000000000010
data: {"id":"01J00000000000000000000010","runId":"01J0000000000000000000000A","type":"run.started","status":"available","content":"01J0000000000000000000000A","occurredAt":"2026-05-19T00:00:01.000Z","durationMs":null,"tokens":null}
```

Stream 会抑制已通过轮询观察到的重复 event ID。没有新事件时会发送 keepalive 注释。如果 stream 启动后失败，mosoo 会发送 `event: thread.error`，其中包含标准错误 envelope。

## 提交事件 [#提交事件]

向 Thread 发送调用方输入：

```http
POST /api/v1/threads/{threadId}/events
```

支持的提交事件变体：

```json
{
  "events": [
    {
      "type": "user_message",
      "requestId": "ticket-182-message-1",
      "resources": [
        {
          "type": "file",
          "file_id": "01J0000000000000000000000J"
        }
      ],
      "text": "Summarize the attached file."
    },
    {
      "type": "permission_decision",
      "requestId": "tool-request-1",
      "decision": "allow_once"
    },
    {
      "type": "user_interrupt",
      "runId": null
    }
  ]
}
```

提交事件时使用 `Idempotency-Key`，避免网络重试时重复发送相同用户输入。

## 重建输出 [#重建输出]

渲染当前 UI 时，按 `runId` 分组公开事件。对目标 Run 按时间顺序拼接 `agent.message.delta`。Run `completed` 后，如果 Thread 或 send-event 响应中存在 `run.finalOutput.text`，优先使用它。

<Cards>
  <Card title="列出 Thread events" href="https://mosoo.ai/docs/zh-Hans/api-reference/list-thread-events/">
    快照端点参考。
  </Card>

  <Card title="流式读取 Thread events" href="https://mosoo.ai/docs/zh-Hans/api-reference/stream-thread-events/">
    SSE 端点参考。
  </Card>

  <Card title="发送事件" href="https://mosoo.ai/docs/zh-Hans/api-reference/send-user-messages-permission-decisions-or-interrupts-to-a-thread/">
    提交事件 schema。
  </Card>
</Cards>


# 文件 (https://mosoo.ai/docs/zh-Hans/files/)



通过公开 API 上传的文件是作用于 Agent API Endpoint Project 的 draft file resource。创建 Thread 或发送用户消息时挂载它们。Agent 生成的文件是 artifact。只要 API token 调用方可见，它们都会出现在 Thread file list 中。

## 上传流程 [#上传流程]

公开上传使用 `multipart/form-data`，文件大小上限是 67108864 字节。

1. 用 `POST /agents/{agentId}/files` 把文件上传到 Agent。
2. 保存返回的 `file.id`。
3. 创建 Thread 或发送后续用户消息时，通过 `resources` 挂载该文件。

## 上传文件 [#上传文件]

```bash
printf 'Customer asks for an implementation plan.' > brief.txt

curl -X POST "https://cloud.mosoo.ai/api/v1/agents/$MOSOO_AGENT_ID/files" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -F "file=@brief.txt;type=text/plain"
```

响应是 `PublicFileResponse`。保存其中的 `file.id`：

```json
{
  "file": {
    "id": "01J0000000000000000000000J",
    "name": "brief.txt",
    "mimeType": "text/plain",
    "size": 41,
    "createdAt": "2026-05-19T00:02:00.000Z"
  }
}
```

## 在首条消息中使用文件 [#在首条消息中使用文件]

```bash
curl -X POST "https://cloud.mosoo.ai/api/v1/agents/$MOSOO_AGENT_ID/threads" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "customer-123",
    "resources": [
      {
        "type": "file",
        "file_id": "01J0000000000000000000000J"
      }
    ],
    "input": {
      "type": "user.message",
      "content": [
        {
          "type": "text",
          "text": "Summarize the attached file."
        }
      ]
    }
  }'
```

## 在后续消息中使用文件 [#在后续消息中使用文件]

后续用户消息通过 `resources` 发送文件 ID：

```json
{
  "events": [
    {
      "type": "user_message",
      "resources": [
        {
          "type": "file",
          "file_id": "01J0000000000000000000000J"
        }
      ],
      "text": "Summarize the attached file."
    }
  ]
}
```

<Cards>
  <Card title="上传 Agent file" href="https://mosoo.ai/docs/zh-Hans/api-reference/upload-an-agent-file/">
    在创建或继续 Thread 之前上传文件。
  </Card>

  <Card title="读取 file metadata" href="https://mosoo.ai/docs/zh-Hans/api-reference/retrieve-file-metadata/">
    读取已上传或已挂载文件的 metadata。
  </Card>

  <Card title="下载内容" href="https://mosoo.ai/docs/zh-Hans/api-reference/download-thread-file-content/">
    下载已挂载文件或 Agent artifact 的字节内容。
  </Card>

  <Card title="删除 file" href="https://mosoo.ai/docs/zh-Hans/api-reference/delete-a-file/">
    删除 pre-Thread upload 或可见的 Thread file。
  </Card>
</Cards>


# 创建第一个 Agent (https://mosoo.ai/docs/zh-Hans/first-agent/)







本指南从空 Project 开始，最终得到一个已发布的 Agent。

## 1. 打开 Project [#1-打开-project]

登录 [cloud.mosoo.ai](https://cloud.mosoo.ai)。新账号会自动创建 **Default Project**。当你需要独立的资源与用量边界时，可通过 Project switcher 创建或切换 Project。

## 2. 添加模型服务商密钥 [#2-添加模型服务商密钥]

打开 **Config → Providers**。为准备使用的 runtime 添加 key，并按需执行连接测试。配置完成后，页面顶部会显示 runtime 已就绪。

<Callout type="warning">
  Provider 凭据只属于当前 Project。保存后的 key 只显示掩码，导出的 Agent package 也不会包含凭据。
</Callout>

## 3. 创建 Agent [#3-创建-agent]

打开 **Agents → Create agent**，填写名称并选择 runtime。

<img alt="New Agent 对话框提供 Claude Agent SDK、OpenAI Runtime 和 OpenCode。" src="__img0" />

* **Claude Agent SDK** 使用 Anthropic key。
* **OpenAI Runtime** 使用 OpenAI-compatible key，并要求 endpoint 支持相应 Responses API。
* **OpenCode** 可使用支持的 Provider 配置，包括自定义 OpenAI-compatible endpoint。

## 4. 配置行为 [#4-配置行为]

在 **Preview** 中选择 **Assistant Agent** 或 **Task Agent**，再设置模型与 system prompt。只有确有需要时才添加 Skills、MCP servers 或自定义 Environment。

<img alt="Agent Preview 将即时测试与配置编辑器放在同一个界面。" src="__img1" />

## 5. 发布前测试 [#5-发布前测试]

在左侧 Preview 中发送具有代表性的任务。验证回答、工具调用、文件以及失败行为。用 **Logs** 查看执行细节，用 **Cost** 查看模型用量。Assistant Agent 还提供 **Terminal** 和工作环境重置操作。

## 6. 发布 [#6-发布]

打开 **Publish** 并发布当前 draft。首次发布会锁定 Agent type。之后创建的新 session 使用当前已发布版本，已有 session 保持启动时的版本。

发布后选择交付方式：

* **Thread**：在 mosoo 控制台中开始工作。
* **API Access**：取得 Agent ID，通过 Public Thread API 调用。
* **Instruction for LLM**：复制适用于受支持 coding-agent 工作流的指令。

<Cards>
  <Card title="配置 Agent" href="https://mosoo.ai/docs/zh-Hans/agent-configuration/">
    理解所有配置项。
  </Card>

  <Card title="Preview 与调试" href="https://mosoo.ai/docs/zh-Hans/test-and-debug/">
    测试真实任务并定位失败。
  </Card>

  <Card title="发布与 API access" href="https://mosoo.ai/docs/zh-Hans/publish-and-api-access/">
    选择交付方式。
  </Card>
</Cards>


# 导入、导出、Fork 与版本 (https://mosoo.ai/docs/zh-Hans/import-export-versions/)





## 导出 Agent [#导出-agent]

打开 Agent settings 并选择 **Export agent**。mosoo 会下载包含可移植 Agent 设置和已打包 Skills 的 `.agent` package。

## 导入 package [#导入-package]

在 Agents 页面选择 **Import package**，选择 `.agent` 文件并检查需要修复的项目。导入结果是当前 Project 中可编辑的新 draft。

<img alt="Import 会从可移植的 .agent package 创建新 draft。" src="__img0" />

## 复刻 Agent [#复刻-agent]

打开 Agent settings 并选择 **Fork agent**。Fork 会在同一 Project 创建独立 draft，原 Agent 不变。可用于修改已发布 Agent 锁定的 type，或测试另一套配置。

## 不会随 package 携带的内容 [#不会随-package-携带的内容]

`.agent` package 不是 Project backup，也不是运行状态快照，不包含：

* Provider 或 MCP credentials；
* conversations、logs 或 usage history；
* live runtime state 或 working files。

请在目标 Project 重新连接外部服务，并补选缺失的 Environment 或 secret values。

## 版本历史 [#版本历史]

打开 draft 或 live-version badge，按从新到旧查看版本。列表标识 live version，并摘要显示 runtime、model、change 和 publish time。新 session 使用 live version，已有 session 保持启动时版本。

版本历史当前只读，尚不能查看完整历史配置、并排比较、查看发布者身份或 restore。


# mosoo 文档 (https://mosoo.ai/docs/zh-Hans/)



mosoo 提供一个统一工作区，用于配置 AI Agent、用真实任务测试、发布稳定版本、运营 Runs 与文件，并通过 Public Thread API 集成到其他产品。

<Cards>
  <Card title="创建第一个 Agent" href="https://mosoo.ai/docs/zh-Hans/first-agent/">
    配置 Provider，创建、测试并发布 Agent。
  </Card>

  <Card title="产品导览" href="https://mosoo.ai/docs/zh-Hans/product-tour/">
    理解 Projects、Agents、Threads、Runs 和交付方式。
  </Card>

  <Card title="CLI 设置" href="https://mosoo.ai/docs/zh-Hans/cli/overview/">
    安装 CLI、登录并检查 cloud readiness。
  </Card>

  <Card title="API 快速开始" href="https://mosoo.ai/docs/zh-Hans/quickstart/">
    通过 curl 从 backend 调用已发布 Agent。
  </Card>
</Cards>

## 直接答案 [#直接答案]

* **mosoo 是什么？** mosoo 是面向 Coding Agent 的开源 Agent runtime 与 API。它围绕已发布的 Agent 提供托管 Thread、文件、sandbox 执行、工具事件和 API access。
* **应该先读什么？** 先从[创建第一个 Agent](https://mosoo.ai/docs/zh-Hans/first-agent/)开始；当你准备从可信 backend 调用已发布 Agent 时，再阅读 [API 快速开始](https://mosoo.ai/docs/zh-Hans/quickstart/)。
* **Public Thread API 是什么？** 它是与已发布 Agent 交互的 backend API，可创建和恢复 Thread、读取或 stream events，并传输文件。
* **credential 应该放在哪里？** 使用 Agent 所属 Project 的 Project API key（`msp_`），只将它保存在可信服务器或自动化 runner 上；旧账号 token 已被拒绝。浏览器和移动端应调用你的 backend，再由 backend 调用 mosoo。

## 来源与验证 [#来源与验证]

* [GitHub 源码](https://github.com/langgenius/mosoo)展示开源 runtime 与 license。
* [API 参考](https://mosoo.ai/docs/zh-Hans/api-reference/)记录由 OpenAPI contract 生成的 Public Thread API。
* [OpenAPI 3.1](https://cloud.mosoo.ai/api/v1/openapi.json)是可机器读取的 API 来源。
* [llms.txt](https://mosoo.ai/docs/llms.txt) 与 [llms-full.txt](https://mosoo.ai/docs/llms-full.txt)为 AI answer engine 提供简版和完整版文档索引。

## 构建 [#构建]

* 选择 [Project boundary 与 Agent type](https://mosoo.ai/docs/zh-Hans/concepts/)。
* 添加 [Provider credential 和模型](https://mosoo.ai/docs/zh-Hans/providers-and-models/)。
* 配置 Agent 的[身份、runtime、指令、Skills、MCP 与 Environment](https://mosoo.ai/docs/zh-Hans/agent-configuration/)。
* 发布前完成 [Preview 与调试](https://mosoo.ai/docs/zh-Hans/test-and-debug/)。

## 发布与运营 [#发布与运营]

* [发布 Agent 并启用 API access](https://mosoo.ai/docs/zh-Hans/publish-and-api-access/)。
* 查看 [Runs、文件与用量](https://mosoo.ai/docs/zh-Hans/operations/)。
* 通过[导入、导出、fork 与 version history](https://mosoo.ai/docs/zh-Hans/import-export-versions/)复用配置。

## 集成 [#集成]

Public Thread API 用于与已经发布的 Agent 交互，包括创建和恢复 Thread、读取或 stream events，以及传输文件。Agent 的创建和配置仍通过 console 或 CLI 完成。

<Cards>
  <Card title="API 核心概念" href="https://mosoo.ai/docs/zh-Hans/threads-and-runs/">
    理解 Thread 和 Run 生命周期。
  </Card>

  <Card title="API 参考" href="https://mosoo.ai/docs/zh-Hans/api-reference/">
    查看自动生成的 request 与 response schema。
  </Card>

  <Card title="错误与限制" href="https://mosoo.ai/docs/zh-Hans/errors-and-limits/">
    安全重试并处理失败状态。
  </Card>
</Cards>


# 运行、文件与用量 (https://mosoo.ai/docs/zh-Hans/operations/)









## 运行与对话 [#运行与对话]

打开 **Runs** 分发 Agent 并跟踪工作。可按 All、Unread、Pinned 或 Failed 过滤 Thread。通过后续回复可异步重新打开 Thread，其 Runs 会保留状态和 event history。

<img alt="Runs 页面汇总 active 与 completed Agent Threads。" src="__img0" />

浏览器通知可在 Agent 完成时提醒你，是否授权由浏览器控制，可选开启。

## 文件 [#文件]

打开 **Files** 查看 Project files、Thread attachments 和 runtime artifacts。可按 Agent、Thread 或 file role 过滤，再进行搜索和 preview。

<img alt="Files 可按 Project、Agent、Thread、attachment 与 artifact role 查看。" src="__img1" />

删除或修改 Agent 并不会让 `.agent` export 变成文件备份；runtime file 与 conversation history 有各自的生命周期。

## Project 用量 [#project-用量]

打开 **Project Settings → Project usage**。选择 All、Production 或 Debug，再选择 7 天、30 天、当月至今或 90 天。查看 Overview、By Agent 与 By Model，或将当前 tab 导出为 CSV。

<img alt="Project Usage 展示 estimated spend、model calls、token trend、Agents 和 models。" src="__img2" />

<Callout type="info">
  金额来自已记录 model call 与参考价格的估算，不是 Provider invoice 或 mosoo charge。未知模型若没有 reported cost，汇总可能偏低。
</Callout>

当前单所有者产品不提供 budget、alert、invoice、payment control 或 per-user usage。


# 产品导览 (https://mosoo.ai/docs/zh-Hans/product-tour/)



mosoo 是一个用于构建、运行、发布和运营 AI Agent 的托管工作区。你可以先配置 Agent，在控制台中测试，然后通过 Thread 或 API endpoint 使用它。

## 产品模型 [#产品模型]

| 资源               | 负责的范围                                                  |
| ---------------- | ------------------------------------------------------ |
| **Organization** | 账号级容器。当前产品是单所有者体验，暂不提供团队角色和邀请。                         |
| **Project**      | Agent、文件、配置和用量的隔离边界。新账号会获得 Default Project。            |
| **Agent**        | 可复用的工作者，包含类型、runtime、模型、指令、Skills、MCP 连接和 Environment。 |
| **Thread**       | 一个 Agent 的持久对话与工作记录，可以通过后续回复异步恢复。                      |
| **Run**          | Thread 中的一次执行，会产生事件、日志、用量和文件。                          |

## 典型工作流 [#典型工作流]

1. 打开或创建一个 Project。
2. 添加模型 Provider key。
3. 创建 Agent 并选择 runtime。
4. 配置身份、指令、Skills、MCP servers 和 Environment。
5. 在 **Preview** 中测试；需要时检查 **Logs**、**Cost** 和 **Terminal**。
6. 发布 Agent。
7. 在 mosoo 中创建 Thread 或启用 API access。
8. 持续查看 Runs、文件、版本和用量。

<Callout type="info">
  大部分配置属于当前 Project。Provider key、MCP 凭据、Skill 和 Environment 不会自动跨 Project 共享。
</Callout>

<Cards>
  <Card title="创建第一个 Agent" href="https://mosoo.ai/docs/zh-Hans/first-agent/">
    完成控制台中的端到端流程。
  </Card>

  <Card title="Project、Agent 与 runtime" href="https://mosoo.ai/docs/zh-Hans/concepts/">
    选择正确的资源和执行边界。
  </Card>

  <Card title="CLI 设置" href="https://mosoo.ai/docs/zh-Hans/cli/overview/">
    安装 CLI 并连接 mosoo Cloud。
  </Card>
</Cards>


# 模型服务商与模型 (https://mosoo.ai/docs/zh-Hans/providers-and-models/)





Provider credential 保存在当前 Project 中，并在 Agent 启动时解析。

<img alt="Providers 页面同时展示 runtime readiness 和 Project 级凭据。" src="__img0" />

## 添加模型服务商密钥 [#添加模型服务商密钥]

1. 打开 **Config → Providers**。
2. 在内置 Provider 中选择 **Add key**，或选择 **Add custom model**。
3. 按要求填写名称、API key、可选 base URL 和支持的模型名。
4. 选择 **Test** 验证连接，然后保存。
5. 回到 Agent 中选择 runtime 与模型。

Key 可以命名、编辑、测试、设为默认和删除。可选测试失败并不会强制阻止保存。

## 运行时就绪状态 [#运行时就绪状态]

页面顶部的 **Runtime availability** 会说明每个 runtime 将解析哪一种凭据。若当前 Project 没有匹配的 key，setup 或 Run 会以配置错误停止；mosoo 不会借用其他 Project 的凭据。

## 自定义 endpoint [#自定义-endpoint]

OpenCode 可使用自定义 OpenAI-compatible credential。OpenAI Runtime 还要求 endpoint 实现该 runtime 使用的 Responses API。

## 凭据边界 [#凭据边界]

* 保存的 key 会加密，并只显示掩码。
* Raw value 不会写入 Agent settings、logs、diagnostics 或 `.agent` export。
* Provider credential 不会跨 Project 继承。
* 删除 key 可能导致依赖它的 Agent 无法启动，删除前应检查 runtime readiness。


# 发布与 API 访问 (https://mosoo.ai/docs/zh-Hans/publish-and-api-access/)







发布会快照 draft 配置，并开放对应交付入口。

<img alt="Publish 菜单提供 Thread、API Access 和 coding-agent instructions。" src="__img0" />

## 发布 draft [#发布-draft]

1. 完成 Preview 测试。
2. 打开 **Publish** 并发布 draft。
3. 检查 live-version badge 与版本摘要。

首次发布会锁定 Agent type。新 session 使用当前 live version，已经运行的 session 保持原版本。

## 创建 Thread [#创建-thread]

选择 **Thread**，或打开 **Runs → New thread**，选择 Agent，填写任务并 dispatch。之后可通过回复恢复同一 Thread 的异步工作。

<img alt="New Thread 会分配一个 Agent 和一条初始任务。" src="__img1" />

## 启用 API 访问 [#启用-api-访问]

从 Publish 菜单选择 **API Access** 并复制不带前缀的 ULID Agent ID。打开该 Agent 所属的 **Project settings → Project API keys**，创建 Project key（`msp_`）并在显示时保存密钥。其他 Project 的密钥不能调用该 Agent。

Token 只应放在 `Authorization: Bearer` header 中。API access 用于创建和恢复 Thread，不负责创建、编辑或发布 Agent。

<Cards>
  <Card title="API 快速开始" href="https://mosoo.ai/docs/zh-Hans/quickstart/">
    用 curl 创建 Thread。
  </Card>

  <Card title="认证与访问" href="https://mosoo.ai/docs/zh-Hans/auth-and-access/">
    理解 token 与 Agent access。
  </Card>

  <Card title="API 参考" href="https://mosoo.ai/docs/zh-Hans/api-reference/">
    查看全部 Public Thread API operation。
  </Card>
</Cards>


# 快速开始 (https://mosoo.ai/docs/zh-Hans/quickstart/)



创建一个已发布 Agent 的 Thread，发送一条后续消息，读取公开事件日志，并附加一个文件。

## 开始前 [#开始前]

你需要：

* mosoo 中一个已发布并启用 API access 的 Agent。
* Agent API Access 面板中的 `agentId`。
* 一个有权限调用该 Agent 的 mosoo API token。
* 由你的后端完成身份验证的应用用户对应的 opaque `userId`。

```bash
export MOSOO_API_BASE="https://cloud.mosoo.ai/api/v1"
export MOSOO_API_TOKEN="msp_..."
export MOSOO_AGENT_ID="01J00000000000000000000001"
```

<Callout type="info">
  v1 资源 ID 是不带前缀的 ULID，不是 `agent_...` 或 `thread_...` 这类前缀 ID。
</Callout>

## 1. 创建 Thread [#1-创建-thread]

Thread 是已发布 Agent 的 API 对话容器。创建时带上 `input` 会同时排队第一个 Run。

```bash
curl -X POST "$MOSOO_API_BASE/agents/$MOSOO_AGENT_ID/threads" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-create-thread" \
  -d '{
    "userId": "customer-123",
    "input": {
      "type": "user.message",
      "content": [
        {
          "type": "text",
          "text": "Say hello and explain what you can help with."
        }
      ]
    }
  }'
```

从响应中复制 `thread.id`：

```bash
export MOSOO_THREAD_ID="01J00000000000000000000009"
```

## 2. 发送另一条消息 [#2-发送另一条消息]

使用 `thread.id` 继续同一个 Agent 交互。

```bash
curl -X POST "$MOSOO_API_BASE/threads/$MOSOO_THREAD_ID/events" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-send-message-1" \
  -d '{
    "events": [
      {
        "type": "user_message",
        "requestId": "quickstart-message-1",
        "text": "Give me the three most important next steps."
      }
    ]
  }'
```

当当前 Run 正在等待输入或仍在执行时，也可以发送 `permission_decision` 或 `user_interrupt`。

## 3. 读取事件日志 [#3-读取事件日志]

按时间顺序读取公开事件：

```bash
curl "$MOSOO_API_BASE/threads/$MOSOO_THREAD_ID/events?limit=100" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN"
```

事件日志是读取结果的稳定位置。它可能包含用户消息、Agent message delta、thinking delta、工具状态、文件变化、用量更新和 Run 状态。

## 4. 附加文件 [#4-附加文件]

先把文件上传到 Agent：

```bash
printf 'Customer asks for an implementation plan.' > brief.txt

curl -X POST "$MOSOO_API_BASE/agents/$MOSOO_AGENT_ID/files" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -F "file=@brief.txt;type=text/plain"
```

从响应中复制 `file.id`：

```bash
export MOSOO_FILE_ID="01J0000000000000000000000J"
```

在后续用户消息中带上这个文件：

```bash
curl -X POST "$MOSOO_API_BASE/threads/$MOSOO_THREAD_ID/events" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-file-message-1" \
  -d '{
    "events": [
      {
        "type": "user_message",
        "requestId": "quickstart-file-message-1",
        "resources": [
          {
            "type": "file",
            "file_id": "01J0000000000000000000000J"
          }
        ],
        "text": "Summarize the attached file."
      }
    ]
  }'
```

如果要在首条用户消息中带文件，请在第 1 步之前上传文件，并把同一个 `resources` 数组加入 create-Thread 请求。

<Cards>
  <Card title="对话与运行" href="https://mosoo.ai/docs/zh-Hans/threads-and-runs/">
    理解 Thread 和 Run 的生命周期状态。
  </Card>

  <Card title="事件与流式传输" href="https://mosoo.ai/docs/zh-Hans/events-and-streaming/">
    通过快照或 SSE stream 读取 Thread event。
  </Card>

  <Card title="文件" href="https://mosoo.ai/docs/zh-Hans/files/">
    上传文件并挂载到 Thread message。
  </Card>

  <Card title="错误与限制" href="https://mosoo.ai/docs/zh-Hans/errors-and-limits/">
    处理重试、幂等冲突、限流和无效请求。
  </Card>
</Cards>


# 技能与 MCP 服务器 (https://mosoo.ai/docs/zh-Hans/skills-and-mcp/)







Skills 和 MCP servers 都是 Project-owned 资源，可绑定到选定的 Agents。

## 技能 [#技能]

Skill 将可信指令与配套文件打包，避免把同一内容手工复制到每个 prompt。

1. 打开 **Config → Skills → Add skill**。
2. 上传 `.md`、`.zip`、`.skill` 文件，上传根目录包含 `SKILL.md` 的文件夹，或从 GitHub、skills.sh 导入。
3. 检查识别出的名称、描述和作者。
4. 打开 Agent 并选择 **Add skill**。

<img alt="Skill 可以从文件或文件夹上传，也可以从 URL 导入。" src="__img0" />

当前控制台支持下载、fork 和 uninstall Skill，但没有站内编辑或更新操作。Fork 是独立副本。卸载后，已有 Agent attachment 可能显示为 **Missing**。

## MCP 服务器 [#mcp-服务器]

1. 打开 **Config → MCP servers → Add MCP**。
2. 填写名称和 Remote HTTPS URL。
3. 选择 OAuth 或 bearer-token authorization 并保存。
4. 完成授权，然后在 Agent editor 中绑定连接。
5. 在 Preview 或新 Thread 中要求 Agent 使用该工具进行测试。

<img alt="MCP 连接通过 OAuth 或 bearer token 访问 Remote HTTPS server。" src="__img1" />

<Callout type="warning">
  **Connected** 只表示 mosoo 已保存有效凭据，不代表远端 server 及其所有工具一定可用。目前错误会在 Agent 首次调用时暴露。
</Callout>

MCP credential 会加密，保存后不再显示。当前不支持 local-process MCP、跨 Project 共享、connector marketplace 或按 tool 选择。


# 预览与调试 (https://mosoo.ai/docs/zh-Hans/test-and-debug/)



使用 Agent workspace 在发布前测试 draft 配置。

## 预览 [#预览]

在左侧输入具有代表性的任务，至少测试：

* 正常请求和预期输出；
* 每个已绑定 Skill 或 MCP server 的调用；
* 文件输入和生成 artifacts；
* 信息不足时的追问行为；
* tool、credential 或 Environment 的失败路径。

Draft 变更会立即作用于 Preview。绿色 **Ready** 表示 editor 可以接收任务，并不代表所有外部依赖都工作正常。

## 日志 [#日志]

打开 **Logs** 检查 session 与执行历史，用于关联 runtime startup、tool use 和 failure。日志不应包含 secret；如果用户输入中带有 raw credential，请在分享 diagnostics 前移除。

## 成本 [#成本]

打开 **Cost** 查看 Agent 级用量估算、model mix 和最近 usage event。Production 与 Debug 可分开过滤。Cost 是模型调用估算，不是 Provider invoice。

## 终端与重置 [#终端与重置]

Assistant Agent 因为可跨 session 保留环境，所以提供 Terminal 和工作状态控制。只有在确实需要干净状态时才 reset；它可能移除本地 workspace 状态、cache 或 sign-in。Task Agent 每次 Run 都从干净环境开始，不提供相同的持久控制。

## 常见问题定位 [#常见问题定位]

1. **Runtime needs a key**：在当前 Project 配置匹配的 Provider。
2. **Model unavailable**：检查 Provider model list 与 endpoint compatibility。
3. **MCP tool failed**：确认连接已启用并授权，再直接测试工具任务。
4. **Environment startup failed**：检查精确 package version、setup script 和必需 variables。
5. **旧 session 行为不同**：创建新 session 以使用当前 published version。


# 对话与运行 (https://mosoo.ai/docs/zh-Hans/threads-and-runs/)



mosoo 通过 Thread API 暴露已发布 Agent。你的应用创建或复用 Thread，然后发送用户事件排队 Run。mosoo 在已发布 Agent 配置内执行每个 Run，并把公开事件写回 Thread。

## 资源模型 [#资源模型]

| 概念                 | 含义                                                         |
| ------------------ | ---------------------------------------------------------- |
| Agent API Endpoint | Agent API Access 面板中的已发布 Agent 入口。v1 的 `agentId` 是裸 ULID。  |
| Thread             | 通过 API 创建的对话容器。你的应用需要保存 `thread.id`。                       |
| Run                | Agent 在 Thread 上的一次执行。create-thread input 或用户消息可以排队一个 Run。 |
| Event              | 输入、Agent 输出、工具状态、文件、用量和 Run 生命周期变化的公开时间线。                  |

v1 资源 ID 是裸 ULID。不要添加 `agent_`、`thread_`、`file_` 或 `run_` 前缀。

## 创建和读取 [#创建和读取]

为已发布 Agent 创建 Thread：

```http
POST /api/v1/agents/{agentId}/threads
```

如果提供 `input`，mosoo 会排队初始 Run。如果省略 `input`，mosoo 会创建一个没有 Run 的空 `IDLE` Thread。

读取当前 Thread 状态：

```http
GET /api/v1/threads/{threadId}
```

响应会包含 `thread`、存在时的最新 `run`，以及便捷 `links`。

## 对话状态 [#对话状态]

| Status         | 含义                    |
| -------------- | --------------------- |
| `IDLE`         | 没有活跃 Run。用户消息可以排队新工作。 |
| `RUNNING`      | Run 正在执行。             |
| `RESCHEDULING` | Thread 处于两个 Run 之间。   |
| `TERMINATED`   | Thread 已结束。           |

## 运行状态 [#运行状态]

| Status          | 含义                                 |
| --------------- | ---------------------------------- |
| `queued`        | Run 已存在，但尚未开始。                     |
| `booting`       | Runtime 正在准备。                      |
| `running`       | Run 正在执行。                          |
| `waiting_input` | Run 正在等待调用方输入，常见于权限决策。             |
| `completed`     | 终态成功。存在时 `finalOutput.text` 是稳定结果。 |
| `failed`        | 终态失败。查看 `run.error`。               |
| `cancelled`     | 终态取消。                              |
| `expired`       | 终态超时或过期。                           |

## 生命周期操作 [#生命周期操作]

用生命周期端点管理应用侧 Thread 列表：

| 操作                   | Endpoint                                    |
| -------------------- | ------------------------------------------- |
| 列出某个 Agent 的 Threads | `GET /api/v1/agents/{agentId}/threads`      |
| Archive Thread       | `POST /api/v1/threads/{threadId}/archive`   |
| Unarchive Thread     | `POST /api/v1/threads/{threadId}/unarchive` |
| Delete Thread        | `DELETE /api/v1/threads/{threadId}`         |

Archive 会让 Thread 从默认 active list 中隐藏。Delete 会永久删除 Thread 及其底层 AgentSession。

<Cards>
  <Card title="创建 Thread" href="https://mosoo.ai/docs/zh-Hans/api-reference/create-a-thread-for-an-agent-api-endpoint/">
    完整请求和响应 schema。
  </Card>

  <Card title="发送事件" href="https://mosoo.ai/docs/zh-Hans/api-reference/send-user-messages-permission-decisions-or-interrupts-to-a-thread/">
    排队 Run、回答权限请求或中断执行。
  </Card>

  <Card title="列出 Thread events" href="https://mosoo.ai/docs/zh-Hans/api-reference/list-thread-events/">
    读取公开事件以渲染输出和状态。
  </Card>
</Cards>


# 常见 Agent 模式 (https://mosoo.ai/docs/zh-Hans/use-cases/)



以下模式可作为起点，仍需用你的真实数据和失败场景完成测试。

## 持续研究助手 [#持续研究助手]

* \*\*Type：\*\*Assistant Agent
* \*\*原因：\*\*重复研究工作可受益于持续 workspace。
* \*\*配置：\*\*强调引用的 prompt、研究 Skills、可选 Remote HTTPS MCP source，以及包含分析 package 的 Environment。
* \*\*交付：\*\*用 mosoo Thread 进行交互工作；通过 API access 嵌入其他产品。

## Pull Request 审查助手 [#pull-request-审查助手]

* \*\*Type：\*\*Task Agent
* \*\*原因：\*\*每次 review 都应从干净临时状态开始。
* \*\*配置：\*\*repository-review Skill、GitHub MCP、严格输出格式和最小 Environment。
* \*\*交付：\*\*每次 review 一个 Thread，或由外部系统调用 Public Thread API。

## Ticket 分流工作者 [#ticket-分流工作者]

* \*\*Type：\*\*Task Agent
* \*\*原因：\*\*ticket 是互相独立的任务，不应泄漏临时状态。
* \*\*配置：\*\*Skill 中的分流规则、issue-tracker MCP，以及明确的 label 与 escalation 条件。
* \*\*运营：\*\*过滤失败 Thread、检查 Logs，并将 production usage 与 Preview 分开查看。

## 团队 Copilot [#团队-copilot]

* \*\*Type：\*\*Assistant Agent
* \*\*原因：\*\*稳定 working directory 能帮助长期 copilot。
* \*\*配置：\*\*产品与运营 Skills，以及已授权 MCP connections。
* \*\*边界：\*\*mosoo 当前控制台是单所有者模式，不支持团队角色和共享管理。应通过适当外部界面交付 Agent，而不是共享 owner credential。

## 公共应用 [#公共应用]

先发布 Agent，再由你的 backend 通过 Public Thread API 为每位应用用户创建或恢复 Thread。


# 归档 Thread (https://mosoo.ai/docs/zh-Hans/api-reference/archive-a-thread/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 为 Agent API Endpoint 创建 Thread (https://mosoo.ai/docs/zh-Hans/api-reference/create-a-thread-for-an-agent-api-endpoint/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 删除 file (https://mosoo.ai/docs/zh-Hans/api-reference/delete-a-file/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 删除 Thread (https://mosoo.ai/docs/zh-Hans/api-reference/delete-a-thread/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 下载 Thread 文件内容 (https://mosoo.ai/docs/zh-Hans/api-reference/download-thread-file-content/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# API 参考 (https://mosoo.ai/docs/zh-Hans/api-reference/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}

## 对话 [#对话]

<Cards>
  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/create-a-thread-for-an-agent-api-endpoint/" title="为 Agent API Endpoint 创建 Thread" />

  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/list-threads-for-an-agent-api-endpoint/" title="列出 Agent API Endpoint 的 Thread" />

  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/retrieve-thread-summary/" title="读取 Thread 摘要" />

  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/archive-a-thread/" title="归档 Thread" />

  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/unarchive-a-thread/" title="取消归档 Thread" />

  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/delete-a-thread/" title="删除 Thread" />
</Cards>

## 事件 [#事件]

<Cards>
  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/send-user-messages-permission-decisions-or-interrupts-to-a-thread/" title="向 Thread 发送用户消息、权限决策或中断" />

  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/list-thread-events/" title="列出 Thread 事件" />

  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/stream-thread-events/" title="流式读取 Thread 事件" />
</Cards>

## 文件 [#文件]

<Cards>
  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/upload-an-agent-file/" title="上传 Agent file" />

  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/retrieve-file-metadata/" title="读取 file metadata" />

  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/list-thread-files/" title="列出 Thread 文件" />

  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/download-thread-file-content/" title="下载 Thread 文件内容" />

  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/delete-a-file/" title="删除 file" />

  <Card href="https://mosoo.ai/docs/zh-Hans/api-reference/remove-a-thread-file/" title="移除 Thread 文件" />
</Cards>


# 列出 Thread 事件 (https://mosoo.ai/docs/zh-Hans/api-reference/list-thread-events/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 列出 Thread 文件 (https://mosoo.ai/docs/zh-Hans/api-reference/list-thread-files/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 列出 Agent API Endpoint 的 Thread (https://mosoo.ai/docs/zh-Hans/api-reference/list-threads-for-an-agent-api-endpoint/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 移除 Thread 文件 (https://mosoo.ai/docs/zh-Hans/api-reference/remove-a-thread-file/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 读取 file metadata (https://mosoo.ai/docs/zh-Hans/api-reference/retrieve-file-metadata/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 读取 Thread 摘要 (https://mosoo.ai/docs/zh-Hans/api-reference/retrieve-thread-summary/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 向 Thread 发送用户消息、权限决策或中断 (https://mosoo.ai/docs/zh-Hans/api-reference/send-user-messages-permission-decisions-or-interrupts-to-a-thread/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 流式读取 Thread 事件 (https://mosoo.ai/docs/zh-Hans/api-reference/stream-thread-events/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 取消归档 Thread (https://mosoo.ai/docs/zh-Hans/api-reference/unarchive-a-thread/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 上传 Agent file (https://mosoo.ai/docs/zh-Hans/api-reference/upload-an-agent-file/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# 命令行工具 (https://mosoo.ai/docs/zh-Hans/cli/overview/)



`mosoo` CLI 提供 Public Thread API、Console GraphQL、console REST，以及 machine-readable command catalog。

## 安装 [#安装]

```bash
curl -fsSL https://install.mosoo.ai/install.sh | bash
```

Installer 会把 CLI 安装到 `~/.local/bin`，安装 `@mosoo` coding-agent Skill，登录 [cloud.mosoo.ai](https://cloud.mosoo.ai)，并运行 `doctor`。如需先检查计划且不修改系统：

```bash
curl -fsSL https://install.mosoo.ai/install.sh | bash -s -- --dry-run
```

## 认证与验证 [#认证与验证]

使用浏览器交互登录：

```bash
mosoo auth login --hostname cloud.mosoo.ai
mosoo auth status --hostname cloud.mosoo.ai
mosoo doctor --json
```

Project key（`msp_`）不能授权账号管理。账号级 Console 操作应使用浏览器登录；密钥迁移后请重新登录，用 `mcli_` 凭据替换旧凭据。详见[认证和访问控制](https://mosoo.ai/docs/zh-Hans/auth-and-access/)。

非交互登录应通过标准输入传 token，避免写入 shell history：

```bash
printf '%s' "$MOSOO_API_TOKEN" | \
  mosoo auth login --hostname cloud.mosoo.ai --with-token
```

## 发现命令 [#发现命令]

```bash
mosoo --help
mosoo commands --json
mosoo commands show console environments create-environment
mosoo search "create environment"
```

`commands --json` 面向工具与 coding Agent；`commands show` 返回单个 generated command 的精确 schema。

## 常用操作 [#常用操作]

```bash
mosoo ls -o json
mosoo run --help
mosoo console environments create-environment --help
```

CLI 命令由契约生成。先更新 CLI 并检查命令帮助；旧版显示的 `--input-app-id` 不适用于当前 Project 契约。运行示例请参阅 [API quickstart](https://mosoo.ai/docs/zh-Hans/quickstart/)。

通过 `--target local|cloud|custom`、`--base-url` 或 `--hostname` 控制 endpoint resolution。输出格式包括 `table`、`json`、`yaml` 和 `raw`。

<Callout type="warning">
  不要把 token 放进 command argument、source file 或 Agent prompt。请使用交互登录，或通过标准输入传给 `--with-token`。
</Callout>


# Agent API Endpoint (https://mosoo.ai/docs/ja/agent-api-endpoints/)



Agent API Endpoint は、公開済み mosoo Agent の public API entry point です。application は `agentId` と mosoo API token を使って呼び出します。

## 必要なもの [#必要なもの]

有効な Agent API Endpoint には次が必要です。

* 実在する Agent ID。
* Agent status が `published`。
* live API endpoint version。
* API token owner が所有する Project。
* Agent owner と Project owner が一致していること。

Agent が公開されていない場合、mosoo は `409 agent_not_published` を返します。live API endpoint version がない場合は `409 service_inactive`、token owner が Agent の Project を所有していない場合は `403 forbidden` を返します。

## `agentId` [#agentid]

`agentId` は mosoo の Agent API Access panel で取得します。v1 の `agentId` は prefix のない ULID です。

```text
01J00000000000000000000001
```

`agent_` prefix を付けないでください。`threadId`、`fileId`、`runId` にも同じ bare-ULID rule が適用されます。

## Endpoint が所有するもの [#endpoint-が所有するもの]

Agent API Endpoint は runtime boundary を所有します。

| mosoo が所有                                                                                                                      | application が所有                                                                                                      |
| ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |
| 公開済み Agent 設定、model provider setup、tool execution、sandbox/runtime behavior、Agent memory/runtime state、public event generation。 | Product UI、backend API、job、app-side user、business logic、storage、`thread.id` persistence、client-owned correlation ID。 |

request から model provider credential、tool、runtime setting、Agent configuration を上書きすることはできません。mosoo で変更し、Agent を再度公開してください。

## 最初の API call [#最初の-api-call]

Agent API Endpoint に Thread を作成します。

```http
POST /api/v1/agents/{agentId}/threads
```

`input` を指定すると最初の Run をすぐに queue に追加します。省略すると空の `IDLE` Thread を作成します。

<Cards>
  <Card title="認証とアクセス" href="https://mosoo.ai/docs/ja/auth-and-access/">
    API token check と resource visibility を確認します。
  </Card>

  <Card title="Thread を作成" href="https://mosoo.ai/docs/ja/api-reference/create-a-thread-for-an-agent-api-endpoint/">
    endpoint の完全なリファレンスです。
  </Card>

  <Card title="Thread と Run" href="https://mosoo.ai/docs/ja/threads-and-runs/">
    Thread と Run の lifecycle state を理解します。
  </Card>
</Cards>

アプリケーションキーは Agent と同じ Project に属する必要があります。作成と移行は[認証とアクセス](https://mosoo.ai/docs/ja/auth-and-access/)を参照してください。


# Agent を設定 (https://mosoo.ai/docs/ja/agent-configuration/)





Agent を開くと、ライブ Preview pane と並べて設定できます。

<img alt="Agent editor ではテストと設定を一つの workspace で行えます。" src="__img0" />

## 識別情報とタイプ [#識別情報とタイプ]

* **Name and description** はリスト、Thread、提供先で Agent を識別します。
* **Assistant Agent** は session 間で作業 Environment を維持します。
* **Task Agent** は Run ごとにクリーンな Environment で開始します。

タイプを変更できるのは最初の公開前だけです。

## Runtime とモデル [#runtime-とモデル]

最初に runtime を選択し、解決された Provider key で利用可能なモデルを選びます。モデル一覧が空の場合や runtime に **Needs key** と表示される場合は、現在の Project で対応する Provider を設定してください。

## System prompt [#system-prompt]

Agent の役割、境界、回答スタイル、確認が必要な条件を記述します。曖昧な personality の説明より、明示的な運用ルールを優先してください。公開前に正常系と失敗系の両方をテストします。

## Skill [#skill]

現在の Project にある再利用可能な指示 package を添付します。Skill は新しい session に読み込まれ、タスクで必要なときに Agent が参照します。添付した Skill が見つからない場合、別の Project から流用されず missing として報告されます。

## MCP server [#mcp-server]

現在の Project にある認証済み Remote HTTPS MCP connection を添付します。connection は認証前でも添付できますが、tool を使用できるのは有効化と認証が完了した後だけです。

## Environment [#environment]

package、setup script、変数、network policy をまとめた再利用可能な runtime template を選びます。Agent に明示的な Environment がない場合は Project default が適用されます。新しい session は選択した Environment revision を固定して使用します。Task Agent は Full または Limited のネットワークアクセスを利用でき、Assistant Agent には Full が必要です。詳しくは [Environment のネットワークポリシー](https://mosoo.ai/docs/ja/environments/#%E3%83%8D%E3%83%83%E3%83%88%E3%83%AF%E3%83%BC%E3%82%AF%E3%83%9D%E3%83%AA%E3%82%B7%E3%83%BC)を参照してください。

## 保存と公開の動作 [#保存と公開の動作]

draft の編集は Preview に反映されます。公開すると、以後の session 向けに新しい live version が作成されます。既存 session の設定が暗黙に切り替わることはありません。


# 認証とアクセス (https://mosoo.ai/docs/ja/auth-and-access/)



アプリケーションの API request には Project API key を使用します。

```http
Authorization: Bearer msp_...
Content-Type: application/json
```

## キーの作成と保管 [#キーの作成と保管]

対象の **Project settings → Project API keys** でキーを作成します。秘密値は一度だけ表示され、サーバーにはハッシュのみ保存されます。信頼できる backend に保管し、ブラウザーやモバイルのクライアントコードには含めないでください。

一つの Project に複数のキーを作成できます。各キーは一つの Project にのみ属し、同じ Agent 設定、Session、ファイルのアクセス権を持ちます。キーごとの scope 設定はありません。Project key では account、Project、他のキーを管理できません。Provider と MCP の credential は別途設定します。

## Agent API Endpoint へのアクセス [#agent-api-endpoint-へのアクセス]

Public Thread API では引き続き公開済み Agent と live API endpoint version が必要です。キーが有効かつ未失効で、Agent と同じ Project に属する必要があります。Project owner と Agent owner も一致する必要があります。同じ account が複数の Project を所有していても、アプリケーションキーは Project を越えてアクセスできません。

未公開の Agent は `409 agent_not_published`、live endpoint version がない場合は `409 service_inactive` を返します。アクセス拒否は resource の境界に応じて `403 forbidden` または `404 not_found` になります。

## ユーザーの識別と実行 [#ユーザーの識別と実行]

backend がエンドユーザーを認証し、Thread 作成時に必須の opaque `userId` を渡します。mosoo は Thread、Run、ファイル、委任 MCP 呼び出しに不変の `(Project, userId)` context を保持しますが、エンドユーザーの認証は行いません。保存した Thread ID へのアクセス認可も backend の責任です。

Run は公開済み Agent 設定を使用します。Thread API request で provider credential、tool、runtime settings、Agent 設定を上書きすることはできません。

## キーの更新と移行 [#キーの更新と移行]

同じ Project で新しいキーを作成し、連携設定を更新してから古いキーを失効させます。失効後の新規 request は拒否されますが、受理済みの処理は停止せず、Thread も削除されません。同じ Project の別の有効なキー、または Project owner が既存の Thread を操作できます。

旧 `mst_` と `grt_pat_` token は拒否され、default Project に自動で割り当てられることはありません。対象 Project ごとにキーを作成し、連携先の credential を更新してください。CLI ユーザーは現在の CLI で再ログインが必要です。ブラウザーと CLI のログインは account control plane へのアクセスを提供し、CLI credential は別の `mcli_` prefix を使用します。Project key は account ログインの代わりにはなりません。

## 安全な再試行 [#安全な再試行]

同じ操作と request body の再試行には同じ `Idempotency-Key` を使用します。Project のキーは冪等性記録と rate limit を共有するため、キーを更新しても処理は重複せず、制限もリセットされません。同じ Project の異なる連携には別の操作 ID を使用してください。

同じ key と request では元の response が返ります。処理中、または異なる body に同じ key を使用すると `409 idempotency_conflict` が返ります。


# Project、Agent、runtime (https://mosoo.ai/docs/ja/concepts/)



mosoo は Coding Agent 向けのオープンソース Agent runtime です。Claude Agent SDK、OpenAI Runtime、OpenCode Agent を一つのプロダクトモデルで実行し、永続的な Thread、Run、event、file、API access を提供することで、アプリ側が sandbox、lifecycle、provider layer を作り直さずに済むようにします。

## Project は分離の境界 [#project-は分離の境界]

Project は Agent、ファイル、設定リソース、使用量を分離します。Project を切り替えると console に表示されるリソースも変わります。現在の Alpha は単一オーナー向けであり、Organization のチームロール、招待、所有権移管は利用できません。

## Agent タイプは継続性を決める [#agent-タイプは継続性を決める]

| タイプ                 | Runtime state                                                                                             | 適した用途                                |
| ------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| **Assistant Agent** | session 間で安定した作業 Environment を維持します。再構築時に選択した workspace と memory は保持されますが、ローカルのサインインや cache が失われる場合があります。 | 継続性が役立つアシスタント、copilot、反復作業。          |
| **Task Agent**      | Thread ごとに state を分離します。成功した Run の作業ディレクトリと provider resume state を保存し、同じ Thread の後続 Run で復元します。          | レビュー、triage、webhook、独立した batch task。 |

新しい Thread は分離された state で開始します。Task Run の成功後、Thread の作業ディレクトリ全体と provider resume state の保存が完了してから次のターンを開始します。cold continuation は checkpoint を復元し、保存失敗時は空の環境で続けず後続ターンを拒否します。checkpoint は少なくとも 20 日間復元可能で、archive 後も保持され、Thread の完全削除時に削除されます。実行中の process、socket、一時 credential、添付ファイルの mount は含みません。導入前の Thread は最初の checkpoint 保存成功まで記録済み artifact を復元できます。

新しい Agent は Assistant Agent として作成されます。draft の間はタイプを変更できますが、最初の公開時に固定されます。元の Agent を変えずにタイプを変更するには fork します。

## Runtime は Agent driver [#runtime-は-agent-driver]

runtime は Agent の実行方法と解決する Provider credential を決めます。runtime の選択は Agent タイプとは独立しています。

* **Claude Agent SDK** は Anthropic を使用します。
* **OpenAI Runtime** は OpenAI または互換性のある Responses API endpoint を使用します。
* **OpenCode** は独自 runtime と互換性のある Provider 設定をサポートします。

## Thread と Run [#thread-と-run]

Thread は一つの Agent に対する永続的な対話記録です。新しいタスクや再開時の返信によって Run が開始されます。Thread は履歴を保持し、非同期に再度開くことができます。Run は status、イベント、ファイル、ログ、使用量を持つ一回の実行です。

## 公開バージョン [#公開バージョン]

公開すると Agent 設定の snapshot が作成されます。新しい session は現在の live version を使用し、既存 session は開始時のバージョンを使い続けます。現在、version history は読み取り専用であり、過去設定の完全な復元や並列比較は利用できません。


# Cloudflare に mosoo をデプロイ (https://mosoo.ai/docs/ja/deploy-mosoo/)



mosoo は二つの Cloudflare Worker として動作します。一つは D1、R2、Queues、Durable Objects、Containers を使用する API Worker、もう一つは console を配信し API service に binding する Web Worker です。

このガイドでは、reference deployment で使用する二つの方法を説明します。

* **Cloud deployment** — GitHub Actions で build して Cloudflare に公開します。
* **Local toolchain deployment** — operator が local checkout から Wrangler で同じ設定を公開します。

どちらも `apps/api/wrangler.toml`、`apps/web/wrangler.toml`、repository の deployment script を使用します。Cloudflare resource を一度準備してから、いずれかの release path を選択してください。

## 前提条件 [#前提条件]

* Workers、D1、R2、Queues、Durable Objects、Containers が利用可能な Cloudflare account。
* Cloudflare DNS にある `console.example.com` などの domain。
* Git、Docker、[Bun](https://bun.sh/)、[just](https://just.systems/)、repository submodule。
* 上記 resource のデプロイに必要な account と zone permission を持つ Cloudflare API token。token と secret value は Git の外に保管し、以下の操作に必要な最小権限を使用してください。

| Scope                     | 必要な操作                                                                              |
| ------------------------- | ---------------------------------------------------------------------------------- |
| Account                   | Workers script、version、deployment、custom domain、Containers、D1 migration、R2、Queues。 |
| Console domain を所有する Zone | `<console-domain>/api/*` API route に対する Workers Routes の変更。                        |
| R2 S3 credential          | Agent runtime backup が使用する sandbox-state bucket の読み書き。                             |

Cloudflare の token label は変わることがあるため、account 全体の administrator 権限を付与するのではなく、上記の API operation が許可されていることを確認してください。

fork を clone し、固定された dependency を install します。

```bash
git clone --recurse-submodules https://github.com/<owner>/mosoo.git
cd mosoo
bun install --frozen-lockfile
```

## 1. Cloudflare resource を準備する [#1-cloudflare-resource-を準備する]

workstation から provisioning する場合は Wrangler で認証します。

```bash
cd apps/api
../../node_modules/.bin/vp exec wrangler login
../../node_modules/.bin/vp exec wrangler whoami
```

production D1 database を一つ作成し、返された database ID をコピーします。

```bash
../../node_modules/.bin/vp exec wrangler d1 create mosoo-prod
```

production 設定で参照する R2 bucket を作成します。

```bash
../../node_modules/.bin/vp exec wrangler r2 bucket create mosoo-file
../../node_modules/.bin/vp exec wrangler r2 bucket create mosoo-sandbox-state
```

API command、artifact build、最終 channel delivery に使用する queue を作成します。

```bash
for queue in \
  api-command \
  api-command-dlq \
  environment-artifact-build \
  channel-final-delivery \
  channel-final-delivery-dlq
do
  ../../node_modules/.bin/vp exec wrangler queues create "$queue"
done
```

resource 名を変更した場合は、`apps/api/wrangler.toml` にある対応するすべての producer、consumer、binding を更新します。

## 2. Domain と binding を設定する [#2-domain-と-binding-を設定する]

両方の Wrangler file にある `[env.prod]` section を編集します。最低限、次を設定してください。

1. `apps/api/wrangler.toml`:
   * `WEB_ORIGIN` を公開 HTTPS console URL に設定。
   * API route を `<console-domain>/api/*` に設定し、その `zone_name` を指定。
   * `wrangler d1 create` が返した D1 `database_id` を設定。
   * default を使用しなかった場合は D1、R2、Queue 名を更新。
   * `AUTH_EMAIL_FROM` を Cloudflare zone で認証済みの sender に更新。
2. `apps/web/wrangler.toml`:
   * production custom domain を同じ console domain に設定。
   * `API` service binding は production API Worker 名を参照したままにする。

例えば routing は次の形になります。

```text
https://console.example.com/*      -> Web Worker
https://console.example.com/api/*  -> API Worker
```

Cloudflare の各 resource namespace で未使用の名前を選びます。Workers、D1 database、Queue、R2 bucket、hostname にはそれぞれ異なる命名規則と一意性の要件があります。別の deployment の database ID、account ID、zone ID、hostname をコピーしないでください。

## 3. Production secret を保存する [#3-production-secret-を保存する]

現在の production 設定では、API Worker に次の secret が必要です。

* `BETTER_AUTH_SECRET`
* `RUNTIME_ACTION_TOKEN_SECRET`
* `VAULT_ROOT_SECRET`
* `R2_ACCESS_KEY_ID`
* `R2_SECRET_ACCESS_KEY`
* `CLOUDFLARE_ACCOUNT_ID`
* `GOOGLE_OAUTH_CLIENT_ID`
* `GOOGLE_OAUTH_CLIENT_SECRET`

最初の三つにはそれぞれ独立した random value を生成します。Cloudflare dashboard で account ID を確認し、R2 S3 credential を作成します。Google OAuth client には公開 mosoo origin と正確な callback URL `https://console.example.com/api/auth/callback/google` を設定し、example domain は `WEB_ORIGIN` に置き換えてください。

各 value は Wrangler で保存し、`wrangler.toml` や commit 対象の `.env` file には追加しないでください。

```bash
cd apps/api
../../node_modules/.bin/vp exec wrangler secret put BETTER_AUTH_SECRET --env prod
# 上記の必須 secret ごとに繰り返します。
```

email login を使用する場合は Cloudflare Email Routing を設定し、`AUTH_EMAIL` binding が使用する sender を認証します。PostHog analytics は任意です。project key を省略すると analytics は無効のままです。

## 4A. GitHub Actions による cloud deployment [#4a-github-actions-による-cloud-deployment]

reference cloud path は `.github/workflows/deploy-try.yml` です。repository を検証し、D1 migration chain を local で実行し、remote D1 migration ledger と Queue list を読み取り、両 Worker を dry-run し、API と Web Worker をデプロイして、最後に public endpoint を確認します。R2、Container、binding のすべての resource を個別に preflight するものではありません。

fork では次を行います。

1. workflow の repository guard、environment URL、public health-check URL、deployment 固有の build variable を更新します。
2. workflow が使用する GitHub Environment を作成し、release branch に制限します。
3. `CLOUDFLARE_ACCOUNT_ID` と `CLOUDFLARE_API_TOKEN` を GitHub Environment secret として追加します。これらは CI の認証に使います。前 section の runtime secret は Cloudflare に残します。
4. release branch を force-push と削除から保護します。
5. review 済みの `main` commit だけを release branch に進めます。

reference workflow は `deploy/try` への push をデプロイします。

```bash
git fetch origin
git push origin origin/main:deploy/try
```

repository check、dry run、deployment、public verification がすべて成功するまで GitHub Actions run を監視します。D1 migration、Queue update、Worker publication は一つの atomic transaction ではないため、workflow は release を直列化します。

<Callout type="warning">
  commit 済み workflow は、設定された upstream 以外の repository からのデプロイを拒否します。fork で CI deployment を動かすには、この guard を意図的に変更する必要があります。
</Callout>

## 4B. Wrangler による local deployment [#4b-wrangler-による-local-deployment]

clean で review 済みの checkout から、同じ commit 済み設定を使用します。Wrangler は `wrangler login` で認証できます。API token を export すると local command を CI に近づけられます。

<Callout type="warning">
  `just check` だけで deployment preflight が完了したと考えないでください。API deploy script は build と bundle の検証より前、最初の remote operation として pending remote D1 migration を適用します。`just deploy` の前に、同じ release commit で以下の非変更 check をすべて完了してください。
</Callout>

最初に production credential を export し、repository、submodule、build-input directory が clean であることを確認します。

```bash
export CLOUDFLARE_ACCOUNT_ID="<your-account-id>"
export CLOUDFLARE_API_TOKEN="<your-api-token>"

git status --short --branch
test -z "$(git status --porcelain=v1 --untracked-files=all)"
git submodule foreach --recursive \
  'test -z "$(git status --porcelain=v1 --untracked-files=all)"'
test -z "$(git ls-files -v | grep -E '^[a-zS]')"
test -z "$(git ls-files --others --ignored --exclude-standard -- apps/web/src apps/web/public)"

just check
```

isolated local D1 database に対して migration chain 全体を実行し、production migration ledger と Queue list を変更せずに確認します。

```bash
(
  cd apps/api
  persist_dir="$(mktemp -d)"
  trap 'rm -rf "$persist_dir"' EXIT
  ../../node_modules/.bin/vp exec wrangler d1 migrations apply DB \
    --local --env prod --persist-to "$persist_dir"
)

(
  cd apps/api
  ../../node_modules/.bin/vp exec wrangler d1 migrations list DB --remote --env prod
  ../../node_modules/.bin/vp exec wrangler queues list
)
```

local migration chain が失敗した場合は停止します。remote ledger に pending migration がある場合は正確な SQL を確認し、migration が additive または明示的に承認済みの場合のみ続行します。step 1 で作成した五つの Queue がすべて存在することを確認してください。

Driver と Web asset を build し、両 Worker upload を dry-run します。以下の command は Worker の公開や remote migration の適用をせずに、設定と bundle を検証します。

```bash
./node_modules/.bin/vp run --filter agent-driver build

(
  cd apps/api
  ../../node_modules/.bin/vp exec wrangler deploy --env prod --minify --dry-run
)

./node_modules/.bin/vp run --filter @mosoo/web build

(
  cd apps/web
  ../../node_modules/.bin/vp exec wrangler deploy --env prod --dry-run
)

git status --short
```

上記すべての check が同じ clean commit で成功してから公開します。

```bash
just deploy
```

`just deploy` は repository gate 全体を実行し、API、Web Worker の順にデプロイします。API deployment は pending remote D1 migration を適用し、期待する schema を検証し、必須 queue を用意し、Driver container を build して API Worker を公開します。その後、Web deployment が console Worker を build して公開します。

部分的な失敗を診断した後に片側だけ release する場合は次を使用します。

```bash
just deploy-api
just deploy-web
```

これらの部分 command は直接公開し、repository gate 全体を実行しません。同じ clean release commit を維持し、上記の関連する build と dry-run を再実行してください。適用済み D1 migration は決して書き換えず、production schema の変更ごとに新しい migration を追加します。

## 5. Deployment を検証する [#5-deployment-を検証する]

example domain を置き換え、三つの public path をすべて確認します。

```bash
curl --fail --silent --show-error https://console.example.com/ >/dev/null
curl --fail --silent --show-error https://console.example.com/api/health
curl --fail --silent --show-error https://console.example.com/api/graphql \
  -H 'content-type: application/json' \
  --data '{"query":"query { __typename }"}'
```

console が HTTPS で読み込まれ、`/api/health` が mosoo service の OK を報告し、GraphQL が `Query` を返す必要があります。user に deployment を案内する前に、両 Worker のログも確認し、D1 migration と Queue consumer が正常であることを確かめてください。

正式な停止条件、recovery guidance、release acceptance check については、mosoo source repository の [`docs/production-deploy-verification.md`](https://github.com/langgenius/mosoo/blob/main/docs/production-deploy-verification.md) に従ってください。


# Environment (https://mosoo.ai/docs/ja/environments/)





Environment を使うと、Agent session を一貫した package set、setup script、変数で開始できます。

<img alt="Environment editor では package、setup、変数、network policy を定義します。" src="__img0" />

## Environment を作成する [#environment-を作成する]

**Config → Environments → Create environment** を開き、次を設定します。

* 再利用する template の **Name and description**。
* public npm または PyPI の、正確な version を指定した **Packages**。
* 準備済み package の復元後に実行される **Setup script**。
* 保存後に値が暗号化される **Environment variables**。
* インターネットアクセスを許可する Full、または Task Agent の接続先をドメイン許可リストで制限する Limited を選ぶ **Network policy**。

project の dependency file から作成することもできます。

```bash
mosoo console environments create-environment
```

## 割り当てと revision [#割り当てと-revision]

Environment を Project default にするか、特定の Agent で選択します。新しい session は選択した Environment revision を取得します。後からの編集は、その後に作成される session にのみ適用され、実行中の session は変わりません。

## ネットワークポリシー [#ネットワークポリシー]

* **Full** はインターネットへの直接アクセスを許可します。
* **Limited** はインターネットへの直接アクセスを無効にし、ドメイン許可リストで送信 HTTP/HTTPS 通信を制限します。許可リストには Environment で指定したドメインに加え、mosoo の runtime 制御と artifact 保存に必要な接続先が含まれます。

Limited は session ごとに独立した sandbox を使う **Task Agent** のみで利用できます。**Assistant Agent** は session 間で sandbox を共有するため、Full が必要です。runtime は sandbox の起動前にポリシーを適用し、その session 中は変更しません。別のポリシーを使うには新しい session を作成してください。

Limited の制限を適用できない場合、runtime は無制限のアクセスに切り替えず、sandbox の起動を拒否します。HTTPS interception を無効にしたローカル開発環境も対象です。Limited は `HTTP_PROXY`、`HTTPS_PROXY`、`ALL_PROXY` 環境変数も拒否します。小文字の形式も同様です。

<Callout type="warning">
  ネットワーク許可リストは接続先を制御します。許可された API や MCP tool が読み取り専用になるわけではありません。本番システムにアクセスする場合は、適切な tool 権限と読み取り専用の認証情報を設定してください。
</Callout>

## Package の動作 [#package-の動作]

npm package の CLI は `PATH`、CommonJS package は `NODE_PATH`、PyPI module は `PYTHONPATH` から利用できます。Node ESM の bare import には project-local install が必要です。OS package、Cargo、RubyGems、Go module は Environment package として選択できません。

Project default、および Agent が選択中の Environment は削除できません。


# エラーと制限 (https://mosoo.ai/docs/ja/errors-and-limits/)



2xx 以外のすべての JSON error は同じ envelope を使用します。

```json
{
  "error": {
    "code": "invalid_request",
    "message": "Request body must be an object."
  }
}
```

`error.message` ではなく `error.code` で branch してください。message は developer 向けであり、end user に直接表示すべきではありません。

## Error code [#error-code]

| HTTP | `error.code`           | Caller の対応                                                                         |
| ---- | ---------------------- | ---------------------------------------------------------------------------------- |
| 400  | `invalid_request`      | request shape、field value、body size、unsupported field を修正します。変更せずに retry しないでください。 |
| 400  | `invalid_json`         | serialization または `Content-Type` を修正します。                                           |
| 401  | `unauthenticated`      | `Authorization` を確認し、API token を rotate または再作成します。                                 |
| 403  | `forbidden`            | API token がこの Agent、Thread、file に access できるか確認します。                                |
| 404  | `not_found`            | ID が存在し、この API token から見えることを確認します。                                                |
| 409  | `agent_not_published`  | Agent を公開し、API access を有効にします。                                                     |
| 409  | `service_inactive`     | mosoo で Agent を再公開または修復します。                                                        |
| 409  | `readiness_blocked`    | mosoo で Agent readiness または configuration を修正します。                                  |
| 409  | `idempotency_conflict` | 処理中なら `Retry-After` まで待ち、body が異なる場合は新しい key を使用します。                               |
| 429  | `rate_limited`         | backoff し、`Retry-After` の後に retry します。                                             |
| 500  | `internal_error`       | 短時間の backoff で retry し、繰り返す場合は failure detail を保存します。                              |

## Idempotency [#idempotency]

`Idempotency-Key` は次でサポートされます。

* `POST /agents/{agentId}/threads`
* `POST /threads/{threadId}/events`

ルール:

* Project key の冪等性 scope は Project、method、route で、body の不一致を検出します。同じ Project のキーは更新後も記録と rate limit を共有します。account CLI credential は自身の credential 境界を使用します。
* 同じ request に同じ key を再使用すると、保存済み response が replay されます。
* 異なる request に同じ key を使用すると `409 idempotency_conflict` が返ります。
* 最初の request が処理中に key を再使用すると `409 idempotency_conflict` が返ります。
* key は空でなく、128 文字以下である必要があります。
* conflict response には `Retry-After` が含まれる場合があります。

## Public limit [#public-limit]

| Limit                    | 値              |
| ------------------------ | -------------- |
| Create Thread input text | 32000 文字       |
| `userId`                 | 255 文字         |
| File ID                  | 26 文字          |
| File upload              | 67108864 bytes |
| Event list default       | 100 events     |
| Event list maximum       | 1000 events    |
| Thread list maximum      | 100 Threads    |

<Cards>
  <Card title="API リファレンス" href="https://mosoo.ai/docs/ja/api-reference/">
    自動生成された endpoint ごとの request と response の詳細です。
  </Card>

  <Card title="認証とアクセス" href="https://mosoo.ai/docs/ja/auth-and-access/">
    API token と Agent access の check を説明します。
  </Card>
</Cards>


# イベントとストリーミング (https://mosoo.ai/docs/ja/events-and-streaming/)



Thread event は mosoo API integration の安定した read surface です。公開可能な state だけを返します。raw runtime payload、private transcript、internal diagnostics はこの API に含まれません。

## Snapshot を読み取る [#snapshot-を読み取る]

polling、job、backend state reconciliation には snapshot を使用します。

```http
GET /api/v1/threads/{threadId}/events?limit=100
```

response の `events` は、指定した window 内で古い順に返されます。limit に達したため古い public event が省略された場合、`truncated` は true です。default limit は 100、maximum は 1000 です。

各 event には次が含まれます。

| Field        | 意味                                                             |
| ------------ | -------------------------------------------------------------- |
| `id`         | 安定した event ID。prefix のない ULID。                                 |
| `runId`      | Run に属する event の Run ID。属さない場合は `null`。                        |
| `type`       | `agent.message.delta` や `run.completed` などの public event type。 |
| `status`     | `available`、`error`、`unsupported`。                             |
| `content`    | public event content または関連 payload への参照。                       |
| `occurredAt` | RFC 3339 timestamp。                                            |
| `durationMs` | 該当する場合の duration。                                              |
| `tokens`     | 該当する場合の token count。                                           |

## Update を stream する [#update-を-stream-する]

長時間動作する user experience には SSE を使用します。

```http
GET /api/v1/threads/{threadId}/events/stream?limit=100
```

stream は comment heartbeat から始まります。

```text
: connected
```

各 public event は次の形式で送信されます。

```text
event: thread.event
id: 01J00000000000000000000010
data: {"id":"01J00000000000000000000010","runId":"01J0000000000000000000000A","type":"run.started","status":"available","content":"01J0000000000000000000000A","occurredAt":"2026-05-19T00:00:01.000Z","durationMs":null,"tokens":null}
```

stream は polling 中に観測した重複 event ID を抑制します。新しい event がない間は keepalive comment を送信します。開始後に stream が失敗した場合、mosoo は standard error envelope を含む `event: thread.error` を送信します。

## 送信するイベント [#送信するイベント]

caller input を Thread に送信します。

```http
POST /api/v1/threads/{threadId}/events
```

送信できる event variant:

```json
{
  "events": [
    {
      "type": "user_message",
      "requestId": "ticket-182-message-1",
      "resources": [
        {
          "type": "file",
          "file_id": "01J0000000000000000000000J"
        }
      ],
      "text": "添付ファイルを要約してください。"
    },
    {
      "type": "permission_decision",
      "requestId": "tool-request-1",
      "decision": "allow_once"
    },
    {
      "type": "user_interrupt",
      "runId": null
    }
  ]
}
```

network retry によって同じ user input を二重送信しないよう、送信する event には `Idempotency-Key` を使用します。

## Output を再構築する [#output-を再構築する]

現在の UI 表示では、public event を `runId` ごとにまとめます。対象 Run の `agent.message.delta` event を時系列順に連結してください。Run が `completed` になった後は、Thread または send-event response に `run.finalOutput.text` があれば、それを優先します。

<Cards>
  <Card title="Thread event を一覧表示" href="https://mosoo.ai/docs/ja/api-reference/list-thread-events/">
    snapshot endpoint のリファレンスです。
  </Card>

  <Card title="Thread event をストリーム" href="https://mosoo.ai/docs/ja/api-reference/stream-thread-events/">
    SSE endpoint のリファレンスです。
  </Card>

  <Card title="イベントを送信" href="https://mosoo.ai/docs/ja/api-reference/send-user-messages-permission-decisions-or-interrupts-to-a-thread/">
    送信 event の schema です。
  </Card>
</Cards>


# ファイル (https://mosoo.ai/docs/ja/files/)



public API で upload したファイルは、Agent API Endpoint Project を scope とする draft file resource です。Thread の作成時または user message の送信時に mount します。Agent が生成したファイルは artifact です。API token caller から見える場合、どちらも Thread file list に表示されます。

## Upload flow [#upload-flow]

public upload は `multipart/form-data` を使用し、67108864 bytes までのファイルを受け付けます。

1. `POST /agents/{agentId}/files` で Agent にファイルを upload します。
2. 返された `file.id` を保存します。
3. Thread の作成時または後続の user message 送信時に `resources` でファイルを mount します。

## ファイルを upload する [#ファイルを-upload-する]

```bash
printf '顧客から実装計画を求められています。' > brief.txt

curl -X POST "https://cloud.mosoo.ai/api/v1/agents/$MOSOO_AGENT_ID/files" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -F "file=@brief.txt;type=text/plain"
```

response は `PublicFileResponse` です。`file.id` を保存します。

```json
{
  "file": {
    "id": "01J0000000000000000000000J",
    "name": "brief.txt",
    "mimeType": "text/plain",
    "size": 41,
    "createdAt": "2026-05-19T00:02:00.000Z"
  }
}
```

## 最初の message でファイルを使用する [#最初の-message-でファイルを使用する]

```bash
curl -X POST "https://cloud.mosoo.ai/api/v1/agents/$MOSOO_AGENT_ID/threads" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "customer-123",
    "resources": [
      {
        "type": "file",
        "file_id": "01J0000000000000000000000J"
      }
    ],
    "input": {
      "type": "user.message",
      "content": [
        {
          "type": "text",
          "text": "添付ファイルを要約してください。"
        }
      ]
    }
  }'
```

## 後続の message でファイルを使用する [#後続の-message-でファイルを使用する]

後続の user message の `resources` に file ID を指定します。

```json
{
  "events": [
    {
      "type": "user_message",
      "resources": [
        {
          "type": "file",
          "file_id": "01J0000000000000000000000J"
        }
      ],
      "text": "添付ファイルを要約してください。"
    }
  ]
}
```

<Cards>
  <Card title="Agent file を upload" href="https://mosoo.ai/docs/ja/api-reference/upload-an-agent-file/">
    Thread の作成または再開前にファイルを upload します。
  </Card>

  <Card title="File metadata を取得" href="https://mosoo.ai/docs/ja/api-reference/retrieve-file-metadata/">
    upload 済みまたは添付済みファイルの metadata を読み取ります。
  </Card>

  <Card title="Content を download" href="https://mosoo.ai/docs/ja/api-reference/download-thread-file-content/">
    添付ファイルまたは Agent artifact の byte content を download します。
  </Card>

  <Card title="ファイルを削除" href="https://mosoo.ai/docs/ja/api-reference/delete-a-file/">
    pre-Thread upload または表示可能な Thread file を削除します。
  </Card>
</Cards>


# 最初の Agent を作成 (https://mosoo.ai/docs/ja/first-agent/)







このガイドでは、空の Project から Agent を公開するまでの手順を説明します。

## 1. Project を開く [#1-project-を開く]

[cloud.mosoo.ai](https://cloud.mosoo.ai) にサインインします。mosoo は新しいアカウントに **Default Project** を作成します。リソースと使用量を分ける必要がある場合は、Project switcher から別の Project を作成するか開きます。

## 2. Provider key を追加する [#2-provider-key-を追加する]

**Config → Providers** を開きます。使用する runtime に対応する key を追加し、必要に応じて接続テストを実行します。準備が整った runtime はページ上部に表示されます。

<Callout type="warning">
  Provider credential は現在の Project に属します。保存済み key はマスクされ、エクスポートした Agent package には含まれません。
</Callout>

## 3. Agent を作成する [#3-agent-を作成する]

**Agents → Create agent** を開き、名前を入力して runtime を選択します。

<img alt="New Agent ダイアログでは Claude Agent SDK、OpenAI Runtime、OpenCode を選択できます。" src="__img0" />

* **Claude Agent SDK** は Anthropic key を使用します。
* **OpenAI Runtime** は OpenAI 互換 key を使用し、互換性のある Responses API endpoint が必要です。
* **OpenCode** は custom OpenAI-compatible endpoint を含む、対応する Provider credential を使用できます。

## 4. 動作を設定する [#4-動作を設定する]

**Preview** で **Assistant Agent** または **Task Agent** を選び、モデルと system prompt を設定します。Agent に必要な場合だけ Skill、MCP server、custom Environment を追加します。

<img alt="Agent Preview ではライブテストと設定編集を同じ画面で行えます。" src="__img1" />

## 5. 公開前にテストする [#5-公開前にテストする]

左側の Preview pane から代表的なタスクを送信します。回答、tool call、ファイル、失敗時の動作を確認してください。実行の詳細は **Logs**、モデル使用量は **Cost** で確認できます。Assistant Agent では作業 Environment の **Terminal** とリセット操作も利用できます。

## 6. 公開する [#6-公開する]

**Publish** を開いて draft を公開します。最初の公開時に Agent タイプが固定されます。以後の新しい session は現在の公開バージョンを使用し、既存 session は開始時のバージョンを維持します。

公開後、提供方法を選択します。

* **Thread** — mosoo console 内で作業を開始します。
* **API Access** — Agent ID を取得し、Public Thread API を呼び出します。
* **Instruction for LLM** — 対応する coding-agent workflow 向けの Agent 指示をコピーします。

<Cards>
  <Card title="Agent を設定" href="https://mosoo.ai/docs/ja/agent-configuration/">
    すべての設定項目を理解します。
  </Card>

  <Card title="プレビューとデバッグ" href="https://mosoo.ai/docs/ja/test-and-debug/">
    実際のタスクをテストし、失敗を診断します。
  </Card>

  <Card title="公開と API access" href="https://mosoo.ai/docs/ja/publish-and-api-access/">
    提供方法を選択します。
  </Card>
</Cards>


# インポート、エクスポート、fork、バージョン (https://mosoo.ai/docs/ja/import-export-versions/)





## Agent をエクスポートする [#agent-をエクスポートする]

Agent settings を開いて **Export agent** を選択します。mosoo は portable Agent setup と package 化した Skill を含む `.agent` package を download します。

## Package をインポートする [#package-をインポートする]

Agents ページで **Import package** を選択し、`.agent` file を選び、報告された repair を確認します。結果は現在の Project に編集可能な draft として作成されます。

<img alt="Import は portable .agent package から新しい draft を作成します。" src="__img0" />

## Agent を fork する [#agent-を-fork-する]

Agent settings を開いて **Fork agent** を選択します。fork は同じ Project に独立した draft を作成し、元の Agent は変更しません。公開済み Agent の固定されたタイプを変える場合や、別の設定をテストする場合に使用します。

## 移行されないもの [#移行されないもの]

`.agent` package は Project backup や実行 state の snapshot ではありません。次は含まれません。

* Provider または MCP credential。
* conversation、ログ、使用履歴。
* live runtime state または作業ファイル。

移行先 Project で外部 service を再接続し、見つからない Environment や secret value を再選択してください。

## Version history [#version-history]

draft または live-version badge を開くと、最新順に version が表示されます。list には live version が示され、runtime、model、変更、公開時刻が要約されます。新しい session は live version を使用し、既存 session は開始時のバージョンを維持します。

version history は読み取り専用です。過去設定の完全な内容、並列比較、publisher identity、restore は現在利用できません。


# mosoo ドキュメント (https://mosoo.ai/docs/ja/)



mosoo は、AI Agent の設定、実際のタスクによるテスト、安定版の公開、Run とファイルの運用、Public Thread API を通じた統合を一つのワークスペースで提供します。

<Cards>
  <Card title="最初の Agent を作成" href="https://mosoo.ai/docs/ja/first-agent/">
    Provider を設定し、Agent を作成、テスト、公開します。
  </Card>

  <Card title="製品ツアー" href="https://mosoo.ai/docs/ja/product-tour/">
    Project、Agent、Thread、Run、提供方法の関係を理解します。
  </Card>

  <Card title="CLI のセットアップ" href="https://mosoo.ai/docs/ja/cli/overview/">
    CLI をインストールしてサインインし、クラウドの準備状態を確認します。
  </Card>

  <Card title="API クイックスタート" href="https://mosoo.ai/docs/ja/quickstart/">
    バックエンドから curl で公開済み Agent を呼び出します。
  </Card>
</Cards>

## 直接回答 [#直接回答]

* **mosoo とは？** mosoo は Coding Agent 向けのオープンソース Agent runtime と API です。公開済み Agent の周りに、ホストされた Thread、ファイル、sandbox 実行、tool event、API access を提供します。
* **最初に何を読むべきですか？** まず[最初の Agent を作成](https://mosoo.ai/docs/ja/first-agent/)を読み、信頼されたバックエンドから公開済み Agent を呼び出す段階で [API クイックスタート](https://mosoo.ai/docs/ja/quickstart/)に進みます。
* **Public Thread API とは？** 公開済み Agent と対話するための backend API です。Thread の作成と再開、event の読み取りや streaming、ファイル転送を行います。
* **credential はどこに置くべきですか？** Agent と同じ Project の Project API key（`msp_`）を使用し、信頼されたサーバーまたは automation runner に保存します。旧 account token は拒否されます。ブラウザやモバイル client は自分の backend を呼び、backend が mosoo を呼び出します。

## ソースと検証 [#ソースと検証]

* [GitHub ソース](https://github.com/langgenius/mosoo)でオープンソース runtime と license を確認できます。
* [API リファレンス](https://mosoo.ai/docs/ja/api-reference/)は OpenAPI contract から生成された Public Thread API を説明します。
* [OpenAPI 3.1](https://cloud.mosoo.ai/api/v1/openapi.json)は機械可読な API source です。
* [llms.txt](https://mosoo.ai/docs/llms.txt) と [llms-full.txt](https://mosoo.ai/docs/llms-full.txt)は AI answer engine 向けの簡潔版と完全版のドキュメント index です。

## 構築 [#構築]

* [Project の境界と Agent タイプ](https://mosoo.ai/docs/ja/concepts/)を選択します。
* [Provider の認証情報とモデル](https://mosoo.ai/docs/ja/providers-and-models/)を追加します。
* Agent の[識別情報、runtime、指示、Skill、MCP、Environment](https://mosoo.ai/docs/ja/agent-configuration/)を設定します。
* 公開前に[プレビューとデバッグ](https://mosoo.ai/docs/ja/test-and-debug/)を行います。

## 公開と運用 [#公開と運用]

* [Agent を公開して API access を有効化](https://mosoo.ai/docs/ja/publish-and-api-access/)します。
* [Run、ファイル、使用量](https://mosoo.ai/docs/ja/operations/)を確認します。
* [インポート、エクスポート、fork、バージョン履歴](https://mosoo.ai/docs/ja/import-export-versions/)で設定を再利用します。

## 統合 [#統合]

Public Thread API は、公開済み Agent と対話するための API です。Thread の作成と再開、イベントの読み取りやストリーミング、ファイル転送を行えます。Agent の作成と設定は引き続き console または CLI で行います。

<Cards>
  <Card title="API の基本概念" href="https://mosoo.ai/docs/ja/threads-and-runs/">
    Thread と Run のライフサイクルを理解します。
  </Card>

  <Card title="API リファレンス" href="https://mosoo.ai/docs/ja/api-reference/">
    自動生成された request と response の schema を参照します。
  </Card>

  <Card title="エラーと制限" href="https://mosoo.ai/docs/ja/errors-and-limits/">
    安全な再試行と失敗状態の処理を実装します。
  </Card>
</Cards>


# Run、ファイル、使用量 (https://mosoo.ai/docs/ja/operations/)









## Run と Thread [#run-と-thread]

**Runs** を開いて Agent を dispatch し、作業を追跡します。Thread は All、Unread、Pinned、Failed で filter できます。Thread は非同期に返信することで再度開けます。各 Run の status と event history は保持されます。

<img alt="Runs ページでは実行中と完了済みの Agent Thread をまとめて表示します。" src="__img0" />

Agent の完了時に browser notification を受け取ることもできます。notification permission は browser が管理し、任意です。

## ファイル [#ファイル]

**Files** を開いて Project file、Thread attachment、runtime artifact を確認します。Agent、Thread、file role で filter し、項目を検索または preview できます。

<img alt="ファイルは Project、Agent、Thread、attachment、artifact role で分類されます。" src="__img1" />

Agent を削除または変更しても、`.agent` export が file backup になるわけではありません。runtime file と conversation history には別々の lifecycle があります。

## Project の使用量 [#project-の使用量]

**Project Settings → Project usage** を開きます。All、Production、Debug を選び、期間を 7 days、30 days、month to date、90 days から選択します。Overview、By Agent、By Model を確認するか、現在の tab を CSV で export できます。

<img alt="Project Usage には費用見積もり、model call、token trend、Agent、model が表示されます。" src="__img2" />

<Callout type="info">
  金額は記録された model call と reference price に基づく見積もりです。Provider invoice や mosoo の請求額ではなく、cost が報告されない未知の model では過少になる場合があります。
</Callout>

現在の単一オーナー製品では、budget、alert、invoice、payment control、user 単位の使用量は利用できません。


# 製品ツアー (https://mosoo.ai/docs/ja/product-tour/)



mosoo は、AI Agent を構築、実行、公開、運用するためのマネージドワークスペースです。Agent を一度設定して console でテストした後、Thread または API endpoint から利用できます。

## 製品モデル [#製品モデル]

| リソース             | 所有するもの                                                                |
| ---------------- | --------------------------------------------------------------------- |
| **Organization** | アカウントレベルのコンテナです。現在は単一オーナー向けであり、チームロールや招待は利用できません。                     |
| **Project**      | Agent、ファイル、設定、使用量を分離する境界です。新しいアカウントには Default Project が作成されます。        |
| **Agent**        | タイプ、runtime、モデル、指示、Skill、MCP connection、Environment を備えた再利用可能なワーカーです。 |
| **Thread**       | 一つの Agent に対する永続的な会話と作業の記録です。返信によって非同期に作業を再開できます。                     |
| **Run**          | Thread 内の一回の実行です。Run はイベント、ログ、使用量、ファイルを生成します。                         |

## 一般的なワークフロー [#一般的なワークフロー]

1. Project を開くか作成します。
2. モデル Provider の key を追加します。
3. Agent を作成して runtime を選択します。
4. 識別情報、指示、Skill、MCP server、Environment を設定します。
5. **Preview** でテストし、必要に応じて **Logs**、**Cost**、**Terminal** を確認します。
6. Agent を公開します。
7. mosoo で Thread を開始するか、API access を有効にします。
8. Run、ファイル、バージョン、使用量を監視します。

<Callout type="info">
  ほとんどの設定は現在の Project に属します。Provider key、MCP credential、Skill、Environment は Project の境界を越えて自動的に共有されません。
</Callout>

<Cards>
  <Card title="最初の Agent を作成" href="https://mosoo.ai/docs/ja/first-agent/">
    console での一連の手順を実行します。
  </Card>

  <Card title="Project、Agent、runtime" href="https://mosoo.ai/docs/ja/concepts/">
    適切な境界と実行モデルを選択します。
  </Card>

  <Card title="CLI のセットアップ" href="https://mosoo.ai/docs/ja/cli/overview/">
    CLI をインストールして mosoo Cloud に接続します。
  </Card>
</Cards>


# Provider とモデル (https://mosoo.ai/docs/ja/providers-and-models/)





Provider credential は現在の Project に保存され、Agent の起動時に解決されます。

<img alt="Providers ページには runtime の準備状態と Project レベルの credential が表示されます。" src="__img0" />

## Provider key を追加する [#provider-key-を追加する]

1. **Config → Providers** を開きます。
2. 組み込み Provider の **Add key**、または **Add custom model** を選びます。
3. 求められた場合は名前、API key、任意の base URL、対応モデル名を入力します。
4. **Test** で接続を確認してから保存します。
5. Agent に戻り、runtime とモデルを選択します。

key は名前付け、編集、テスト、default 指定、削除ができます。任意の接続テストが失敗しても保存自体は可能です。

## Runtime の準備状態 [#runtime-の準備状態]

**Runtime availability** card には、runtime が解決する credential が表示されます。対応する key がない場合、セットアップまたは Run は設定エラーで停止します。mosoo が別の Project の credential を流用することはありません。

## Custom endpoint [#custom-endpoint]

custom OpenAI-compatible credential は OpenCode で実行できます。OpenAI Runtime では、その runtime が使用する Responses API を endpoint が実装している必要もあります。

## Credential の境界 [#credential-の境界]

* 保存済み key は暗号化され、マスクされた形式でのみ表示されます。
* raw value は Agent settings、ログ、診断、`.agent` export に含まれません。
* Provider credential は Project 間で継承されません。
* key を削除すると依存する Agent が起動できなくなる場合があります。削除前に影響を受ける runtime の準備状態を確認してください。


# 公開と API access (https://mosoo.ai/docs/ja/publish-and-api-access/)







公開すると draft 設定の snapshot が作られ、各提供方法が利用可能になります。

<img alt="Publish menu には Thread、API Access、coding-agent instructions が表示されます。" src="__img0" />

## Draft を公開する [#draft-を公開する]

1. Preview のテストを完了します。
2. **Publish** を開いて draft を公開します。
3. live-version badge と version summary を確認します。

最初の公開時に Agent タイプが固定されます。新しい session は現在の live version を使用し、進行中の session は元のバージョンを使い続けます。

## Thread を開始する [#thread-を開始する]

**Thread** を選ぶか、**Runs → New thread** を開き、Agent を選択してタスクを入力し、dispatch します。後から返信すると同じ Thread を非同期に再開できます。

<img alt="新しい Thread には一つの Agent と一つの初期タスクを割り当てます。" src="__img1" />

## API access を有効にする [#api-access-を有効にする]

Publish menu の **API Access** で prefix のない ULID Agent ID をコピーします。その Agent の **Project settings → Project API keys** で Project key（`msp_`）を作成し、表示された秘密値を保存します。別の Project のキーでは呼び出せません。

token は `Authorization: Bearer` header でのみ使用してください。API access は Thread の作成と再開を行います。Agent の作成、編集、公開は行いません。

<Cards>
  <Card title="API クイックスタート" href="https://mosoo.ai/docs/ja/quickstart/">
    curl で Thread を作成します。
  </Card>

  <Card title="認証とアクセス" href="https://mosoo.ai/docs/ja/auth-and-access/">
    token と Agent access を理解します。
  </Card>

  <Card title="API リファレンス" href="https://mosoo.ai/docs/ja/api-reference/">
    Public Thread API のすべての operation を参照します。
  </Card>
</Cards>


# クイックスタート (https://mosoo.ai/docs/ja/quickstart/)



公開済み Agent に Thread を作成し、follow-up message を一つ送信して、public event log を読み取り、ファイルを添付します。

## 始める前に [#始める前に]

次が必要です。

* mosoo で API access を有効にした公開済み Agent。
* Agent API Access panel に表示される `agentId`。
* その Agent を呼び出せる mosoo API token。
* backend で認証した application user の opaque な `userId`。

```bash
export MOSOO_API_BASE="https://cloud.mosoo.ai/api/v1"
export MOSOO_API_TOKEN="msp_..."
export MOSOO_AGENT_ID="01J00000000000000000000001"
```

<Callout type="info">
  v1 の resource ID は prefix のない ULID です。`agent_...` や `thread_...` のような prefix 付き ID ではありません。
</Callout>

## 1. Thread を作成する [#1-thread-を作成する]

Thread は公開済み Agent の API conversation container です。`input` を指定して作成すると、最初の Run も queue に追加されます。

```bash
curl -X POST "$MOSOO_API_BASE/agents/$MOSOO_AGENT_ID/threads" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-create-thread" \
  -d '{
    "userId": "customer-123",
    "input": {
      "type": "user.message",
      "content": [
        {
          "type": "text",
          "text": "こんにちは。どのような支援ができるか説明してください。"
        }
      ]
    }
  }'
```

response から `thread.id` をコピーします。

```bash
export MOSOO_THREAD_ID="01J00000000000000000000009"
```

## 2. 別の message を送信する [#2-別の-message-を送信する]

同じ Agent interaction を続けるには `thread.id` を使用します。

```bash
curl -X POST "$MOSOO_API_BASE/threads/$MOSOO_THREAD_ID/events" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-send-message-1" \
  -d '{
    "events": [
      {
        "type": "user_message",
        "requestId": "quickstart-message-1",
        "text": "次に行うべき重要な三つの手順を教えてください。"
      }
    ]
  }'
```

現在の Run が input 待ち、または実行中の場合は、`permission_decision` や `user_interrupt` event も送信できます。

## 3. Event log を読み取る [#3-event-log-を読み取る]

public event を時系列順に読み取ります。

```bash
curl "$MOSOO_API_BASE/threads/$MOSOO_THREAD_ID/events?limit=100" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN"
```

event log は結果を読み取るための安定した場所です。user message、Agent message delta、thinking delta、tool status、file change、usage update、run status などが含まれます。

## 4. ファイルを添付する [#4-ファイルを添付する]

最初に Agent へファイルを upload します。

```bash
printf '顧客から実装計画を求められています。' > brief.txt

curl -X POST "$MOSOO_API_BASE/agents/$MOSOO_AGENT_ID/files" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -F "file=@brief.txt;type=text/plain"
```

response から `file.id` をコピーします。

```bash
export MOSOO_FILE_ID="01J0000000000000000000000J"
```

後続の user message とともにファイルを送信します。

```bash
curl -X POST "$MOSOO_API_BASE/threads/$MOSOO_THREAD_ID/events" \
  -H "Authorization: Bearer $MOSOO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-file-message-1" \
  -d '{
    "events": [
      {
        "type": "user_message",
        "requestId": "quickstart-file-message-1",
        "resources": [
          {
            "type": "file",
            "file_id": "01J0000000000000000000000J"
          }
        ],
        "text": "添付ファイルを要約してください。"
      }
    ]
  }'
```

最初の user message にファイルを含めるには、step 1 より前に upload し、create-Thread request に同じ `resources` array を追加します。

<Cards>
  <Card title="Thread と Run" href="https://mosoo.ai/docs/ja/threads-and-runs/">
    Thread と Run の lifecycle state を理解します。
  </Card>

  <Card title="イベントとストリーミング" href="https://mosoo.ai/docs/ja/events-and-streaming/">
    snapshot を読み取るか、SSE で Thread event を stream します。
  </Card>

  <Card title="ファイル" href="https://mosoo.ai/docs/ja/files/">
    ファイルを upload して Thread message に mount します。
  </Card>

  <Card title="エラーと制限" href="https://mosoo.ai/docs/ja/errors-and-limits/">
    retry、idempotency conflict、rate limit、invalid request を処理します。
  </Card>
</Cards>


# Skill と MCP server (https://mosoo.ai/docs/ja/skills-and-mcp/)







Skill と MCP server は Project が所有するリソースであり、選択した Agent に添付できます。

## Skill [#skill]

Skill は信頼できる指示と補助ファイルを package 化するため、各 prompt に同じ内容をコピーする必要がなくなります。

1. **Config → Skills → Add skill** を開きます。
2. `.md`、`.zip`、`.skill` ファイル、root に `SKILL.md` がある folder をアップロードするか、GitHub または skills.sh から import します。
3. 検出された名前、説明、author を確認します。
4. Agent を開き、**Add skill** を選択します。

<img alt="Skill はファイルや folder からアップロードするか、URL から import できます。" src="__img0" />

現在の console では Skill の download、fork、uninstall が可能ですが、Project 内 editor や update 操作はありません。fork は独立した copy です。uninstall 後も既存の Agent attachment が **Missing** として残る場合があります。

## MCP server [#mcp-server]

1. **Config → MCP servers → Add MCP** を開きます。
2. 名前と Remote HTTPS URL を入力します。
3. OAuth または bearer-token 認証を選んで保存します。
4. 認証を完了し、Agent editor で connection を添付します。
5. Preview または新しい Thread で、Agent に tool を使うよう依頼してテストします。

<img alt="MCP connection は Remote HTTPS server に OAuth または bearer token で接続します。" src="__img1" />

<Callout type="warning">
  **Connected** は mosoo に credential が保存されていることを示すだけで、remote server やすべての tool が動作する保証ではありません。現在、失敗は Agent が server を使用した時点で表示されます。
</Callout>

MCP credential は暗号化され、入力後に再表示されることはありません。local-process MCP、Project 間共有、connector marketplace、tool 単位の選択は利用できません。


# プレビューとデバッグ (https://mosoo.ai/docs/ja/test-and-debug/)



Agent workspace を使って、公開前に draft 設定をテストします。

## Preview [#preview]

左側の pane に代表的なタスクを入力します。次をテストしてください。

* 通常の request と期待する output。
* 添付した各 Skill または MCP server を使用する request。
* file input と生成される artifact。
* 情報不足時の確認動作。
* tool、credential、Environment の失敗経路。

draft の変更はすぐに Preview に反映されます。緑色の **Ready** state は editor がタスクを受け付けられることを示すだけで、すべての外部 dependency が動作する保証ではありません。

## Logs [#logs]

**Logs** を開いて session と実行履歴を確認します。runtime startup、tool use、failure を関連付けるために利用できます。secret がログに出力されるべきではありません。ユーザーが作成した内容に raw credential が含まれる場合は、診断情報を共有する前に削除してください。

## Cost [#cost]

**Cost** では Agent 単位の費用見積もり、model mix、最近の usage event を確認できます。production と debug の使用を分けて filter してください。cost は記録された model call に基づく見積もりであり、Provider invoice ではありません。

## Terminal とリセット [#terminal-とリセット]

Assistant Agent は Environment を session 間で維持できるため、Terminal と作業 state の control を提供します。意図的にクリーンな state に戻す場合に reset を使用します。reset により local workspace state、cache、sign-in が削除されることがあります。Task Agent は Run ごとにクリーンな状態で開始し、同じ永続 control は提供しません。

## 一般的な失敗の診断 [#一般的な失敗の診断]

1. **Runtime needs a key:** この Project で対応する Provider を設定します。
2. **Model is unavailable:** Provider の model list と endpoint compatibility を確認します。
3. **MCP tool fails:** connection が有効かつ認証済みであることを確認し、tool を直接使うタスクを再試行します。
4. **Environment startup fails:** 正確な package version、setup script、必須変数を確認します。
5. **Old session behaves differently:** 現在の公開バージョンを使うには新しい session を開始します。


# Thread と Run (https://mosoo.ai/docs/ja/threads-and-runs/)



mosoo は公開済み Agent を Thread-based API として公開します。application は Thread を作成または再利用し、Run を queue に追加する user event を送信します。mosoo は公開済み Agent 設定の中で各 Run を実行し、public event を Thread に書き戻します。

## Resource model [#resource-model]

| 概念                 | 意味                                                                                         |
| ------------------ | ------------------------------------------------------------------------------------------ |
| Agent API Endpoint | Agent API Access panel に表示される公開済み Agent の entry point。v1 の `agentId` は prefix のない ULID です。 |
| Thread             | API で作成する conversation container。application に `thread.id` を保存します。                         |
| Run                | Thread 上での Agent の一回の実行。create-thread input または user message によって Run を queue に追加できます。     |
| Event              | input、Agent output、tool state、file、usage、Run lifecycle の変更を表す public timeline entry。       |

v1 の resource ID は prefix のない ULID です。`agent_`、`thread_`、`file_`、`run_` などの prefix を付けないでください。

## 作成と取得 [#作成と取得]

公開済み Agent に Thread を作成します。

```http
POST /api/v1/agents/{agentId}/threads
```

`input` がある場合、mosoo は最初の Run を queue に追加します。`input` を省略した場合、Run のない空の `IDLE` Thread を作成します。

現在の Thread state を取得します。

```http
GET /api/v1/threads/{threadId}
```

response には `thread`、存在する場合は最新の `run`、便利な `links` が含まれます。

## Thread status [#thread-status]

| Status         | 意味                                                 |
| -------------- | -------------------------------------------------- |
| `IDLE`         | active Run がありません。user message で作業を queue に追加できます。 |
| `RUNNING`      | Run を実行中です。                                        |
| `RESCHEDULING` | Thread が Run と Run の間にあります。                        |
| `TERMINATED`   | Thread が終了しています。                                   |

## Run status [#run-status]

| Status          | 意味                                                        |
| --------------- | --------------------------------------------------------- |
| `queued`        | Run は存在しますが、まだ開始していません。                                   |
| `booting`       | Runtime を準備中です。                                           |
| `running`       | Run を実行中です。                                               |
| `waiting_input` | Run が caller input を待っています。多くの場合は permission decision です。 |
| `completed`     | 正常に終了しました。存在する場合、`finalOutput.text` は安定した値です。             |
| `failed`        | 失敗して終了しました。`run.error` を確認してください。                         |
| `cancelled`     | cancel されて終了しました。                                         |
| `expired`       | timeout または期限切れで終了しました。                                   |

## Lifecycle operation [#lifecycle-operation]

application 側の Thread list を整理するには lifecycle endpoint を使用します。

| Operation            | Endpoint                                    |
| -------------------- | ------------------------------------------- |
| Agent の Thread を一覧表示 | `GET /api/v1/agents/{agentId}/threads`      |
| Thread を archive     | `POST /api/v1/threads/{threadId}/archive`   |
| Thread を unarchive   | `POST /api/v1/threads/{threadId}/unarchive` |
| Thread を削除           | `DELETE /api/v1/threads/{threadId}`         |

archive すると Thread は default の active list に表示されなくなります。delete すると Thread と backing AgentSession が完全に削除されます。

<Cards>
  <Card title="Thread を作成" href="https://mosoo.ai/docs/ja/api-reference/create-a-thread-for-an-agent-api-endpoint/">
    request と response の完全な schema です。
  </Card>

  <Card title="イベントを送信" href="https://mosoo.ai/docs/ja/api-reference/send-user-messages-permission-decisions-or-interrupts-to-a-thread/">
    Run を queue に追加し、permission request に回答するか、実行を中断します。
  </Card>

  <Card title="Thread event を一覧表示" href="https://mosoo.ai/docs/ja/api-reference/list-thread-events/">
    output と status の表示に使う public event を読み取ります。
  </Card>
</Cards>


# 一般的な Agent パターン (https://mosoo.ai/docs/ja/use-cases/)



以下を出発点として、自分のデータと失敗ケースでテストしてください。

## 継続的なリサーチアシスタント [#継続的なリサーチアシスタント]

* **タイプ:** Assistant Agent
* **理由:** 反復する調査では継続する workspace が役立ちます。
* **設定:** citation を重視する prompt、関連する research Skill、任意の Remote HTTPS MCP source、分析 package 用の再利用可能な Environment。
* **提供:** 対話的な作業には mosoo Thread、別の製品への組み込みには API access。

## Pull request reviewer [#pull-request-reviewer]

* **タイプ:** Task Agent
* **理由:** 各 review はクリーンな一時 state で開始する必要があります。
* **設定:** repository-review Skill、GitHub MCP connection、厳密な output format、最小限の Environment。
* **提供:** review ごとに一つの Thread、または Public Thread API を呼び出す外部 system。

## Ticket triage worker [#ticket-triage-worker]

* **タイプ:** Task Agent
* **理由:** ticket は独立した job であり、一時 state を相互に漏らすべきではありません。
* **設定:** Skill 内の triage rubric、issue-tracker MCP、label と escalation の明示的なルール。
* **運用:** 失敗した Thread を filter し、Logs を確認し、production usage と Preview を分けて監視します。

## Team copilot [#team-copilot]

* **タイプ:** Assistant Agent
* **理由:** session 間で安定した working directory を維持すると copilot に役立ちます。
* **設定:** product と operations の Skill、および認証済み MCP connection。
* **境界:** mosoo の現在の console は単一オーナー向けです。team role と shared administration は利用できません。owner credential を共有せず、適切な外部 surface を通じて Agent を公開してください。

## 公開 application [#公開-application]

Agent を公開し、backend から Public Thread API を使用して、application user ごとに Thread を作成または再開します。


# Thread をアーカイブする (https://mosoo.ai/docs/ja/api-reference/archive-a-thread/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Agent API Endpoint の Thread を作成する (https://mosoo.ai/docs/ja/api-reference/create-a-thread-for-an-agent-api-endpoint/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# ファイルを削除する (https://mosoo.ai/docs/ja/api-reference/delete-a-file/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Thread を削除する (https://mosoo.ai/docs/ja/api-reference/delete-a-thread/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Thread ファイルコンテンツをダウンロード (https://mosoo.ai/docs/ja/api-reference/download-thread-file-content/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# API リファレンス (https://mosoo.ai/docs/ja/api-reference/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}

## Thread [#thread]

<Cards>
  <Card href="https://mosoo.ai/docs/ja/api-reference/create-a-thread-for-an-agent-api-endpoint/" title="Agent API Endpoint の Thread を作成する" />

  <Card href="https://mosoo.ai/docs/ja/api-reference/list-threads-for-an-agent-api-endpoint/" title="Agent API Endpoint の Thread をリストする" />

  <Card href="https://mosoo.ai/docs/ja/api-reference/retrieve-thread-summary/" title="Thread の概要を取得" />

  <Card href="https://mosoo.ai/docs/ja/api-reference/archive-a-thread/" title="Thread をアーカイブする" />

  <Card href="https://mosoo.ai/docs/ja/api-reference/unarchive-a-thread/" title="Thread のアーカイブを解除する" />

  <Card href="https://mosoo.ai/docs/ja/api-reference/delete-a-thread/" title="Thread を削除する" />
</Cards>

## イベント [#イベント]

<Cards>
  <Card href="https://mosoo.ai/docs/ja/api-reference/send-user-messages-permission-decisions-or-interrupts-to-a-thread/" title="ユーザー メッセージ、権限決定、または割り込みを Thread に送信します。" />

  <Card href="https://mosoo.ai/docs/ja/api-reference/list-thread-events/" title="Thread イベントのリスト" />

  <Card href="https://mosoo.ai/docs/ja/api-reference/stream-thread-events/" title="Thread イベントをストリーミングする" />
</Cards>

## ファイル [#ファイル]

<Cards>
  <Card href="https://mosoo.ai/docs/ja/api-reference/upload-an-agent-file/" title="Agent ファイルをアップロードする" />

  <Card href="https://mosoo.ai/docs/ja/api-reference/retrieve-file-metadata/" title="ファイルのメタデータを取得する" />

  <Card href="https://mosoo.ai/docs/ja/api-reference/list-thread-files/" title="Thread ファイルをリストする" />

  <Card href="https://mosoo.ai/docs/ja/api-reference/download-thread-file-content/" title="Thread ファイルコンテンツをダウンロード" />

  <Card href="https://mosoo.ai/docs/ja/api-reference/delete-a-file/" title="ファイルを削除する" />

  <Card href="https://mosoo.ai/docs/ja/api-reference/remove-a-thread-file/" title="Thread ファイルを削除する" />
</Cards>


# Thread イベントのリスト (https://mosoo.ai/docs/ja/api-reference/list-thread-events/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Thread ファイルをリストする (https://mosoo.ai/docs/ja/api-reference/list-thread-files/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Agent API Endpoint の Thread をリストする (https://mosoo.ai/docs/ja/api-reference/list-threads-for-an-agent-api-endpoint/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Thread ファイルを削除する (https://mosoo.ai/docs/ja/api-reference/remove-a-thread-file/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# ファイルのメタデータを取得する (https://mosoo.ai/docs/ja/api-reference/retrieve-file-metadata/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Thread の概要を取得 (https://mosoo.ai/docs/ja/api-reference/retrieve-thread-summary/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# ユーザー メッセージ、権限決定、または割り込みを Thread に送信します。 (https://mosoo.ai/docs/ja/api-reference/send-user-messages-permission-decisions-or-interrupts-to-a-thread/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Thread イベントをストリーミングする (https://mosoo.ai/docs/ja/api-reference/stream-thread-events/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Thread のアーカイブを解除する (https://mosoo.ai/docs/ja/api-reference/unarchive-a-thread/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# Agent ファイルをアップロードする (https://mosoo.ai/docs/ja/api-reference/upload-an-agent-file/)



{/* This file is generated from the mosoo OpenAPI snapshot. Run npm run openapi:pages after changing the spec. */}



# CLI (https://mosoo.ai/docs/ja/cli/overview/)



`mosoo` CLI は Public Thread API、Console GraphQL operation、console REST operation、machine-readable command catalog を提供します。

## インストール [#インストール]

```bash
curl -fsSL https://install.mosoo.ai/install.sh | bash
```

installer は CLI を `~/.local/bin` に配置し、`@mosoo` coding-agent Skill をインストールし、[cloud.mosoo.ai](https://cloud.mosoo.ai) にサインインして `doctor` を実行します。system を変更せずに option を確認するには次を実行します。

```bash
curl -fsSL https://install.mosoo.ai/install.sh | bash -s -- --dry-run
```

## 認証と確認 [#認証と確認]

interactive browser login:

```bash
mosoo auth login --hostname cloud.mosoo.ai
mosoo auth status --hostname cloud.mosoo.ai
mosoo doctor --json
```

Project key（`msp_`）は account 管理を認可しません。account 全体の Console 操作にはブラウザーログインを使用し、キー移行後は再ログインして旧 credential を `mcli_` credential に置き換えてください。[認証とアクセス](https://mosoo.ai/docs/ja/auth-and-access/)を参照してください。

non-interactive login では、token を shell history に残す引数ではなく standard input から渡します。

```bash
printf '%s' "$MOSOO_API_TOKEN" | \
  mosoo auth login --hostname cloud.mosoo.ai --with-token
```

## Command を探す [#command-を探す]

```bash
mosoo --help
mosoo commands --json
mosoo commands show console environments create-environment
mosoo search "create environment"
```

`commands --json` は tool と coding Agent 向けです。`commands show` は一つの generated command の正確な schema を表示します。

## 一般的な操作 [#一般的な操作]

```bash
mosoo ls -o json
mosoo run --help
mosoo console environments create-environment --help
```

CLI command は契約から生成されます。CLI を更新して command help を確認してください。旧版の `--input-app-id` は現在の Project 契約には使えません。実行例は [API quickstart](https://mosoo.ai/docs/ja/quickstart/) を参照してください。

endpoint resolution は `--target local|cloud|custom`、`--base-url`、`--hostname` で制御します。output format は `table`、`json`、`yaml`、`raw` です。

<Callout type="warning">
  token を command argument、source file、Agent prompt に貼り付けないでください。interactive login を使うか、`--with-token` に pipe してください。
</Callout>
