<span id="智能体、会话与自动化"></span>

# Agents, Conversations, and Automations

Use `moi-cli agent` and `moi-cli conversation` to discover and invoke agents, submit image and interactive A2A payloads, build agent packages locally, manage loaded agent versions and scheduled automations, and maintain persisted workspace conversations. Except for the offline agent package authoring commands, complete [Configuration and Authentication](../configuration-authentication.md) before running commands.

<span id="发现智能体发送文本与跟踪任务"></span>

## Discover agents, send text, and track tasks

List workspace or system agents, inspect an agent card, and submit plain-text requests through `agent send`:

```bash
# List available agents and read an agent card
moi-cli -auth pat -o agent list --workspace-id "$WORKSPACE_ID"
moi-cli -auth pat -o agent card --workspace-id "$WORKSPACE_ID" --agent-id "$AGENT_ID"

# Send a plain-text message and inspect or cancel the resulting task
moi-cli -auth pat -o agent send \
  --workspace-id "$WORKSPACE_ID" \
  --agent-id "$AGENT_ID" \
  --text 'Summarize order anomalies from this week.'

moi-cli -auth pat -o agent get-task \
  --workspace-id "$WORKSPACE_ID" \
  --agent-id "$AGENT_ID" \
  --task-id "$AGENT_TASK_ID"

moi-cli -auth pat -o agent cancel-task \
  --workspace-id "$WORKSPACE_ID" \
  --agent-id "$AGENT_ID" \
  --task-id "$AGENT_TASK_ID"
```

`agent send`, `get-task`, and `cancel-task` select the target agent via `--agent-id` or `--agent-code`. Agent A2A task IDs (strings), persisted `conversation` `session_id` values (integers), and workflow `execution_id` values belong to distinct services—pass each identifier only to its corresponding command group.

(cli-agent-message-inputs)=
<span id="发送图片重新生成与提交交互答复"></span>

## Send images, regenerate replies, and answer prompts

Use `agent a2a` (or `agent a2a-stream --output` for streaming responses) to submit full A2A JSON requests for image attachments, answer regeneration, and pending interaction replies. Run `moi-cli schema agent a2a` to inspect top-level CLI request fields (`agent_id` / `agent_code`, `jsonrpc`, `id`, `method`, `params`):

| Scenario | Example payload file | Required payload fields |
| --- | --- | --- |
| Send an image from a Catalog volume | `image-request.json` | Target `agent_id`, vision model name, matching `moi://files/<file_id>` file part, and `catalog_file` (`workspace_id`, positive integer `volume_id`, `file_id`). |
| Regenerate a completed reply | `regenerate-request.json` | Completed task `taskId` and `contextId`, pre-generated unique `controlId`, and `moi.run.control` (`action: "regenerate"`). |
| Answer a tool input prompt | `input-request.json` | `method: "matrixflow/input.submit"`, `taskId` in `input-required` state, current `inputRequestId`, and `answers` keyed by question ID. |
| Respond to a provider interaction | `provider-request.json` | Original interaction `requestId`, `target`, and the `payload` expected by `moi.provider_interaction.respond` (or `cancelled: true` with `payload` omitted). |

For example, save a PNG image request referencing a file already uploaded to a workspace Catalog volume as `image-request.json` (see [Send images, regenerate answers, and respond to interactions](../../api/ai-studio/agents/message-inputs.md) for all four full A2A request templates):

```json
{
  "agent_id": "<agent-id>",
  "jsonrpc": "2.0",
  "id": "req-image-001",
  "method": "message/send",
  "params": {
    "model": "<vision-model-name>",
    "message": {
      "kind": "message",
      "role": "user",
      "messageId": "msg-image-001",
      "parts": [
        {
          "kind": "text",
          "text": "Describe the labels and values shown in this chart."
        },
        {
          "kind": "file",
          "file": {
            "uri": "moi://files/<image-file-id>",
            "mimeType": "image/png",
            "name": "chart.png"
          },
          "metadata": {
            "file_id": "<image-file-id>"
          }
        }
      ]
    },
    "metadata": {
      "files": [
        {
          "catalog_file": {
            "workspace_id": "<workspace-id>",
            "volume_id": 123,
            "file_id": "<image-file-id>"
          }
        }
      ]
    }
  }
}
```

