Metadata-Version: 2.4
Name: magic-campus-cli
Version: 0.2.0b10
Summary: Magic Campus business HTTP SDK and CLI
License-Expression: AGPL-3.0-or-later
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: httpx<1,>=0.27
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: build>=1; extra == "dev"
Requires-Dist: twine>=6; extra == "dev"

# magic-campus-cli

Business Python SDK and HTTP-only `magic-campus` command. Install this distribution
in a dedicated tool environment. It provides `magiccampus_sdk` and
`magiccampus_cli`; do not co-install it with the frozen `magic-campus-sdk`.

## Usage

```sh
python -m pip install magic-campus-cli
export MAGIC_CAMPUS_BASE_URL="<api-base-url>"
export MAGIC_CAMPUS_API_KEY='<api-key>'
magic-campus --help
magic-campus user get --id 10001 --format json
magic-campus assistant user-id --user-id 123 --format json
magic-campus playgroup list --format json
```

`MAGIC_CAMPUS_BASE_URL` and `MAGIC_CAMPUS_API_KEY` select the business environment
and credential. New installs and updates of this package do not install the IM
distribution. Current-conversation replies remain the responsibility of the
Agent's Channel.

### Agent OAuth

使用服务票（`client_credentials`）执行业务命令只需配置 `MAGIC_CAMPUS_BASE_URL`、
`MAGIC_CAMPUS_CLIENT_ID` 和 `MAGIC_CAMPUS_CLIENT_SECRET`。发起新的用户委托授权时，
CLI 默认使用 `http://127.0.0.1:8765/callback`，显式设置的 `MAGIC_CAMPUS_OAUTH_REDIRECT_URI` 优先。
授权申请和换票使用同一个 URI，须与 srv 为该客户端登记的 `redirectUris` 精确匹配。
srv 初始化个人助手时会登记上述默认值。手工登记的客户端若要使用默认值，须在 `redirectUris` 中包含该地址。
多用户会话从可信上下文为每次调用设置 `MAGIC_CAMPUS_SUBJECT_USER_ID`。

用全局参数 `--as` 显式选择身份：

- `--as user`：代表 `MAGIC_CAMPUS_SUBJECT_USER_ID` 指定的用户。未设置时由服务端确定个人 Agent 的主人。用这个身份读取该用户的数据，只有用户明确要求 Agent 代表自己时才执行写操作。
- `--as agent`：使用 `client_credentials` 获取服务票，以 Agent 自己的账号执行，忽略 `MAGIC_CAMPUS_SUBJECT_USER_ID`。
- 省略：采用 `MAGIC_CAMPUS_AS=user|agent` 指定的部署默认值。两者均未设置时，有 `MAGIC_CAMPUS_SUBJECT_USER_ID` 就使用用户委托，否则使用服务票。

这两个选项只选择取票方式。可用 scope 由管理员在后台配置，业务权限由服务端检查。

API Key 模式下 Key 已决定身份，`--as` 不起作用。JSON 输出的 `_meta.identity` 报告本次实际身份，例如 `{"auth": "oauth", "as": "user", "userId": "101"}` 或 `{"auth": "api_key"}`。

普通查询直接执行业务命令。CLI 按 scope 和身份复用有效票据。需要用户委托时，CLI 创建授权请求，以客户端 Basic 凭据调用 `POST /oauth/authorizations/confirm`，显式 subject 只读取可信会话提供的 `MAGIC_CAMPUS_SUBJECT_USER_ID`。CLI 校验 state、登记的 redirect URI，以 S256 PKCE 换票并校验委托身份。全程由 CLI 完成。

Agent 查询 IM 历史或建群时，如果需要自己的用户 ID，CLI 通过 `POST /oauth2/introspect` 读取 `actor_user_id`，并随服务票缓存。

删除评论、调整群成员、修改资料、替换 Focus 或重置成长档案等敏感操作，Agent 要在对话中说清动作、目标及范围，等待当前用户口头或文字明确同意。CLI 对专用命令和通用 `api` 均返回 `confirmation_required` 和一次性 `confirmationId`，退出码为 10，以区别于普通失败（1）。获得同意后，在原命令前加确认参数，例如：

