Package API

The ctx.aigd API of AI Game Dev packages: every namespace, stable versus proposed members, desktop-only calls, and working examples for tools, UI and state.

Updated November 19, 2026 View as Markdown

Your package's code reaches the app through one object, ctx.aigd, handed to activate(ctx). This page lists its namespaces, says which members are stable and which are proposed, and shows working examples of the calls most packages make: commands, slash commands, agent tools, settings, messages, webviews, tree views, custom editors, tutorials and stored state. The package API is version 0.4.0.

Types

gamedev pkg init writes the whole API as one self-contained file, src/types/aigd.d.ts, generated from the app's own contract and matching the app version that wrote it. TypeScript imports it; JavaScript uses it from 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) { /* … */ };

A newer gamedev pkg init in a scratch folder gives you a newer copy of the types. An npm types package (@ai-game-dev/package-api) is prepared but not published yet.

Every call crosses a process boundary (your code runs in the app's Extension Host), so arguments and results must be JSON values, and every method that talks to the app is async. The few synchronous members (env, project.path, settings.get) read state the app pushed when the package started.

The context

MemberWhat it is
ctx.aigdThe API (below)
ctx.packageThis package: id, publisher, name, version, displayName, dir, manifest
ctx.subscriptionsPush every Disposable here; the app disposes them when the package stops
ctx.globalState, ctx.projectStateSmall key-value stores for this computer, and for this project on this computer
ctx.globalStoragePath, ctx.projectStoragePathFolders your package may write to
ctx.logdebug, info, warn, error: lines tagged pkg:<id> in the app log
ctx.asAbsolutePath(rel)A path inside the package folder
ctx.reportError(err, subject?)Record an error in the Packages window's Errors list

Namespaces

NamespaceWhat it doesStatus
envHost (desktop or cli), app version, platform, nodeCommand, fetch through the system proxy, openExternal, clipboard (desktop)Stable
commandsRegister and run commands and slash commands, set when context keysStable
capabilitiesStatus, activation and per-chat attachment of your Tools switchesStable
mcpRegister MCP servers for this projectStable
agentServe agent tools in memory (registerProvider)Stable
gameEnginesImplement a game engine (registerEngine, host)Stable since 0.4.0
settingsRead and write your settings, watch changesStable
projectThe project path and getInfo() (engine, engine version, the engine projects in the folder)Stable
packagesOther packages and their exports (all, get, getExports)Stable
claudeAdd a Claude Code plugin folder to this project's chats (registerPlugin)Stable
editorThe connected engine editor's tools, for chats your provider is attached toStable
accountThe signed-in account's capability catalog (getSnapshot)Stable
mediaRegister a local media generator declared in contributes.mediaProviders (registerProvider)Stable
windowMessages, quick picks, input boxes, progress, status bar, webviews, tree views, custom editorsStable, desktop
tutorialsRequest and track in-app tipsStable, desktop
sessionslist(), active() and live events are stable; transcripts, prompts and per-chat configuration are proposedMixed
storage, downloads, hardwareThe app's blob store, verified downloads and hardware probeProposed
tasks, subscriptions, workBackground task observation, long-lived work, work holdsProposed

Members marked @desktop in aigd.d.ts do nothing on the CLI: they resolve to undefined or return an inert object, and the host logs one line. Check aigd.env.host when your package should behave differently in the terminal.

Stable and proposed API

A stable member keeps its meaning in every app release. Changes are additions only; a stable member is removed only after at least two minor app releases of deprecation warnings (one line per package per session in gamedev pkg logs), together with a raise of the oldest engines.aigd the app loads.

A proposed member may change or disappear in any release. To call one, declare its proposal; a call without the declaration fails with a message naming the proposal:

{ "enabledApiProposals": ["forms"] }
ProposalMembers
formswindow.showForm
alertswindow.showAlert
sessionssessions.getTranscript, sendPrompt, create, focusComposer
sessionConfigurationper-chat package configuration and Tools modules (sessions.getConfiguration, updateConfiguration, registerToolStateProvider, …)
appFocuswindow.keepInFront
storage, downloads, hardwarethe blob store, the download manager, the hardware probe
backgroundTasks, subscriptions, workHoldstasks.*, subscriptions.open, work.hold
paidOperations, mockJobspaid server jobs (AI Game Dev's own provider packages only) and their development simulation

Commands and slash commands

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

A slash command gets the text after its name (inv.args), the chat it was typed in (inv.sessionId), say() for live lines and cancelled, a promise that settles when the user presses Esc or Stop. Slash commands work the same in the desktop chat and in the CLI. App commands your package may run include aigd.packages.open, aigd.packages.reload, aigd.packages.checkForUpdates, aigd.session.focus, aigd.settings.open and aigd.tutorials.show.

Give the agent tools

An MCP server, declared. The simplest way: declare the server and a capability that switches it on per chat. No code needed; the server is your own script started with the app's 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"] }
    }
  }
}

