このページは英語から機械翻訳されています。英語の原文を読む。

パッケージ API

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

2026年11月19日に更新 Markdownで表示

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

型

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

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

名前空間

名前空間機能ステータス
envホスト(desktop または cli)、アプリバージョン、プラットフォーム、nodeCommand、システムプロキシ経由の fetch、openExternal、クリップボード(デスクトップ)安定
commandsコマンドとスラッシュコマンドの登録・実行、when コンテキストキーの設定安定
capabilitiesTools スイッチのステータス、有効化、チャットごとのアタッチ安定
mcpこのプロジェクト用の MCP サーバーを登録安定
agentエージェントツールをメモリ内で提供(registerProvider)安定
gameEnginesゲームエンジンを実装(registerEngine、host)0.4.0 以降安定
settings設定の読み書き、変更の監視安定
projectプロジェクトのパスと getInfo()(エンジン、エンジンバージョン、フォルダ内のエンジンプロジェクト)安定
packages他のパッケージとそのエクスポート(all、get、getExports)安定
claudeこのプロジェクトのチャットに Claude Code プラグインフォルダを追加(registerPlugin)安定
editor接続中のエンジンエディタのツール。プロバイダーがアタッチされているチャットで利用可能安定
accountサインイン中のアカウントのケイパビリティカタログ(getSnapshot)安定
mediacontributes.mediaProviders で宣言したローカルメディアジェネレーターを登録(registerProvider)安定
windowメッセージ、クイックピック、入力ボックス、プログレス、ステータスバー、WebView、ツリービュー、カスタムエディタ安定、デスクトップ
tutorialsアプリ内ヒントのリクエストと追跡安定、デスクトップ
sessionslist()、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 が引き上げられた後のみです。

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

{ "enabledApiProposals": ["forms"] }
プロポーザルメンバー
formswindow.showForm
alertswindow.showAlert
sessionssessions.getTranscript、sendPrompt、create、focusComposer
sessionConfigurationチャットごとのパッケージ設定とToolsモジュール(sessions.getConfiguration、updateConfiguration、registerToolStateProvider、…)
appFocuswindow.keepInFront
storage、downloads、hardwareblobストア、ダウンロードマネージャー、ハードウェアプローブ
backgroundTasks、subscriptions、workHoldstasks.*、subscriptions.open、work.hold
paidOperations、mockJobs有料のサーバージョブ(AI Game Dev自身のプロバイダーパッケージのみ)とその開発用シミュレーション

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

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で起動される独自のスクリプトです。

{
  "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サーバー。 何かが起動して初めてアドレスがわかるサーバー(外部アプリのポートなど)向けです。

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

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

{
  "contributes": {
    "capabilities": [{ "id": "acme.helper", "label": "Helper", "description": "Helper tools", "defaultEnabled": true }],
    "agentProviders": [{ "id": "acme.helper.agent", "serverName": "acme--helper", "capabilityId": "acme.helper" }]
  }
}
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を設定します。アプリはスイッチ上にステータスを表示し、アクティベーションハンドラーを呼び出します。

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) } }; }
  }),
);

設定

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で宣言する必要があります。書き込みはすべて宣言に照らして検証されます。

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

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ページです。同じページが、ペイン、サイドパネルのタブ、または専用ウィンドウで動作します。

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 });
// 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()を提供します。

ツリービュー

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になります。項目にはチェックボックス、バッジ、クリックコマンドを持たせられます。

カスタムエディター

{ "contributes": { "customEditors": [{ "viewType": "acme.level-tools.level", "displayName": "Level preview", "selector": [{ "filenamePattern": "*.level.json" }], "priority": "default" }] } }
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)は、エクスプローラーでクリックしたときと同じように、プロジェクトのファイルをプレビューに表示します。

チュートリアル

{ "contributes": { "tutorials": [{ "id": "acme.level-tools.intro", "title": "Count collectibles", "anchor": "slashCommand:/collectibles", "markdown": "tutorials/intro.md" }] } }
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 で既読状態を読み書きできます。

保存される状態

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 を比較して引き上げるのはあなたの役目です。