Submit the request and decode the outer `json` string field to extract the A2A task `id`:

```bash
# --no-wait returns immediately after server acceptance
moi-cli -auth pat -o agent a2a --no-wait --json-file image-request.json > image-response.json

# Decode the embedded JSON-RPC response and extract the task id when kind == "task"
jq '.json | fromjson | (.result // .)' image-response.json

export AGENT_TASK_ID="$(jq -r '.json | fromjson | (.result // .) | select(.kind == "task") | .id' image-response.json)"
moi-cli -auth pat -o agent get-task --agent-id "$AGENT_ID" --task-id "$AGENT_TASK_ID"
```

Submit regeneration or interaction reply requests with the same command:

```bash
moi-cli -auth pat -o agent a2a --no-wait --json-file regenerate-request.json
moi-cli -auth pat -o agent a2a --json-file input-request.json
moi-cli -auth pat -o agent a2a --json-file provider-request.json
```

:::{warning}
Regenerating a reply can re-execute external tool calls; when the response returns a `moi.run.control.result` message, read the new `taskId` matching your `controlId`, whereas tool-input and provider-interaction replies continue on the original task. If a request times out, retain your JSON file and control identifiers and inspect existing task state before retrying.
:::

<span id="配置智能体固定输出语言"></span>

### Configure a fixed agent output language

Read the agent's current metadata and merge `metadata.output_language` (set `""` to clear the fixed language; refresh `agent-before.json` before merging if concurrent edits occur):

```bash
moi-cli -auth pat -o agent resource-get --resource agents --tail-path "/$AGENT_ID" > agent-before.json
jq '{metadata: ((.metadata // {}) + {output_language: "zh-CN"})}' agent-before.json > language-update.json
moi-cli -auth pat -o agent resource-patch --resource agents --tail-path "/$AGENT_ID" --json-file language-update.json
moi-cli -auth pat -o agent resource-get --resource agents --tail-path "/$AGENT_ID"
```

<span id="本地构建智能体包与管理工作区技能包"></span>

## Build agent packages locally and manage workspace skills

`moi-cli` provides four local agent package commands that run offline without login, a workspace, or an API connection (if your installed package does not include these subcommands, obtain a deployment-matched installer from your deployment administrator):

```bash
# 1. Initialize an agent package source tree (target directory must not already exist)
moi-cli agent init --output ./assistant-package --agent-id com.example.assistant

# 2. Verify the source directory offline and build a deterministic .moiagent archive
moi-cli agent verify --source ./assistant-package
moi-cli agent build --source ./assistant-package --output assistant.moiagent --overwrite

# 3. Verify the built archive or unpack it back into an editable source tree
moi-cli agent verify --file assistant.moiagent
moi-cli agent unpack --file assistant.moiagent --output ./editable-assistant
```

When `agent.yaml` sets `minMOIVersion`, `build`, `verify`, and `unpack` accept `--running-moi-version <version>` to validate version compatibility; `unpack` strips generated `checksums.txt` files and compiled custom tool artifacts.

Use the authenticated workspace commands below to load agent packages or manage skill packages:

| Scenario | Subcommands | Description |
| --- | --- | --- |
| Load or export agent packages | `load-agent-package --file-path <file>`, `export-agent-package` | Load a `.moiagent` archive into a workspace or export an existing agent package. |
| Inspect, import, and read skills | `inspect-skill-package --file-path <file>`, `import-skill-package --file-path <file>`, `get-skill-file`, `download-skill-files`, `polish-skill-stream` | Run `inspect-skill-package` before importing to verify structure and ensure no secrets are bundled; inside sandbox tasks, `download-skill-files --skill-id <id> --output-dir <new-dir>` unpacks bound skill files without executing scripts. |
| Upload workspace files | `upload-workspace-file --file-path <file>` | Upload supporting workspace files for agents (default 64 MiB limit, configurable via `--max-upload-bytes`). |