```sh
magic-campus --confirm-action <confirmationId> comment delete --id c1
```

确认绑定本次身份、命令和实际请求，五分钟内可用一次。五分钟内重复执行同一请求会返回同一个 `confirmationId`，并带 `"pending": true`：如果用户已经同意过这个操作，直接加 `--confirm-action` 执行，不要再问一次。目标或内容变化、确认过期，都要重新说明并征得同意。即使 OAuth 票仍有效或通用写命令已加 `--allow-write`，也要逐次确认。收到 `write_outcome_unknown` 先查证业务结果。

失败输出在 `code` 之外带 `hint`，写明 Agent 的下一步，覆盖 OAuth 错误码、`confirmation_invalid`、`write_outcome_unknown` 以及业务码 401、403、404。

- `scope_not_granted` 表示客户端缺少所需 scope。请运维在管理后台启用该 scope。也适用于取票时收到的 `invalid_scope` 和 `unauthorized_client`。
- `insufficient_scope` 表示当前票据缺少 scope，CLI 会按服务端返回的缺项重新取票。遇到其他 403 时，保持已选身份并报告拒绝结果。

服务端提供 `hint` 时，CLI 优先显示该提示。

管理员可用 `magic-campus auth status` 检查缓存，或用 `magic-campus auth token --scope story:read` 诊断取票。后者报告取票结果、有效期和 scope，并输出访问令牌本身，只能在运维会话中使用。票据默认保存在 `~/.magic-campus/auth/oauth.json`。

`im notify send --file ./report.pdf` 等本地附件走 OpenIM 上传，OAuth 和 API Key 的用法相同。OAuth 使用当前授权方式取得 `im:send` scope 的票据，通过 `GET /api/v1/accounts/imToken` 换取已认证 Agent 账号自己的 IM token。`file upload` 和 `file presign` 继续使用 Pearl 文件服务。

### API 调用、文件上传与 Story 发布

```sh
magic-campus api --list
magic-campus api GET /api/v1/space/playgroups/detail --query spaceId=space-42
magic-campus api POST /api/v1/space/notices --body notice.json --allow-write
magic-campus file upload photo.png --channel-user-id 10001 --normalize-url
magic-campus file upload audio.wav --channel-user-id 10001 --scope PRIVATE --scene LIVE_FILE
magic-campus file presign --file-type PNG --file-type ZIP --scope PRIVATE --scene COMMON
magic-campus story publish image --title "活动照片" --channel-user-id 10001 --image-file photo.png --cover-url https://cdn.example.com/cover.jpg
magic-campus story publish video --title "活动回放" --channel-user-id 10001 --video-file clip.mp4 --cover-file photo.png
```

- `api --list` 离线列出允许调用的路由及其业务影响和 OAuth scope。路径和查询参数分开传，查询参数可重复使用 `--query`。用 `--body -` 从 stdin 读取 JSON 对象。写路由需要 `--allow-write`。
- `file upload` 支持 JPEG、JPG、PNG、WEBP、MP3、WAV、MP4、MOV、M4A 和 ZIP。可用 `--file-type` 覆盖扩展名推断。图片可用 `--normalize-url` 转换公开 S3 下载链接。
- `file upload` 和 `file presign` 支持 `--scope PUBLIC_READ|PRIVATE`，默认 `PUBLIC_READ`，以及 `--scene COMMON|THUMBNAIL|LIVE_FILE`，默认 `COMMON`。`file presign` 接受 1–16 个 `--file-type`，单个调用 `genUploadPreSignUrl`，批量调用 `genUploadPreSignUrls`，按请求顺序返回预签名结果且不上传。
- `story publish` 支持本地文件和已有 URL。图片可重复传 `--image-file`，也可传 `--image-story-file`、`--image-urls-file` 或 `--image-urls`。视频支持文件、URL 或保存 URL 的文本文件。图片和视频均支持 `--cover-file`、`--cover-url-file` 或 `--cover-url`，三选一。图片省略封面时使用第一张图。
- 三类命令均复用当前 CLI 凭据和身份选择。`--channel-user-id` 保留脚本的参数校验，实际归属由服务端凭据确定。成功和失败的 JSON 均包含 `_meta.cliVersion` 和 `_meta.identity`，未使用凭据时身份为 `null`。成功退出码为 0，失败为 1，待确认为 10。

