# リモート セッション

リモート セッションを使用すると、ユーザーは Mission Control 経由でGitHub Web およびモバイルからCopilot セッションにアクセスできます。 有効にすると、SDK は各セッションを Mission Control に接続し、リンクまたは QR コードとして共有できる URL を生成します。

<!-- markdownlint-disable GHD046 GHD005 -->

<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->

GitHubホスト型コンピューティングでのセッションの実行については、[クラウド セッション](/ja/copilot/how-tos/copilot-sdk/features/cloud-sessions) を参照してください。

## Prerequisites

* ユーザーは認証されている必要があります (GitHub トークンまたはログイン ユーザー)
* セッションの作業ディレクトリは、GitHub リポジトリである必要があります

## リモート セッションの有効化

### 常時オン（クライアントレベル）

クライアントの作成時に `remote: true` を設定します。 GitHub リポジトリ内のすべてのセッションで、リモート URL が自動的に取得されます。

<!-- tabs:start -->

#### TypeScript

<!-- docs-validate: skip -->

```typescript
import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient({ remote: true });
const session = await client.createSession({
  workingDirectory: "/path/to/github-repo",
  onPermissionRequest: async () => ({ allowed: true }),
});

session.on("session.info", (event) => {
  if (event.data.infoType === "remote") {
    console.log("Remote URL:", event.data.url);
  }
});
```

#### Python

<!-- docs-validate: skip -->

```python
from copilot import CopilotClient

client = CopilotClient(enable_remote_sessions=True)
session = await client.create_session(
    working_directory="/path/to/github-repo",
    on_permission_request=lambda req: {"allowed": True},
)

def on_event(event):
    if event.type == "session.info" and event.data.info_type == "remote":
        print(f"Remote URL: {event.data.url}")

session.on(on_event)
```

#### Go

<!-- docs-validate: skip -->

```golang
client, _ := copilot.NewClient(&copilot.ClientOptions{Remote: true})
session, _ := client.CreateSession(ctx, &copilot.SessionConfig{
    WorkingDirectory: "/path/to/github-repo",
    OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) {
        return &rpc.PermissionDecisionApproveOnce{}, nil
    },
})

session.On(func(event copilot.SessionEvent) {
    if event.Type == "session.info" {
        // Check infoType and extract URL
    }
})
```

#### C\#

<!-- docs-validate: skip -->

```csharp
var client = new CopilotClient(new CopilotClientOptions { Remote = true });
var session = await client.CreateSessionAsync(new SessionConfig
{
    WorkingDirectory = "/path/to/github-repo",
    OnPermissionRequest = (req, inv) =>
        Task.FromResult(PermissionDecision.ApproveOnce()),
});

session.On((SessionEvent e) =>
{
    if (e is SessionInfoEvent info && info.Data.InfoType == "remote")
    {
        Console.WriteLine($"Remote URL: {info.Data.Url}");
    }
});
```

#### Rust

<!-- docs-validate: skip -->

```rust
use github_copilot_sdk::{Client, ClientOptions, SessionConfig};
use github_copilot_sdk::handler::PermissionResult;

let client = Client::start(
    ClientOptions::new().with_enable_remote_sessions(true)
).await?;
let session = client.create_session(
    SessionConfig::new("/path/to/github-repo")
        .with_permission_handler(|_req, _inv| async {
            Ok(PermissionResult::approve_once())
        }),
).await?;

let mut events = session.subscribe();
while let Ok(event) = events.recv().await {
    if event.event_type == "session.info" {
        // Check info_type and extract URL
    }
}
```

<!-- tabs:end -->

### オンデマンド (セッションごとの切り替え)

`session.rpc.remote.enable()`を使用してセッションの途中でリモート アクセスを開始し、`session.rpc.remote.disable()`して停止します。 これは、CLI の `/remote on` コマンドと `/remote off` コマンドと同じです。

<!-- tabs:start -->

#### TypeScript

<!-- docs-validate: skip -->

```typescript
const result = await session.rpc.remote.enable();
console.log("Remote URL:", result.url);

// Later: stop sharing
await session.rpc.remote.disable();
```

#### Python

<!-- docs-validate: skip -->

```python
result = await session.rpc.remote.enable()
print(f"Remote URL: {result.url}")

# Later: stop sharing
await session.rpc.remote.disable()
```

#### Go

<!-- docs-validate: skip -->

```golang
result, err := session.RPC.Remote.Enable(ctx)
if result.URL != nil {
    fmt.Println("Remote URL:", *result.URL)
}

// Later: stop sharing
err = session.RPC.Remote.Disable(ctx)
```

#### C\#

<!-- docs-validate: skip -->

```csharp
var result = await session.Rpc.Remote.EnableAsync();
Console.WriteLine($"Remote URL: {result.Url}");

// Later: stop sharing
await session.Rpc.Remote.DisableAsync();
```

#### Rust

<!-- docs-validate: skip -->

```rust
let result = session.rpc().remote().enable().await?;
if let Some(url) = &result.url {
    println!("Remote URL: {url}");
}

// Later: stop sharing
session.rpc().remote().disable().await?;
```

<!-- tabs:end -->

## QR コードの生成

リモート URL は、モバイル アクセスを容易にする QR コードとしてレンダリングできます。 SDK には URL が用意されています。任意の QR コード ライブラリを使用します。

* **TypeScript**: [qrcode](https://www.npmjs.com/package/qrcode)
* **Python**: [qrcode](https://pypi.org/project/qrcode/)
* **Go**: [go-qrcode](https://github.com/skip2/go-qrcode)
* **C#**: [QRCoder](https://www.nuget.org/packages/QRCoder)
* **Rust**: [qrcode](https://crates.io/crates/qrcode)

## メモ

* `remote` クライアント オプションは、SDK が CLI プロセスを生成する場合にのみ適用されます。
  `cliUrl`経由で外部サーバーに接続する場合は無視されます。
* 作業ディレクトリがGitHub リポジトリでない場合、リモート セットアップはサイレント モードでスキップされるか (常時オン モード)、エラー (オンデマンド モード) が返されます。
* リモート セッションには認証が必要です。
  `gitHubToken`または`useLoggedInUser`が構成されていることを確認します。