# パッケージ API — AI Game DevアプリとCLI · AI Game Developer Wiki

AI Game Dev パッケージの ctx.aigd API：すべての名前空間、安定版と提案中のメンバー、デスクトップ専用の呼び出し、ツール・UI・状態の実例を解説します。

このページは英語から機械翻訳されています。[英語の原文を読む](https://ai-game.dev/docs/wiki/app/package-api)。

パッケージのコードは、`activate(ctx)` に渡される 1 つのオブジェクト `ctx.aigd` を通じてアプリにアクセスします。このページでは、その名前空間を一覧し、どのメンバーが安定版でどれが提案中かを示し、ほとんどのパッケージが使う呼び出しの実例を紹介します。コマンド、スラッシュコマンド、エージェントツール、設定、メッセージ、WebView、ツリービュー、カスタムエディタ、チュートリアル、保存された状態です。パッケージ API はバージョン 0.4.0 です。

## 型

`gamedev pkg init` は API 全体を 1 つの自己完結したファイル `src/types/aigd.d.ts` として書き出します。これはアプリ自身のコントラクトから生成され、書き出したアプリのバージョンと一致します。TypeScript ではインポートし、JavaScript では JSDoc から利用します：

```typescript
import type { PackageContext } from "./types/aigd";

export async function activate(ctx: PackageContext): Promise<void> {
  ctx.subscriptions.push(ctx.aigd.commands.registerCommand("acme.level-tools.hello", () => "hi"));
}

export function deactivate(): void {}
```

```javascript
/** @param {import("./types/aigd").PackageContext} ctx */
exports.activate = function activate(ctx) { /* … */ };
```

空のフォルダで新しい `gamedev pkg init` を実行すると、より新しい型のコピーが得られます。npm の型パッケージ（`@ai-game-dev/package-api`）は準備済みですが、まだ公開されていません。

すべての呼び出しはプロセスの境界を越えます（あなたのコードはアプリの Extension Host で実行されます）。そのため引数と戻り値は JSON 値である必要があり、アプリとやり取りするすべてのメソッドは非同期です。数少ない同期メンバー（`env`、`project.path`、`settings.get`）は、パッケージの起動時にアプリがプッシュした状態を読み取ります。

## コンテキスト

| メンバー | 内容 |
| --- | --- |
| `ctx.aigd` | API（下記） |
| `ctx.package` | このパッケージ：`id`、`publisher`、`name`、`version`、`displayName`、`dir`、`manifest` |
| `ctx.subscriptions` | すべての `Disposable` をここにプッシュします。パッケージの停止時にアプリが破棄します |
| `ctx.globalState`、`ctx.projectState` | このコンピューター用、およびこのコンピューター上のこのプロジェクト用の小さなキーバリューストア |
| `ctx.globalStoragePath`、`ctx.projectStoragePath` | パッケージが書き込んでよいフォルダ |
| `ctx.log` | `debug`、`info`、`warn`、`error`：アプリログに `pkg:<id>` タグ付きで出力される行 |
| `ctx.asAbsolutePath(rel)` | パッケージフォルダ内のパス |
| `ctx.reportError(err, subject?)` | Packages ウィンドウの Errors リストにエラーを記録します |

## 名前空間

| 名前空間 | 機能 | ステータス |
| --- | --- | --- |
| `env` | ホスト（`desktop` または `cli`）、アプリバージョン、プラットフォーム、`nodeCommand`、システムプロキシ経由の `fetch`、`openExternal`、クリップボード（デスクトップ） | 安定 |
| `commands` | コマンドとスラッシュコマンドの登録・実行、`when` コンテキストキーの設定 | 安定 |
| `capabilities` | Tools スイッチのステータス、有効化、チャットごとのアタッチ | 安定 |
| `mcp` | このプロジェクト用の MCP サーバーを登録 | 安定 |
| `agent` | エージェントツールをメモリ内で提供（`registerProvider`） | 安定 |
| `gameEngines` | ゲームエンジンを実装（`registerEngine`、`host`） | 0.4.0 以降安定 |
| `settings` | 設定の読み書き、変更の監視 | 安定 |
| `project` | プロジェクトのパスと `getInfo()`（エンジン、エンジンバージョン、フォルダ内のエンジンプロジェクト） | 安定 |
| `packages` | 他のパッケージとそのエクスポート（`all`、`get`、`getExports`） | 安定 |
| `claude` | このプロジェクトのチャットに Claude Code プラグインフォルダを追加（`registerPlugin`） | 安定 |
| `editor` | 接続中のエンジンエディタのツール。プロバイダーがアタッチされているチャットで利用可能 | 安定 |
| `account` | サインイン中のアカウントのケイパビリティカタログ（`getSnapshot`） | 安定 |
| `media` | `contributes.mediaProviders` で宣言したローカルメディアジェネレーターを登録（`registerProvider`） | 安定 |
| `window` | メッセージ、クイックピック、入力ボックス、プログレス、ステータスバー、WebView、ツリービュー、カスタムエディタ | 安定、デスクトップ |
| `tutorials` | アプリ内ヒントのリクエストと追跡 | 安定、デスクトップ |
| `sessions` | `list()`、`active()`、ライブイベントは安定。トランスクリプト、プロンプト、チャットごとの設定は提案中 | 混在 |
| `storage`、`downloads`、`hardware` | アプリの BLOB ストア、検証済みダウンロード、ハードウェアプローブ | 提案中 |
| `tasks`、`subscriptions`、`work` | バックグラウンドタスクの監視、長時間実行のワーク、ワークホールド | 提案中 |

`aigd.d.ts` で `@desktop` とマークされたメンバーは CLI では何もしません。`undefined` に解決されるか、無効なオブジェクトを返し、ホストは 1 行ログを出力します。ターミナルでパッケージの動作を変える場合は `aigd.env.host` を確認してください。

## 安定版 API と提案中 API

**安定**メンバーは、すべてのアプリリリースでその意味を保ちます。変更は追加のみです。安定メンバーが削除されるのは、少なくとも 2 つのマイナーアプリリリースにわたって非推奨警告（`gamedev pkg logs` にパッケージごと・セッションごとに 1 行）が出た後、かつアプリが読み込む最も古い `engines.aigd` が引き上げられた後のみです。

**提案中**メンバーは、どのリリースでも変更または削除される可能性があります。呼び出すには、そのプロポーザルを宣言する必要があります。宣言なしの呼び出しは、プロポーザル名を示すメッセージとともに失敗します：

```json
{ "enabledApiProposals": ["forms"] }
```

| プロポーザル | メンバー |
| --- | --- |
| `forms` | `window.showForm` |
| `alerts` | `window.showAlert` |
| `sessions` | `sessions.getTranscript`、`sendPrompt`、`create`、`focusComposer` |
| `sessionConfiguration` | チャットごとのパッケージ設定とToolsモジュール（`sessions.getConfiguration`、`updateConfiguration`、`registerToolStateProvider`、…） |
| `appFocus` | `window.keepInFront` |
| `storage`、`downloads`、`hardware` | blobストア、ダウンロードマネージャー、ハードウェアプローブ |
| `backgroundTasks`、`subscriptions`、`workHolds` | `tasks.*`、`subscriptions.open`、`work.hold` |
| `paidOperations`、`mockJobs` | 有料のサーバージョブ（AI Game Dev自身のプロバイダーパッケージのみ）とその開発用シミュレーション |

**注意**

コミュニティレジストリは、proposalを宣言するパッケージをすべて拒否します。proposalが必要なパッケージでも、GitHub、npm、またはフォルダから共有できます。詳しくは[パッケージの公開](https://ai-game.dev/ja/docs/wiki/app/publishing-packages#other-sources)を参照してください。

## コマンドとスラッシュコマンド

```typescript
const ID = "acme.level-tools";

ctx.subscriptions.push(
  aigd.commands.registerCommand(`${ID}.count`, async (...args) => {
    const n = await countCollectibles();
    await aigd.window.showInformationMessage(`${n} collectibles in this level`);
    return n;
  }),
  aigd.commands.registerSlashCommand("/collectibles", async (inv) => {
    inv.say("Counting…");                       // a system line in the chat, live
    const n = await countCollectibles(inv.args.trim());
    inv.say(`${n} collectibles.`);
  }),
);

await aigd.commands.setContext(`${ID}.hasLevel`, true);   // usable in when clauses
await aigd.commands.executeCommand("aigd.packages.open", { packageId: ID });
```

スラッシュコマンドは、名前の後に続くテキスト（`inv.args`）、入力されたチャット（`inv.sessionId`）、ライブ行を表示するための`say()`、そしてユーザーがEscまたはStopを押すと解決されるpromiseである`cancelled`を受け取ります。スラッシュコマンドはデスクトップチャットでもCLIでも同じように動作します。パッケージから実行できるアプリコマンドには、`aigd.packages.open`、`aigd.packages.reload`、`aigd.packages.checkForUpdates`、`aigd.session.focus`、`aigd.settings.open`、`aigd.tutorials.show`があります。

## エージェントにツールを与える

**宣言するMCPサーバー。** 最も簡単な方法は、サーバーと、チャットごとにそれを有効化するケイパビリティを宣言することです。コードは不要で、サーバーはアプリのNodeで起動される独自のスクリプトです。

```json
{
  "contributes": {
    "capabilities": [
      { "id": "acme.level-tools", "label": "Level tools", "description": "Counts collectibles in level files.", "mcpServer": "acme--level-tools" }
    ],
    "mcpServers": {
      "acme--level-tools": { "command": "${node}", "args": ["${packageDir}/server.js"] }
    }
  }
}
```

**実行時に登録するMCPサーバー。** 何かが起動して初めてアドレスがわかるサーバー（外部アプリのポートなど）向けです。

```typescript
await aigd.mcp.registerServer("acme--level-tools", { type: "http", url: `http://127.0.0.1:${port}/mcp` });
```

**コードから提供するツール。** エージェントプロバイダーは、サーバープロセスなしでツールをパッケージ内に保持します。ケイパビリティとともに宣言してから、登録します。

```json
{
  "contributes": {
    "capabilities": [{ "id": "acme.helper", "label": "Helper", "description": "Helper tools", "defaultEnabled": true }],
    "agentProviders": [{ "id": "acme.helper.agent", "serverName": "acme--helper", "capabilityId": "acme.helper" }]
  }
}
```

```typescript
ctx.subscriptions.push(await aigd.agent.registerProvider("acme.helper.agent", {
  getTools: () => [{
    name: "status",
    description: "Read the helper's status",
    inputSchema: { type: "object", properties: {}, additionalProperties: false },
  }],
  getInstructions: () => "Use the helper's status tool when working in this project.",
  invokeTool: async (name, args, context) => ({ content: [{ type: "text", text: context.project.path }] }),
}));
```

ツールの入力スキーマはオブジェクトをルートに持ち、トップレベルに`oneOf`、`anyOf`、`allOf`を含めてはいけません。結果にはテキストと画像（`{ type: "image", data, mimeType }`、PNG、JPEG、WebP）を含められます。アプリのチェックに通らない画像はエラーにはならず、注記に置き換えられます。ツールのデフォルトの期限は60秒です（`executionTimeoutMs`、最大1時間）。

**ステータス付きのケイパビリティ。** 有効化に手間がかかる場合（外部アプリの起動など）は、ケイパビリティに`statusful: true`を設定します。アプリはスイッチ上にステータスを表示し、アクティベーションハンドラーを呼び出します。

```typescript
ctx.subscriptions.push(
  aigd.capabilities.registerStatusProvider("acme.level-tools", async () =>
    (await isRunning()) ? { phase: "connected", detail: "Editor 4.2" } : { phase: "idle" }),
  aigd.capabilities.registerActivationHandler("acme.level-tools", async (req) => {
    req.progress("Starting the level server…");
    try { await start(); return { ok: true }; }
    catch (e) { return { ok: false, failure: { code: "start-failed", text: String(e) } }; }
  }),
);
```

## 設定

```typescript
const quality = aigd.settings.get<string>("quality") ?? "draft";
await aigd.settings.update("quality", "final", "project");   // user, project or local
ctx.subscriptions.push(aigd.settings.onDidChange((e) => ctx.log.info(`${e.key} is now ${String(e.value)}`)));
```

キーは独自のもの（パッケージプレフィックスなし）で、`contributes.settings`で宣言する必要があります。書き込みはすべて宣言に照らして検証されます。

## メッセージ、ピッカー、プログレス

```typescript
const choice = await aigd.window.showWarningMessage("Overwrite the export?", { modal: true }, "Overwrite", "Keep");
const level = await aigd.window.showQuickPick(["forest", "cave", "castle"], { title: "Export which level?" });
const name = await aigd.window.showInputBox({ prompt: "File name", value: "level-1" });

await aigd.window.withProgress({ title: "Exporting", cancellable: true }, async (progress, cancelled) => {
  progress.report({ message: "Meshes", increment: 50 });
  progress.report({ message: "Textures", increment: 50 });
});

const item = aigd.window.createStatusBarItem("acme.level-tools.status", { alignment: "left" });
item.text = "3 levels";
item.command = "acme.level-tools.count";
item.show();
ctx.subscriptions.push(item);
```

CLIでは、メッセージはシステム行として出力されます。モーダルメッセージ、クイックピック、入力ボックスは、スラッシュコマンドの実行中はターミナルのプロンプトになります。スラッシュコマンドの外では、CLIは`PromptRefusedError`（コード`prompt_refused`）でプロンプトを拒否するため、質問を行うパッケージは、スラッシュコマンドから質問するか、`aigd.env.host`を確認してください。

## Webview: パネル、サイドビュー、ウィンドウ

webviewはアプリ（デスクトップ）内の独自のHTMLページです。同じページが、ペイン、サイドパネルのタブ、または専用ウィンドウで動作します。

```typescript
const panel = aigd.window.createWebviewPanel("acme.level-tools.map", "Level map");
const script = panel.webview.asWebviewUri(ctx.asAbsolutePath("dist/map.js"));
panel.webview.html = `<!doctype html><html><body><canvas id="map"></canvas>
  <script type="module" src="${script}"></script></body></html>`;
panel.webview.onDidReceiveMessage((msg) => ctx.log.info(`page says ${JSON.stringify(msg)}`));
await panel.webview.postMessage({ type: "level", tiles });
```

```javascript
// dist/map.js, inside the page
const api = acquireAigdApi();
api.postMessage({ type: "ready" });
window.addEventListener("message", (e) => draw(e.data));
api.setState({ zoom: 2 });             // restored with the pane after a relaunch
```

- **サイドパネルのタブ:** `contributes.views.right`の下に`{ "id": "acme.level-tools.side", "name": "Levels", "type": "webview" }`を宣言し、`aigd.window.registerWebviewViewProvider("acme.level-tools.side", { resolveWebviewView(view) { view.webview.html = page(); } })`を登録します。`"titleBar": "hidden"`を指定すると、ページが独自のヘッダーを描画できます。
- **専用ウィンドウ:** `aigd.window.createWebviewWindow(viewType, title)`は、サイズ変更可能なネイティブウィンドウを開きます（プロジェクトごとにビュータイプあたり1つ）。そのページは厳格なコンテンツセキュリティポリシーの下で動作し、パッケージ自身のファイルのみ、ネットワークなし、`eval`なしです。
- **テーマ:** ページは`<html data-theme="light|dark">`と、アプリのパレットを表す`--aigd-*` CSS変数（`--aigd-bg`、`--aigd-surface`、`--aigd-text`、`--aigd-primary`、…）を受け取り、テーマを切り替えるたびに再送されます。
- **ページAPI:** `acquireAigdApi()`は、`postMessage`、`getState`、`setState`、`executeCommand`（独自のコマンドとアプリコマンド）、`getContext()`、`close()`を提供します。

## ツリービュー

```typescript
const tree = aigd.window.createTreeView("acme.level-tools.levels", {
  treeDataProvider: {
    getChildren: async (parent) => parent
      ? listObjects(parent.id).map((o) => ({ id: o.id, label: o.name, icon: "$(box)" }))
      : listLevels().map((l) => ({ id: l.id, label: l.name, collapsible: "collapsed", contextValue: "level" })),
  },
});
tree.message = "3 levels";
ctx.subscriptions.push(tree);
```

ビューは`contributes.views`で`"type": "tree"`として宣言します。`contextValue`は`view/item/context`メニューの`viewItem`になります。項目にはチェックボックス、バッジ、クリックコマンドを持たせられます。

## カスタムエディター

```json
{ "contributes": { "customEditors": [{ "viewType": "acme.level-tools.level", "displayName": "Level preview", "selector": [{ "filenamePattern": "*.level.json" }], "priority": "default" }] } }
```

```typescript
ctx.subscriptions.push(aigd.window.registerCustomEditorProvider("acme.level-tools.level", {
  resolveCustomEditor(document, panel) {
    panel.webview.html = renderLevel(fs.readFileSync(document.path, "utf8"));
  },
}));
```

`default`エディターは、該当するファイルに対してアプリ標準のプレビューを置き換えます。`option`エディターは「プログラムから開く」に表示されます。ドキュメントはアプリ側からは読み取り専用です。ファイルの書き込みはパッケージ自身が行い、ディスク上のファイルが変更されるとペインが再読み込みされます。`aigd.window.openPreview(path)`は、エクスプローラーでクリックしたときと同じように、プロジェクトのファイルをプレビューに表示します。

## チュートリアル

```json
{ "contributes": { "tutorials": [{ "id": "acme.level-tools.intro", "title": "Count collectibles", "anchor": "slashCommand:/collectibles", "markdown": "tutorials/intro.md" }] } }
```

```typescript
ctx.subscriptions.push(aigd.tutorials.request("acme.level-tools.intro"));
```

ヒントはユーザーごとに一度だけ、落ち着いたタイミングで、アンカーを指して表示されます。アンカーは `capability:`、`statusBar:`、`view:`、`slashCommand:`、`command:`、`menu:` のいずれかに id を続けたもの、`composer`、または `none` です。リッチコンテンツには、最大 8 個の `media` ファイルを指定した `markdown` か、`webview` ページを使います。`request(id, { force: true })` を呼ぶと再表示され、`isSeen` と `setSeen` で既読状態を読み書きできます。

## 保存される状態

```typescript
const DATA = 2;
if ((ctx.globalState.dataVersion ?? 0) < DATA) {
  await migrate(ctx.globalState);
  await ctx.globalState.setDataVersion(DATA);
}
await ctx.projectState.update("lastExport", new Date().toISOString());
const last = ctx.projectState.get<string>("lastExport");
```

`globalState` はこのコンピューター上のすべてのプロジェクトで共有され、`projectState` はこのコンピューター上のこのプロジェクトに属します。どちらも更新や削除に耐えます（パッケージを再追加すると復元されます）。Packages ウィンドウの **Remove data** で削除されます。アプリがデータを移行することはありません。`dataVersion` を比較して引き上げるのはあなたの役目です。

## 関連ページ

- これらの呼び出しと対になる宣言については、[パッケージマニフェストリファレンス](https://ai-game.dev/ja/docs/wiki/app/package-manifest) を参照してください。
- コードが実行されるタイミングと実行できる内容については、[ライフサイクル、ホスト、権限](https://ai-game.dev/ja/docs/wiki/app/package-lifecycle) を参照してください。
- `aigd.gameEngines` については、[ゲームエンジンパッケージ](https://ai-game.dev/ja/docs/wiki/app/game-engine-packages) を参照してください。

---

Source (HTML): https://ai-game.dev/ja/docs/wiki/app/package-api

Machine-translated (ja) from the English page: https://ai-game.dev/docs/wiki/app/package-api