### 业务专用命令

一个业务对象一个命令名，范围、筛选和数量用参数表达。完整参数见 `magic-campus --help`。

```sh
magic-campus story list --limit 20                          # 全站时间线（游标分页）
magic-campus story list --user-id 10001 --page 1 --page-size 20   # 指定作者已发布的 Story
magic-campus story list --view liked --user-id 10001        # published|authored|liked|co-created|recommend|robot
magic-campus story list --view recommend --snapshot-id <id>
magic-campus story get --id <storyId>
magic-campus story like|delete --id <storyId>
magic-campus story feedback --id <storyId> --reason-type 1  # 1 DISLIKE, 2 REPORT, 3 BLOCK_USER, 4 OTHER
magic-campus task list --scope TODAY_DUE                    # 或 --space <spaceId>、--global
magic-campus task list --space <spaceId> --user-id 10001 --only-summary --timezone Asia/Shanghai
magic-campus task get --id <taskId> [--global] [--timezone Asia/Shanghai]
magic-campus focus list | focus get --quest-id <id> | focus coins
magic-campus focus replace --body focus.json
magic-campus notification list --read                       # 或 --unread，或 --own-story-unread --page-size 20
magic-campus notification count --type LIKED --type COMMENTS_LIKED   # 可重复 --type 按类型统计，list 同样支持
magic-campus notification delete --id n1 --id n2            # 或 --all-read、--all
magic-campus user list --keyword alice
magic-campus user list --page 2
magic-campus user init-growth-profile --id 10001 --academy-code Digital --onboarding-answer "我的回答"
magic-campus user adjust-academy-level --id 10001 --academy-level L2
magic-campus im notify history --unread --since 2026-11-01T00:00:00+08:00   # 省略 --to 查当前用户全部会话
magic-campus im notify history --read --exclude-self --text-only --private-only --include-revoked --include-deleted --include-notifications
magic-campus im notify send --to user:10001 --quote <serverMsgID> --text "收到"
magic-campus im notify send --to group:g1 --native-at @message.json
magic-campus im group get --group g1,g2
magic-campus im group members --group g1 --page 1 --page-size 100
magic-campus im group create --name 小组
magic-campus im group create --space s1 --name 小组 --owner 10001 --group-id g_s1 --join-passcode <passcode>
magic-campus im group invite --space s1 --users 10002,10003
magic-campus im group rename --group g1 --name 新名字
magic-campus playgroup reject-join --id s1 --applicant-id 10002
magic-campus space create --body space.json
magic-campus space list-notice [--space <spaceId>]
magic-campus comment create --feed-id <feedId> --content=--继续
magic-campus comment create --feed-id <feedId> --content-file <path|->
magic-campus space update-notice --id 42 --title 新标题 | space delete-notice --id 42
magic-campus file download-url --id f1 [--id f2]            # 单个走 genDownloadUrl，多个走 genDownloadUrls
```

- 输出统一为 `{"ok": true, "resource": ..., "action": ..., "result": <AjaxResult>}`，失败退出码为 1。`story list` 不带 `--view`/`--user-id` 时保持原时间线输出。
- `--limit/--cursor` 与 `--page/--page-size` 互斥；`task list` 的 `--space` 与 `--global` 互斥；`notification delete` 的 `--id`、`--all-read`、`--all` 互斥。
- `task list` 和 `task get` 的 `--timezone` 随请求发为 `X-Timezone`。`task list --space` 的 `--user-id` 筛选任务所属用户。`space list-notice` 省略 `--space` 时查询当前用户或主人的关联 Space。
- `--timeout <seconds>` 为有限正数，覆盖 task、focus、notification、story、comment、user、assistant、playgroup、space、im group、im notify history 和 im reaction 的单次业务请求超时。省略时沿用各命令原有默认值。
- 评论接受 `--content <text>`、`--content=<text>` 或 `--content-file <path|->`。文件和 stdin 以 UTF-8 读取，保留原始空白和换行。
- 写命令不需要 `--allow-write`，敏感写入（删除、群管理、Space 管理、Focus 替换、成长调整等）走上文的 `--confirm-action` 确认。
- 旧命令名保留为隐藏别名：`feed …`（同 `story …`）、`im group get-batch`、`im chat.members get`（`--page-number/--show-number`）、`space group update-name`。

