# 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.

_Last updated: 2026-11-19_

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:

```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) { /* … */ };
```

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

| Member | What it is |
| --- | --- |
| `ctx.aigd` | The API (below) |
| `ctx.package` | This package: `id`, `publisher`, `name`, `version`, `displayName`, `dir`, `manifest` |
| `ctx.subscriptions` | Push every `Disposable` here; the app disposes them when the package stops |
| `ctx.globalState`, `ctx.projectState` | Small key-value stores for this computer, and for this project on this computer |
| `ctx.globalStoragePath`, `ctx.projectStoragePath` | Folders your package may write to |
| `ctx.log` | `debug`, `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

| Namespace | What it does | Status |
| --- | --- | --- |
| `env` | Host (`desktop` or `cli`), app version, platform, `nodeCommand`, `fetch` through the system proxy, `openExternal`, clipboard (desktop) | Stable |
| `commands` | Register and run commands and slash commands, set `when` context keys | Stable |
| `capabilities` | Status, activation and per-chat attachment of your Tools switches | Stable |
| `mcp` | Register MCP servers for this project | Stable |
| `agent` | Serve agent tools in memory (`registerProvider`) | Stable |
| `gameEngines` | Implement a game engine (`registerEngine`, `host`) | Stable since 0.4.0 |
| `settings` | Read and write your settings, watch changes | Stable |
| `project` | The project path and `getInfo()` (engine, engine version, the engine projects in the folder) | Stable |
| `packages` | Other packages and their exports (`all`, `get`, `getExports`) | Stable |
| `claude` | Add a Claude Code plugin folder to this project's chats (`registerPlugin`) | Stable |
| `editor` | The connected engine editor's tools, for chats your provider is attached to | Stable |
| `account` | The signed-in account's capability catalog (`getSnapshot`) | Stable |
| `media` | Register a local media generator declared in `contributes.mediaProviders` (`registerProvider`) | Stable |
| `window` | Messages, quick picks, input boxes, progress, status bar, webviews, tree views, custom editors | Stable, desktop |
| `tutorials` | Request and track in-app tips | Stable, desktop |
| `sessions` | `list()`, `active()` and live events are stable; transcripts, prompts and per-chat configuration are proposed | Mixed |
| `storage`, `downloads`, `hardware` | The app's blob store, verified downloads and hardware probe | Proposed |
| `tasks`, `subscriptions`, `work` | Background task observation, long-lived work, work holds | Proposed |

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:

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

| Proposal | Members |
| --- | --- |
| `forms` | `window.showForm` |
| `alerts` | `window.showAlert` |
| `sessions` | `sessions.getTranscript`, `sendPrompt`, `create`, `focusComposer` |
| `sessionConfiguration` | per-chat package configuration and Tools modules (`sessions.getConfiguration`, `updateConfiguration`, `registerToolStateProvider`, …) |
| `appFocus` | `window.keepInFront` |
| `storage`, `downloads`, `hardware` | the blob store, the download manager, the hardware probe |
| `backgroundTasks`, `subscriptions`, `workHolds` | `tasks.*`, `subscriptions.open`, `work.hold` |
| `paidOperations`, `mockJobs` | paid server jobs (AI Game Dev's own provider packages only) and their development simulation |

**Warning**

The community registry refuses every package that declares a proposal. A package that needs one can still be shared from GitHub, npm or a folder; see [Publishing packages](https://ai-game.dev/docs/wiki/app/publishing-packages#other-sources).

## Commands and slash commands

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

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:

```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"] }
    }
  }
}
```

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

```typescript
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:

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

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:

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

## Settings

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

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

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

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:

```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
```

- **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

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

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

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

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

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

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

```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` 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.

## Related pages

- [Package manifest reference](https://ai-game.dev/docs/wiki/app/package-manifest) for the declarations these calls pair with.
- [Lifecycle, hosts and permissions](https://ai-game.dev/docs/wiki/app/package-lifecycle) for when your code runs and what it may do.
- [Game engine packages](https://ai-game.dev/docs/wiki/app/game-engine-packages) for `aigd.gameEngines`.

---

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