An MCP server, registered at run time. For a server whose address you only know once something has started (an external app's port):

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

Tools served from your code. An agent provider keeps the tools in your package, with no server process. Declare it with its capability, then register it:

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

A tool's input schema must have an object root, without a top-level oneOf, anyOf or allOf. Results may carry text and images ({ type: "image", data, mimeType }, PNG, JPEG or WebP); an image that fails the app's checks is replaced by a note, never an error. The default tool deadline is 60 seconds (executionTimeoutMs, up to one hour).

A capability with a status. Set statusful: true on the capability when turning it on takes work (starting an external app). The app then shows your status on the switch and calls your activation handler:

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

Settings

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

Keys are your own (without the package prefix) and must be declared in contributes.settings. Every write is validated against the declaration.

Messages, pickers and progress

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

On the CLI, messages print as system lines; a modal message, a quick pick or an input box becomes a terminal prompt while your slash command runs. Outside a slash command the CLI refuses prompts with a PromptRefusedError (code prompt_refused), so a package that asks questions should ask them from a slash command or check aigd.env.host.

Webviews: panels, side views and windows

A webview is your own HTML page inside the app (desktop). The same page works in a pane, a side-panel tab or its own window:

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
  • Side-panel tab: declare { "id": "acme.level-tools.side", "name": "Levels", "type": "webview" } under contributes.views.right and register aigd.window.registerWebviewViewProvider("acme.level-tools.side", { resolveWebviewView(view) { view.webview.html = page(); } }). "titleBar": "hidden" lets your page draw its own header.
  • Own window: aigd.window.createWebviewWindow(viewType, title) opens a resizable native window, one per view type per project. Its page runs under a strict content security policy: the package's own files only, no network, no eval.
  • Theme: the page gets <html data-theme="light|dark"> and the app's palette as --aigd-* CSS variables (--aigd-bg, --aigd-surface, --aigd-text, --aigd-primary, …), re-sent on every theme switch.
  • Page API: acquireAigdApi() gives postMessage, getState, setState, executeCommand (your own commands and app commands), getContext() and close().

Tree views

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

The view is declared with "type": "tree" in contributes.views. contextValue becomes viewItem for view/item/context menus; items can carry checkboxes, badges and a click command.

Custom editors

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

A default editor replaces the app's own preview for matching files; an option editor appears under Open With. Documents are read-only from the app's side: your package writes files itself, and the pane reloads when the file changes on disk. aigd.window.openPreview(path) shows a project file in the preview, as a click in the Explorer does.

Tutorials

{ "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"));

A tip is shown once per user, at a calm moment, pointing at its anchor: capability:, statusBar:, view:, slashCommand:, command: or menu: followed by an id, composer, or none. markdown with up to 8 media files, or a webview page for rich content. request(id, { force: true }) shows it again; isSeen and setSeen read and set the seen state.

Stored state

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 is shared by every project on this computer; projectState belongs to this project on this computer. Both survive updates and removal (re-adding the package restores them); Remove data in the Packages window deletes them. The app never migrates your data: dataVersion is yours to compare and raise.