### Python SDK

```python
import os

from magiccampus_sdk import MagicCampusClient, MagicCampusClientConfig

client = MagicCampusClient(MagicCampusClientConfig(
    apiurl=os.environ["MAGIC_CAMPUS_BASE_URL"],
    apikey=os.environ["MAGIC_CAMPUS_API_KEY"],
))
# client.user, client.feed, client.space, client.playgroup, client.comment, client.assistant
# client.group: HTTP group management, members, and message queries
# client.im.http(): HTTP message sender; client.im also supplies reactions
```

`client.assistant.get_user_id(123)` calls `GET /api/v1/assistant/userId?userId=123`
and returns an integer assistant user ID or `None`. The CLI returns
`{"ok": true, "userId": 123, "assistantUserId": 456}` (plus `_meta`), or
`assistantUserId: null` when no identity is bound, including nonexistent owners.
The explicit target must be a positive Long integer and is never replaced by
the API Key's owner. This read does not create or wake an assistant, and a
returned ID does not prove readiness or grant access to the assistant's profile.

All commands use HTTP. Existing OpenIM HTTP group operations retain their request
semantics; no command initializes a websocket. `im group kick --group ID --users
ID1,ID2` uses the business kick endpoint. Group invitations and member queries use
the business API. `auth status` verifies HTTP credentials and reports
`transport=http_api`, without claiming a websocket is connected.

`im notify history --to user:ID|group:ID --limit N` queries
`POST /api/v1/im/message/query`, then selects the requested conversation. The
server currently accepts a per-conversation limit rather than a target-conversation
filter, so the HTTP response can include other conversations; only the requested
one is returned by the CLI. It does not synchronize or read an IM local database.
Results use the server's message field names.

`im notify history` 的 `--read` 和 `--unread` 互斥。`--private-only` 只能用于全部会话或私聊目标。
使用 `--quote <serverMsgID> --text <text>` 时，CLI 先查目标会话最近 50 条记录，找到原消息后发送原生引用。OAuth 需要 `im:read` 和 `im:send`。
`--native-at <json|@file|->` 仅用于群聊，需要 `text`、至少一项 `mentions`（`user_id`、`nickname`）和至少一项 `medias`（`type` 为 `IMAGE` 或 `VIDEO`，提供 HTTP(S) `url`，视频还需 `cover`）。可选 `parts` 按零基索引引用媒体，`text_format` 可设为 `MARKDOWN`。CLI 只发送一条 contentType 106 消息。

OAuth 独立建群使用 `/api/v1/im/createGroupWithMembers`。省略 `--group-id` 时 CLI 生成 ID，省略 `--owner` 时使用已认证的身份。两种建群模式均接受 `--join-passcode`，当前服务端在绑定 Space 时应用口令。独立建群的业务路由支持名称、成员、管理员和头像。

Only an explicit `magic-campus update` checks PyPI and installs a newer CLI.
Business commands run the installed version. `MAGIC_CAMPUS_CLI_SOURCE` selects a local source project
for development; it must point to a project named `magic-campus-cli`. The updater
refuses to run in an environment where the frozen `magic-campus-sdk` distribution
is installed. This is an update guard, not a pip installation conflict mechanism:
manual co-installation can still overwrite shared files and is unsupported.
The legacy updater continues to target the frozen package name.

## Development and validation

From the repository root:

```sh
uv sync --frozen --all-packages
uv run --frozen --no-sync pytest -q magic-campus-cli/tests
uv build --no-sources --package magic-campus-cli --out-dir dist/cli --clear
```

Use `uv sync --frozen --package magic-campus-cli --group dev` for an environment containing
only this member and development tools. See [workspace instructions](../README.md)
and [build/install checks](../PYPI_RELEASE.md). This source does not perform an
online Agent upgrade.
