# 连接插件账号

为需要外部身份认证的插件创建账号连接，发起浏览器 OAuth 或设备码授权流程，并轮询确认授权完成状态。

(sdk-ai-studio-plugin-account-flow)=
## 任务流程

```text
查询插件发布的连接需求与 OAuth 配置
               │
               ▼
创建插件账号连接并发起 OAuth 授权
               │
               ▼
在浏览器完成登录授权（或输入用户码）
               │
               ▼
轮询并确认连接授权状态
```

(sdk-ai-studio-plugin-account-prepare)=
## 准备

1. 已完成 [使用 SDK](../../../quickstart/ai-studio/sdk.md) 中的服务地址、个人访问令牌与工作区配置。
2. 调用 `service.list_plugin_releases(sdk.with_query_param("namespace", "system"))` 与 `service.get_plugin_release(release_id, sdk.with_query_param("namespace", "system"))`（Go 为 `ListPluginReleases` 与 `GetPluginRelease`）查询目标插件发布，记录发布命名空间（`RELEASE_NAMESPACE`）、发布 ID（`RELEASE_ID`）、连接需求名称（`CONNECTION_REQUIREMENT`）及驱动为 `oauth` 的授权配置标识（`CONNECTION_PROFILE`）。
3. 准备对应外部服务的登录账号，用于在浏览器中完成身份验证与授权确认。

(sdk-ai-studio-plugin-account-connect)=
## 创建连接并发起授权

若工作区中已有可复用的插件账号连接，可通过连接列表读取并直接复用。以下示例调用 `create_plugin_connection`（Go 为 `CreatePluginConnection`）新建连接，再调用 `begin_plugin_oauth`（Go 为 `BeginPluginOAuth`）获取授权链接与尝试参数。

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
import os

import moi_product_sdk as sdk

client = sdk.new_with_personal_access_token(
    os.environ["PRODUCT_API_BASE_URL"],
    os.environ["PRODUCT_API_KEY"],
)
service = client.agents(os.environ["WORKSPACE_ID"])

connection = service.create_plugin_connection(
    sdk.PluginCreateConnectionRequest(
        release_namespace=os.environ["RELEASE_NAMESPACE"],
        release_id=os.environ["RELEASE_ID"],
        requirement=os.environ["CONNECTION_REQUIREMENT"],
        profile=os.environ["CONNECTION_PROFILE"],
        name="My plugin account",
    )
)
action = service.begin_plugin_oauth(connection.id, connection.version)
print("Connection:", connection.id, "Version:", connection.version)
print("Grant:", action.grant)
print("Open in browser:", action.authorization_url)
print("User code:", action.user_code)
print("Attempt:", action.attempt_id, "Poll after:", action.poll_after)
```

::::

::::{tab-item} Go
:sync: go

```go
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	sdk "github.com/matrixorigin/matrixflow/sdk/go-sdk"
)

