Metadata-Version: 2.4
Name: magic-campus-cli
Version: 0.2.0b2
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`。

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

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

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

确认绑定本次身份、命令和实际请求，五分钟内可用一次。目标或内容变化、确认过期，都要重新说明并征得同意。即使 OAuth 票仍有效或通用写命令已加 `--allow-write`，也要逐次确认。收到 `write_outcome_unknown` 先查证业务结果。

管理员可用 `magic-campus auth status` 检查缓存，或用 `magic-campus auth token --scope story:read` 诊断取票。后者输出 bearer 凭据，只在私密终端使用。票据默认保存在 `~/.magic-campus/auth/oauth.json`。

OAuth 发送本地附件时使用文件服务的预签名上传。文件通过公开下载链接交付，格式
受文件服务支持范围限制。

### 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 story publish image --title "活动照片" --channel-user-id 10001 --image-file photo.png
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、MP4 和 MOV。可用 `--file-type` 覆盖推断的类型。使用 `--normalize-url` 可按当前 API 环境转换公开 S3 下载链接。
- `story publish` 支持本地文件和已有 URL。图片可重复传 `--image-file`，也可传 `--image-story-file`、`--image-urls-file` 或 `--image-urls`。视频和封面各支持文件、URL 或保存 URL 的文本文件。
- 三类命令均复用当前 CLI 凭据，OAuth 交互用户从 `MAGIC_CAMPUS_SUBJECT_USER_ID` 读取。`--channel-user-id` 保留脚本的参数校验，实际归属由服务端凭据确定。请求结果以 JSON 输出，成功退出码为 0，失败为 1。

### 业务专用命令

一个业务对象一个命令名，范围、筛选和数量用参数表达。完整参数见 `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 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 get --id <taskId> [--global]
magic-campus focus list | focus get --quest-id <id> | focus coins
magic-campus focus replace --body focus.json
magic-campus notification list --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 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 group get --group g1,g2
magic-campus im group members --group g1 --page 1 --page-size 100
magic-campus im group create --space s1 --name 小组 --owner 10001 --group-id g_s1
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 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` 互斥。
- 写命令不需要 `--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. Pagination/search are not invented.

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.