(cli-agent-versions)=
<span id="管理智能体版本"></span>

## Manage agent versions

List loaded versions and check the active default version for an agent (append `--query-param agent_workspace_id=system` when inspecting read-only system agents):

```bash
# Read items[].version, status, diagnostics, and lineage.default_version
moi-cli -auth pat -o agent resource-get \
  --resource agents \
  --tail-path "/$AGENT_ID/versions" > versions.json

# Switch the default version to a verified target version and read back
moi-cli -auth pat -o agent resource-post \
  --resource agents \
  --tail-path "/$AGENT_ID/versions/$TARGET_AGENT_VERSION/default" \
  --json '{}'
moi-cli -auth pat -o agent resource-get --resource agents --tail-path "/$AGENT_ID/versions"
```

To retire an older non-default version, disable it first, verify `status` is `disabled`, and then delete it if needed:

```bash
moi-cli -auth pat -o agent resource-post \
  --resource agents \
  --tail-path "/$AGENT_ID/versions/$OLD_AGENT_VERSION/disable" \
  --json '{}'

moi-cli -auth pat -o agent resource-delete \
  --resource agents \
  --tail-path "/$AGENT_ID/versions/$OLD_AGENT_VERSION"
```

:::{warning}
The active default version cannot be disabled or deleted, and any enabled version must be disabled before deletion. Resolve missing configuration issues reported in `diagnostics` and generate a new version before switching the default version.
:::

(cli-agent-automations)=
<span id="管理定时与触发式自动化任务"></span>

## Manage scheduled and triggered automations

Prepare an automation definition `automation.json` with a pre-generated unique task `id` (the server validates `cron_expression` immediately even when `status` is `disabled`):

```json
{
  "id": "<new-task-id>",
  "name": "Daily Summary",
  "agent_id": "<agent-id>",
  "model": "<available-model>",
  "instruction_text": "Summarize authorized records for today.",
  "trigger": {
    "mode": "cron",
    "cron_expression": "TZ=UTC 0 9 * * *"
  },
  "status": "disabled"
}
```

Create the task, update its Cron schedule, and activate it (omit server-generated read-only fields such as `service_name` from update payloads):

```bash
# 1. Create the automation task and read it back (if timed out, query your reserved id first)
moi-cli -auth pat -o agent resource-post \
  --resource agent-automation-tasks \
  --json-file automation.json > created.json

export AUTOMATION_TASK_ID="$(jq -r '.id' created.json)"
moi-cli -auth pat -o agent resource-get \
  --resource agent-automation-tasks \
  --tail-path "/$AUTOMATION_TASK_ID" > task.json

# 2. Update the Cron schedule and activate, then check status, version, and next_trigger_at
cat > schedule.json <<'EOF'
{"trigger":{"mode":"cron","cron_expression":"TZ=UTC 0 10 * * *"},"status":"active"}
EOF

moi-cli -auth pat -o agent resource-patch \
  --resource agent-automation-tasks \
  --tail-path "/$AUTOMATION_TASK_ID" \
  --json-file schedule.json
moi-cli -auth pat -o agent resource-get \
  --resource agent-automation-tasks \
  --tail-path "/$AUTOMATION_TASK_ID"
```

Trigger an active Cron task manually, inspect run history, and disable or archive the task:

```bash
# List task-scoped runs or workspace-wide runs (supports status and RFC 3339 created_from/created_to; max limit 200)
moi-cli -auth pat -o agent resource-get \
  --resource agent-automation-tasks \
  --tail-path "/$AUTOMATION_TASK_ID/runs" \
  --query-param limit=50 --query-param offset=0

moi-cli -auth pat -o agent resource-get \
  --resource agent-automation-runs \
  --query-param status=succeeded --query-param limit=50 --query-param offset=0

# Trigger a manual run on an active Cron task and read details, events, and results
moi-cli -auth pat -o agent resource-post \
  --resource agent-automation-tasks \
  --tail-path "/$AUTOMATION_TASK_ID/runs" \
  --json '{"payload":{}}' > run.json

export AUTOMATION_RUN_ID="$(jq -r '.id' run.json)"
moi-cli -auth pat -o agent resource-get --resource agent-automation-runs --tail-path "/$AUTOMATION_RUN_ID"
moi-cli -auth pat -o agent resource-get --resource agent-automation-runs --tail-path "/$AUTOMATION_RUN_ID/events" --query-param limit=20 --query-param offset=0
moi-cli -auth pat -o agent resource-get --resource agent-automation-runs --tail-path "/$AUTOMATION_RUN_ID/result"

# Disable future triggers (in-flight runs continue under AUTOMATION_RUN_ID) and archive the task
moi-cli -auth pat -o agent resource-patch --resource agent-automation-tasks --tail-path "/$AUTOMATION_TASK_ID" --json '{"status":"disabled"}'
moi-cli -auth pat -o agent resource-delete --resource agent-automation-tasks --tail-path "/$AUTOMATION_TASK_ID"
```

API-triggered tasks are invoked through their returned `api_summary` contract, and callback-triggered tasks run through their callback pipeline. Running `resource-delete` on `agent-automation-tasks` transitions the task to `status: archived` while keeping its definition and run history readable; generate a new `id` if creating another task with the same name.

<span id="管理持久化会话与消息"></span>

## Manage persisted conversations and messages

Use `conversation` to list and maintain persisted workspace sessions visible to the current identity (identified by numeric `session_id`):

```bash
# List sessions with pagination (optional query params: source, keyword, tag)
moi-cli -auth pat -o conversation list-sessions \
  --workspace-id "$WORKSPACE_ID" \
  --query-param page=1 \
  --query-param page_size=20

# Read session metadata and messages (paginate with after=<last-message-id> and limit=50 until [])
moi-cli -auth pat -o conversation get-session --workspace-id "$WORKSPACE_ID" --session-id "$SESSION_ID"
moi-cli -auth pat -o conversation list-messages \
  --workspace-id "$WORKSPACE_ID" \
  --session-id "$SESSION_ID" \
  --query-param limit=50
```

In `list-messages`, `total` reports total messages in the session and does not shrink as `after` advances; JSON output may omit zero-valued fields such as `role=0` on user messages.

(cli-conversation-update)=
<span id="更新会话标题与维护消息"></span>

### Update session titles and maintain messages

Supply the current title in `expected_title` inside `session-update.json` for optimistic concurrency checking when renaming a session:

```json
{
  "title": "Archived Discussion",
  "expected_title": "<current-title-from-get-session>"
}
```

```bash
moi-cli -auth pat -o conversation update-session \
  --workspace-id "$WORKSPACE_ID" \
  --session-id "$SESSION_ID" \
  --json-file session-update.json

# Delete a session that is no longer needed
moi-cli -auth pat -o conversation delete-session \
  --workspace-id "$WORKSPACE_ID" \
  --session-id "$SESSION_ID"
```

:::{warning}
If `expected_title` does not match the current title on the server, `conversation update-session` can still exit `0` and return the unchanged session object. Always compare the returned `title` or re-run `get-session` to confirm the rename took effect (empty `title` or `config` values preserve existing settings).
:::

`conversation modify-response` and `append-modified-response` edit stored reply text without invoking model regeneration. For inbound IM bindings and external plugin OAuth accounts, see [Messaging Channels and Plugins](channels-plugins.md).

<span id="限制和注意事项"></span>

## Limitations and notes

- Workspace-wide `agent-automation-runs` ignores the `automation_task_id` query parameter; use `agent-automation-tasks --tail-path "/$AUTOMATION_TASK_ID/runs"` to list runs for one automation task.
- `created_from` (inclusive) and `created_to` (exclusive) use RFC 3339 timestamps; deduplicate by run `id` when paginating with `offset` during active task execution.
- Keep personal access tokens, connector keys, and third-party credentials out of prompt text, A2A JSON files, and shared logs.