func main() {
	ctx := context.Background()
	client, err := sdk.NewWithPersonalAccessToken(
		os.Getenv("PRODUCT_API_BASE_URL"),
		os.Getenv("PRODUCT_API_KEY"),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	service := client.Agents(os.Getenv("WORKSPACE_ID"))
	connection, err := service.CreatePluginConnection(ctx, &sdk.PluginCreateConnectionRequest{
		ReleaseNamespace: os.Getenv("RELEASE_NAMESPACE"),
		ReleaseId:        os.Getenv("RELEASE_ID"),
		Requirement:      os.Getenv("CONNECTION_REQUIREMENT"),
		Profile:          os.Getenv("CONNECTION_PROFILE"),
		Name:             "My plugin account",
	})
	if err != nil {
		log.Fatal(err)
	}
	action, err := service.BeginPluginOAuth(ctx, connection.GetId(), int(connection.GetVersion()))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Connection:", connection.GetId(), "Version:", connection.GetVersion())
	fmt.Println("Grant:", action.GetGrant())
	fmt.Println("Open in browser:", action.GetAuthorizationUrl())
	fmt.Println("User code:", action.GetUserCode())
	fmt.Println("Attempt:", action.GetAttemptId(), "Poll after:", action.GetPollAfter())
}
```

::::

:::::

保存返回的连接 `id`、`version`、`grant` 以及非空的 `attempt_id`：

- 当 `grant` 为 `browser_handoff` 时，打开返回的 `authorization_url` 在产品浏览器页面中继续操作，此时 `attempt_id` 为空。
- 当返回非空 `attempt_id` 时，打开 `authorization_url` 完成外部服务授权（设备码模式还需填入 `user_code`），随后按该 `attempt_id` 推进并检查授权状态。

(sdk-ai-studio-plugin-account-status)=
## 查询并推进授权结果

在浏览器完成登录授权后，接续上一步保存的 `connection` 与 `action` 读取当前连接的授权状态；当状态仍为 `pending` 且存在 `attempt_id` 时，按返回的 `poll_after` 间隔调用 `poll_plugin_oauth`（Go 为 `PollPluginOAuth`）推进状态并限制总等待时长。

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
status = service.get_plugin_authorization(connection.id)
print("Status:", status.status)
if status.connection_version != connection.version:
    raise RuntimeError("Connection version changed; review latest state before continuing")

if status.status == "pending":
    attempt_id = action.attempt_id or status.attempt_id
    if attempt_id:
        progress = service.poll_plugin_oauth(
            connection.id,
            attempt_id,
            connection.version,
        )
        print(progress.status, progress.reason, progress.poll_after)
        status = service.get_plugin_authorization(connection.id)
        print("Authorization:", status.status)
    elif action.grant == "browser_handoff":
        print("Continue authorization in the product browser page")
    else:
        raise RuntimeError("Saved attempt ID is required before polling")
```

::::

::::{tab-item} Go
:sync: go

```go
status, err := service.GetPluginAuthorization(ctx, connection.GetId())
if err != nil {
	log.Fatal(err)
}
fmt.Println("Status:", status.GetStatus())
if status.GetConnectionVersion() != connection.GetVersion() {
	log.Fatal("connection version changed; review latest state before continuing")
}

if status.GetStatus() == "pending" {
	attemptID := action.GetAttemptId()
	if attemptID == "" {
		attemptID = status.GetAttemptId()
	}
	if attemptID != "" {
		progress, err := service.PollPluginOAuth(ctx, connection.GetId(), attemptID, int(connection.GetVersion()))
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(progress.GetStatus(), progress.GetReason(), progress.GetPollAfter())
		status, err = service.GetPluginAuthorization(ctx, connection.GetId())
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println("Authorization:", status.GetStatus())
	} else if action.GetGrant() == "browser_handoff" {
		fmt.Println("Continue authorization in the product browser page")
	} else {
		log.Fatal("saved attempt ID is required before polling")
	}
}
```

::::

:::::

(sdk-ai-studio-plugin-account-limit)=
## 限制和注意事项

- `get_plugin_authorization` 不一定返回 OAuth `attempt_id`；进程重启或中断恢复时，应同时结合本地持久化的 `attempt_id` 与最新连接状态继续轮询。
- 连接版本号（`connection_version`）发生变更时，先重新核查当前连接配置，确认匹配后再执行后续轮询或绑定。
- 授权完成后可将连接绑定到对应插件安装实例并回读确认；如需断开已授权的插件账号，调用 `service.disconnect_plugin_connection(connection_id, expected_generation)`（Go 为 `service.DisconnectPluginConnection(ctx, connectionID, expectedGeneration)`）。

(sdk-ai-studio-plugin-account-next)=
## 下一步

- [检查与导入技能包](检查与导入技能包.md)
- [调用智能体与跟踪任务](调用智能体并跟踪任务.md#sdk-ai-studio-agent-task-send)
