ohpichamber-sdk
v1.1.0
Published
Contract for OhPiChamber guests: manifest parse and iframe host bridge.
Readme
ohpichamber-sdk
Build extensions for OhPiChamber: rail panels, background actions, slash commands, custom tool views, work-status sections, or local services. See Build an extension, Host API, SDK internals, and GUEST_SERVICES.md.
Extensions load on Web and Electron desktop. Hosted mobile and Capacitor mobile mark the guest catalog unsupported and do not load extensions or spawn services.
Device-scoped extension storage (scope: 'device') is local browser preference data partitioned by host runtime identity and extension installation; URL aliases do not share preferences, and saved host/relay connections follow host runtime identity rules.
Install
npm install ohpichamber-sdkShips compiled JS with .d.ts declarations; package version matches the target OhPiChamber release (e.g. 1.0.0). Panels connect over a private MessagePort bootstrap (v: 2, manifest apiVersion: 1); v1 window hello handshakes and v1 bootstrap announcements are dropped without granting a port or host state.
Monorepo development scripts
bun run --cwd packages/sdk build
bun run --cwd packages/sdk type-check
bun run --cwd packages/sdk test
bunx ohpichamber-guest-bundle panel/main.ts panel/main.jsPreview builds
Preview releases (npm install ohpichamber-sdk@preview) test unreleased SDK changes against matching development builds of OhPiChamber and do not imply compatibility with the published release of the same base version.
Maintainers publish previews via the Publish SDK preview GitHub Actions workflow_dispatch (branch/tag + unused positive preview number, e.g. 1 → 1.0.0-preview.1, NPM_TOKEN secret, optional dry_run), which validates imports, types, and the bundler without commits, release tags, or updating latest.
What you ship
Ship a folder containing:
package.jsonwith anohpichambermanifest blockpanel/index.html(panel markup)panel/main.js(single classic IIFE bundle; sandboxed iframes cannot load ES modules)
OhPiChamber never compiles TypeScript or source files. Bundle scripts with bunx ohpichamber-guest-bundle panel/main.ts panel/main.js (or esbuild --format=iife --platform=browser).
Install from Settings → Extensions → Add. Folder installs run in place (edit, rebuild, reload); .zip or https git/zip URLs copy built files into OhPiChamber's data folder. Git installs pin branches/tags via #<ref> (https://…/panel.git#v1) and update when version increases. See sdk.mdx and ./examples (16 examples).
Manifest
Git installs also accept SSH URLs ([email protected]:…, ssh://…). The fingerprint selector in Settings → Extensions chooses Global Identity or a server Git identity for installs and updates; on remote instances, SSH keys/agent must be available to the server process. See Extensions.
{
"name": "@acme/hello",
"version": "1.0.0",
"ohpichamber": {
"apiVersion": 1,
"engines": { "ohpichamber": ">=1.0.0" },
"id": "acme-hello",
"name": "Hello",
"icon": "window",
"contributes": {
"panel": { "entry": "panel/index.html" },
"attach": "dialog",
"capabilities": ["prompt", "sessions"],
"actions": [
{ "id": "create-task", "label": "Create task from message", "where": "message", "roles": ["assistant"] },
{ "id": "summarize", "label": "Summarize session", "where": "session", "payload": ["messages"] }
],
"commands": [{ "name": "task", "description": "Attach a task by id" }],
"tools": [{ "match": "tasks_*", "name": "Tasks", "icon": "checkbox-circle", "title": "{input.id}", "output": "table", "columns": ["id", "title", "status"] }],
"integration": {
"name": "Acme",
"description": "Tasks from Acme",
"token": {
"apiOrigin": "https://api.acme.example",
"account": { "path": "/me", "name": "login" },
"scheme": "bearer"
},
"settings": [{ "id": "list-id", "label": "List ID" }]
}
}
}
}version: required semver shown on the Settings → Extensions card.apiVersion:1(other values refused).engines.ohpichamber: optional1.0.0or>=1.0.0; older hosts refuse install.panel:id(unique kebab-case),icon(Remixicon kebab name, e.g.RiWindowLine→window, or package SVG),entry(panel HTML; omit to hide the rail icon). Extensions withoutpanel.entrycan declarebackground.entry,tools(examples/tools-only),providerLogos, self-hosted surfaces (statusSection,fileEditors,blocks,page), or standaloneservicefeatures (provides,surface,keepRunning,schedule,sessionEvents,waits,mentions).background:{ entry: "background/index.html" }supplies compiled HTML run on demand in a hidden sandboxed frame for backgroundactionsandcommands. Coexists withpanel.attach: optional ("dialog",true/"panel", or{ mode, entry }). Opens from the composer+menu (ctx.surfaceidentifies the surface); clicking an attached chip reopens withctx.item(vsnullfrom+).actions: up to 8 menu entries on messages (where: "message", optionalroles: ["assistant"]) or sessions (where: "session", optionalpayload: ["messages"]). Opens UI withctx.item(kind: "message" | "session"), or invokesonActionwithout UI whenmode: "background".commands: up to 8 slash commands (/task DEMO-2callshost.onResolve, returning a chip ornull). App-owned names take precedence.tools: up to 16 declarative chat renderers matching OMP tool names (match, e.g.tasks_*), withname,icon,title/subtitletemplates ({input.id},{output.total}), andoutput(text,json,markdown,code+language,table+columns, orcard). Omitoutputfor default host rendering; see API.md.capabilities: install-time grants —prompt,sessions,files(open project),model(host.generate),network(added byintegration),service(added byservice),filesystem(outer-project patterns forreadFile/writeFile/listDir/stat),conversation(payload: ["messages"]), andtranscript(sessionEventswithcontent: true). Calls outside approved grants fail withNOT_GRANTED.integration: optional Settings → Integrations card (tokenbearer/basic,oauth, orhost: { provider: "linear" }). Tokens stay on host; frames call viahost.request.service: optional unsandboxed local host process (GUEST_SERVICES.md). Supportsprovides("browser","source-control","notifications","tracker","quota"),surface: true(with optional dockedpanel.entryviapanel.dock/panel.size),contributes.sessionEvents, andcontributes.marks: true(host.setMark). An extension cannot be both a Git host (source-control) and atracker.
Actions without opening a panel
Set mode: "background" on a message or session action to call host.onAction in a fresh hidden iframe after connectHost():
const host = connectHost();
host.onAction(async (item) => {
if (item.kind === 'message' && item.action === 'message-length') {
await host.toast({
kind: 'info',
message: `Message length: ${item.text.length} characters.`,
copy: true,
dismiss: true,
persistent: true,
});
}
});Await all work (including host.toast) inside onAction. Loading and execution together are bounded (the 20 s host request timeout plus a fixed load allowance); thrown errors surface as toasts, and a runtime switch, disable, or grant withdrawal aborts without rollback or retry. ctx.surface is "background" (skip rendering UI) and ctx.item is null; session/directory context stays bound to the clicked target. Loads background.entry if declared, else falls back to panel.entry. Omit panel to drop the rail icon (only panel.entry creates one; see examples/hello-kit):
{
"id": "message-tools",
"name": "Message Tools",
"icon": "apps",
"contributes": {
"background": { "entry": "background/index.html" },
"actions": [
{ "id": "message-length", "label": "Show message length", "where": "message", "mode": "background" }
]
}
}Toast buttons
host.toast accepts three optional button/lifetime fields:
copy: true(orcopy: { text }up to 32,000 chars, preserving whitespace): copies text while keeping the toast open and showing Copied or a retry error on failure.dismiss: true: adds an OK button.persistent: true: keeps the toast until dismissed and always adds OK.
OhPiChamber translates buttons and handles clicks after a background iframe closes; await host.toast(...) resolves once displayed.
In the page
Full-screen boards use "page": true or "page": { "entry": "panel/page.html", "title": "Board" } (ctx.surface === "page", opened from the Extension pages menu; extensions cannot open it themselves). Work Status readouts use "statusSection": { "entry": "status/index.html", "title": "Recent commits", "defaultExpanded"?: false, "requiresProject"?: true } (ctx.surface === "status", no panel.entry needed, host.setHeight(px) clamped at 480 px; see examples/git-graph-status).
With sessions approved, use listProjects(), listWorktrees(projectId), listSessions(projectId), and onProjects/onWorktrees/onSessions (retain the returned unsubscribe function); snapshots distinguish loading, ready, and error separately from live activity and turn outcomes. startSession takes projectId and worktree: { kind: "new", name, baseBranch } | { kind: "existing", directory }, keeping the current screen unless openSession(sessionId) is called. host.storage (get/set/delete/keys) persists server JSON without a file grant (see API.md and tasks-demo). Pass { scope: 'device' } only when onReady sets features.deviceStorage: true; older hosts reject with UNSUPPORTED without falling back to instance storage (not for secrets or SSO state).
import { connectHost, HostRequestError } from 'ohpichamber-sdk';
const host = connectHost();
host.onReady((ctx) => {
document.body.dataset.theme = ctx.theme.mode;
});
host.onSession((session) => {
document.querySelector('#session')!.textContent = session?.title ?? '';
});
try {
const user = await host.request({ method: 'GET', path: '/me' });
} catch (error) {
if (error instanceof HostRequestError && error.code === 'DISCONNECTED') {
await host.oauthStart();
}
}
await host.toast({ kind: 'info', message: 'Hello' });
await host.compose({ text: 'Ask about the latest diff' });
await host.attach({
providerId: 'acme-hello',
id: 'TICKET-1',
title: 'Login is broken',
url: 'https://example.com/TICKET-1',
});
await host.startSession({
providerId: 'acme-hello',
id: 'TICKET-1',
title: 'Login is broken',
url: 'https://example.com/TICKET-1',
worktree: true,
text: 'Optional first message',
});
await host.prompt({ text: 'Fix the login', send: true });
await host.setBadge(3); // number on the rail icon; null clears it
await host.openCommit(sha); // show a commit of the open project in the Diff view
await host.openWalkthrough({ base: 'main' }); // Changes Walkthrough on This branch against main; the user clicks Generate
await host.setHeight(document.body.scrollHeight); // Work Status section: frame height, clamped by the host
const { text } = await host.generate({ prompt: task.description, system: 'One-line summary only.' }); // capability model
host.onResolve(({ command, args }) => {
// the user typed /task DEMO-2
const task = findTask(args.trim());
return task ? { providerId: 'acme-hello', id: task.id, title: task.title, url: task.url } : null;
});
host.onItem((item) => {
if (item?.kind === 'message') showMessage(item.text); // "Create task from message"
if (item?.kind === 'session') showSummary(item.messages); // "Summarize session"
});Every method, its limits, and the error codes are on the Host API page.
Popovers outside the extension frame
When ready.features.popovers is true, host.openPopover opens a bounded card in a second sandboxed frame (ready.surface === 'popover', ready.popover.data carrying your JSON, same capabilities). Attach triggers via mountPopoverAnchor from ohpichamber-sdk/ui (handles hover, keyboard, anchor removal, scrolling; keep a click fallback for older hosts). See Anchored popovers.
UI kit
ohpichamber-sdk/ui provides theme-matched buttons, inputs, searchable selects, checkboxes, tabs, badges, lists, empty states, spinners, banners, separators, progress bars, menus, and safe text. Call applyHostReady(ctx, document.documentElement) on every onReady (which also publishes optional --oc-syntax-* variables and clears omitted ones), but mount controls and register listeners once. Every mount returns { update, dispose } (call tabs.update({ activeId }) / select.update({ value }) inside onChange; see ./examples).
import { applyHostReady, mountList } from 'ohpichamber-sdk/ui';
let mounted = false;
host.onReady((ctx) => {
applyHostReady(ctx, document.documentElement);
if (mounted) return;
mounted = true;
mountList(document.querySelector('#root')!, {
items: tasks.map((task) => ({ id: task.id, leading: task.key, title: task.title })),
onSelect: (id) => {
const task = tasks.find((item) => item.id === id);
if (task) void host.attach({ providerId: 'acme-hello', id, title: task.title, url: task.url });
},
});
});OhPiChamber injects thin theme-aware scrollbars (GUEST_SCROLLBAR_CSS) and updates kit colors, borders, radii, and states across app updates without rebuilding your bundle; sizing and spacing stay pinned to the SDK version you bundled. Override kit styles with higher specificity (e.g. #root .oc-sdk-btn), respecting your CSP. Custom hosts can use GUEST_SCROLLBAR_CSS (ohpichamber-sdk) and GUEST_UI_LOOK_CSS (ohpichamber-sdk/ui).
Schemas & scope
ohpichamber-sdk/schemas exports Zod schemas for manifests and wire messages without adding Zod to the main runtime entry.
This package covers pages, manifests, messages, and the UI kit. Pages have no terminal, git, undeclared file access, or React tree access; declared service processes run unsandboxed with full user privileges. apiVersion 1 is frozen; new host methods ship with app releases.
