包 API
AI Game Dev 包的 ctx.aigd API:各命名空间、稳定与提案成员、仅桌面端调用,以及工具、UI 与状态的示例。
你的包代码通过一个对象访问应用:ctx.aigd,它被传给 activate(ctx)。本页列出它的命名空间,说明哪些成员是稳定的、哪些是提案中的,并展示大多数包会用到的调用示例:命令、斜杠命令、智能体工具、设置、消息、Web 视图、树视图、自定义编辑器、教程和存储状态。包 API 版本为 0.4.0。
类型
gamedev pkg init 会把整个 API 写成一个自包含文件 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.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 窗口的错误列表中记录错误 |
命名空间
| 命名空间 | 作用 | 状态 |
|---|---|---|
env | 宿主(desktop 或 cli)、应用版本、平台、nodeCommand、通过系统代理的 fetch、openExternal、剪贴板(桌面端) | 稳定 |
commands | 注册并运行命令和斜杠命令,设置 when 上下文键 | 稳定 |
capabilities | 你的工具开关的状态、激活以及按聊天附加 | 稳定 |
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 | 消息、快速选择、输入框、进度、状态栏、Web 视图、树视图、自定义编辑器 | 稳定,桌面端 |
tutorials | 请求并跟踪应用内提示 | 稳定,桌面端 |
sessions | list()、active() 和实时事件是稳定的;对话记录、提示词和按聊天配置是提案中的 | 混合 |
storage、downloads、hardware | 应用的 blob 存储、经过校验的下载和硬件探测 | 提案中 |
tasks、subscriptions、work | 后台任务观察、长时间运行的工作、工作占用 | 提案中 |
在 aigd.d.ts 中标记为 @desktop 的成员在 CLI 上不起作用:它们会解析为 undefined 或返回一个无作用的对象,并且宿主会记录一行日志。当你的包需要在终端中表现不同时,请检查 aigd.env.host。
稳定与提案 API
稳定成员在每个应用版本中都保持其含义。变更仅为新增;只有在至少两个次版本的应用发布中给出弃用警告(在 gamedev pkg logs 中每个包每个会话一行)并同时提高应用加载的最旧 engines.aigd 之后,稳定成员才会被移除。
提案成员可能会在任何版本中更改或消失。要调用此类成员,请声明其提案;未声明就调用会失败,并给出指明该提案的消息:
{ "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 自有的 provider 包)及其开发阶段的模拟 |
命令与斜杠命令
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(),以及 cancelled——一个在用户按下 Esc 或 Stop 时兑现的 promise。斜杠命令在桌面端聊天和 CLI 中行为一致。你的包可以运行的应用命令包括 aigd.packages.open、aigd.packages.reload、aigd.packages.checkForUpdates、aigd.session.focus、aigd.settings.open 和 aigd.tutorials.show。
为 agent 提供工具
声明式 MCP server。 最简单的方式:声明该 server,以及一个按会话开启它的能力。无需编写代码;该 server 就是由应用的 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 server。 适用于只有某个东西启动之后你才知道其地址的 server(例如外部应用的端口):
await aigd.mcp.registerServer("acme--level-tools", { type: "http", url: `http://127.0.0.1:${port}/mcp` });由你的代码提供工具。 agent provider 把工具保留在你的包中,无需 server 进程。声明它及其所属的能力,然后注册它:
{
"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 }] }),
}));工具的 input schema 必须以 object 为根,顶层不能出现 oneOf、anyOf 或 allOf。结果可以携带文本和图像({ type: "image", data, mimeType },PNG、JPEG 或 WebP);未通过应用检查的图像会被替换为一条提示,而绝不会报错。默认的工具超时时间为 60 秒(executionTimeoutMs,最长一小时)。
带状态的能力。 当开启某个能力需要耗时操作(启动外部应用)时,在该能力上设置 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)会打开一个可调整大小的原生窗口,每个项目中每种视图类型各一个。其页面运行在严格的内容安全策略下:仅限包自身的文件,无网络,禁止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。markdown 最多可带 8 个 media 文件,也可以用 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 由你自己比较并提升。
相关页面
- 包清单参考,了解这些调用所搭配的声明。
- 生命周期、宿主与权限,了解你的代码何时运行以及它可以做什么。
- 游戏引擎包,了解
aigd.gameEngines。