ohpichamber-sdk 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/API.md +740 -0
  2. package/DOCUMENTATION.md +269 -0
  3. package/GUEST_SERVICES.md +543 -0
  4. package/LICENSE +21 -0
  5. package/README.md +235 -2
  6. package/dist/api-version.d.ts +17 -0
  7. package/dist/api-version.js +16 -0
  8. package/dist/bootstrap.d.ts +14 -0
  9. package/dist/bootstrap.js +87 -0
  10. package/dist/contract.d.ts +595 -0
  11. package/dist/contract.js +239 -0
  12. package/dist/file-editor.d.ts +57 -0
  13. package/dist/file-editor.js +60 -0
  14. package/dist/frame-policy.d.ts +1 -0
  15. package/dist/frame-policy.js +18 -0
  16. package/dist/host-version.d.ts +17 -0
  17. package/dist/host-version.js +50 -0
  18. package/dist/host.d.ts +102 -0
  19. package/dist/host.js +1103 -0
  20. package/dist/index.d.ts +40 -0
  21. package/dist/index.js +23 -0
  22. package/dist/links.d.ts +5 -0
  23. package/dist/links.js +19 -0
  24. package/dist/manifest.d.ts +554 -0
  25. package/dist/manifest.js +363 -0
  26. package/dist/message-channel-test.d.ts +25 -0
  27. package/dist/message-channel-test.js +62 -0
  28. package/dist/microphone.d.ts +23 -0
  29. package/dist/microphone.js +46 -0
  30. package/dist/navigation.d.ts +15 -0
  31. package/dist/navigation.js +15 -0
  32. package/dist/parse.d.ts +1040 -0
  33. package/dist/parse.js +1051 -0
  34. package/dist/popover-schemas.d.ts +33 -0
  35. package/dist/popover-schemas.js +70 -0
  36. package/dist/popover.d.ts +36 -0
  37. package/dist/popover.js +54 -0
  38. package/dist/protocol.d.ts +1808 -0
  39. package/dist/protocol.js +703 -0
  40. package/dist/schemas.d.ts +13 -0
  41. package/dist/schemas.js +10 -0
  42. package/dist/scrollbar-style.d.ts +3 -0
  43. package/dist/scrollbar-style.js +58 -0
  44. package/dist/service-host-schemas.d.ts +110 -0
  45. package/dist/service-host-schemas.js +75 -0
  46. package/dist/service-host.d.ts +240 -0
  47. package/dist/service-host.js +108 -0
  48. package/dist/service-provider-schemas.d.ts +1726 -0
  49. package/dist/service-provider-schemas.js +433 -0
  50. package/dist/service-providers.d.ts +865 -0
  51. package/dist/service-providers.js +420 -0
  52. package/dist/service-surface-schemas.d.ts +169 -0
  53. package/dist/service-surface-schemas.js +54 -0
  54. package/dist/service-surface.d.ts +81 -0
  55. package/dist/service-surface.js +129 -0
  56. package/dist/session-events.d.ts +115 -0
  57. package/dist/session-events.js +87 -0
  58. package/dist/shells.d.ts +49 -0
  59. package/dist/shells.js +4 -0
  60. package/dist/source-control-capabilities.d.ts +70 -0
  61. package/dist/source-control-capabilities.js +36 -0
  62. package/dist/source-control-draft-schemas.d.ts +69 -0
  63. package/dist/source-control-draft-schemas.js +62 -0
  64. package/dist/source-control-reviewers.d.ts +11 -0
  65. package/dist/source-control-reviewers.js +1 -0
  66. package/dist/source-control-reviews.d.ts +11 -0
  67. package/dist/source-control-reviews.js +7 -0
  68. package/dist/source-control-urls.d.ts +6 -0
  69. package/dist/source-control-urls.js +9 -0
  70. package/dist/status-control-schemas.d.ts +21 -0
  71. package/dist/status-control-schemas.js +29 -0
  72. package/dist/status-controls.d.ts +27 -0
  73. package/dist/status-controls.js +43 -0
  74. package/dist/status-view-schemas.d.ts +165 -0
  75. package/dist/status-view-schemas.js +110 -0
  76. package/dist/status-view.d.ts +101 -0
  77. package/dist/status-view.js +12 -0
  78. package/dist/ui/badge.d.ts +9 -0
  79. package/dist/ui/badge.js +25 -0
  80. package/dist/ui/banner.d.ts +13 -0
  81. package/dist/ui/banner.js +48 -0
  82. package/dist/ui/button.d.ts +13 -0
  83. package/dist/ui/button.js +49 -0
  84. package/dist/ui/checkbox.d.ts +11 -0
  85. package/dist/ui/checkbox.js +45 -0
  86. package/dist/ui/dom.d.ts +11 -0
  87. package/dist/ui/dom.js +59 -0
  88. package/dist/ui/empty.d.ts +11 -0
  89. package/dist/ui/empty.js +44 -0
  90. package/dist/ui/field.d.ts +16 -0
  91. package/dist/ui/field.js +49 -0
  92. package/dist/ui/icons.d.ts +9 -0
  93. package/dist/ui/icons.js +25 -0
  94. package/dist/ui/index.d.ts +38 -0
  95. package/dist/ui/index.js +19 -0
  96. package/dist/ui/list.d.ts +23 -0
  97. package/dist/ui/list.js +90 -0
  98. package/dist/ui/menu.d.ts +19 -0
  99. package/dist/ui/menu.js +112 -0
  100. package/dist/ui/navigation.d.ts +12 -0
  101. package/dist/ui/navigation.js +32 -0
  102. package/dist/ui/option.d.ts +14 -0
  103. package/dist/ui/option.js +41 -0
  104. package/dist/ui/popover-anchor.d.ts +15 -0
  105. package/dist/ui/popover-anchor.js +219 -0
  106. package/dist/ui/popup.d.ts +1 -0
  107. package/dist/ui/popup.js +38 -0
  108. package/dist/ui/progress.d.ts +10 -0
  109. package/dist/ui/progress.js +51 -0
  110. package/dist/ui/search.d.ts +10 -0
  111. package/dist/ui/search.js +62 -0
  112. package/dist/ui/select.d.ts +19 -0
  113. package/dist/ui/select.js +164 -0
  114. package/dist/ui/separator.d.ts +6 -0
  115. package/dist/ui/separator.js +26 -0
  116. package/dist/ui/spinner.d.ts +7 -0
  117. package/dist/ui/spinner.js +29 -0
  118. package/dist/ui/style.d.ts +3 -0
  119. package/dist/ui/style.js +310 -0
  120. package/dist/ui/tabs.d.ts +14 -0
  121. package/dist/ui/tabs.js +61 -0
  122. package/dist/ui/text.d.ts +21 -0
  123. package/dist/ui/text.js +88 -0
  124. package/dist/ui/theme.d.ts +16 -0
  125. package/dist/ui/theme.js +88 -0
  126. package/dist/waits-schemas.d.ts +28 -0
  127. package/dist/waits-schemas.js +42 -0
  128. package/dist/waits.d.ts +90 -0
  129. package/dist/waits.js +95 -0
  130. package/dist/workspace-schemas.d.ts +192 -0
  131. package/dist/workspace-schemas.js +63 -0
  132. package/dist/workspace.d.ts +150 -0
  133. package/dist/workspace.js +5 -0
  134. package/package.json +56 -4
  135. package/scripts/bundle-guest.ts +44 -0
  136. package/scripts/check-guest.ts +72 -0
package/API.md ADDED
@@ -0,0 +1,740 @@
1
+ # ohpichamber-sdk — developer API reference
2
+
3
+ What third-party guest authors import and call. Source of truth: [packages/sdk/src](https://github.com/Shizuku-Yume/ohpichamber/tree/main/packages/sdk/src). Author guides live in the [product docs](https://github.com/Shizuku-Yume/ohpichamber/tree/main/packages/docs/content/docs) (`sdk.mdx`, `sdk/host.mdx`, `sdk/ui.mdx`) and in [GUEST_SERVICES.md](./GUEST_SERVICES.md) for local services.
4
+
5
+ **Package:** `ohpichamber-sdk`
6
+
7
+ **API version:** manifest `apiVersion: 1`, wire envelope `v: 2` (private `MessagePort` bootstrap)
8
+
9
+ **Runtimes that load guests:** Web and Electron. `loadGuestCatalog` currently marks mobile surfaces `unsupported`, so mobile opt-in fields (`panel.mobile`, `page.mobile`) are accepted by the SDK schema but inactive in the current mobile shell.
10
+
11
+ Wire `v: 2` is the private bootstrap transport; manifest `apiVersion` stays `1` because the `manifest`/`contributes` schema did not change. The host refuses a `v: 1` window `hello` and names the mismatch in the pane instead of waiting for a timeout; a `v: 1` bootstrap announcement is dropped without granting anything.
12
+
13
+ Two entrypoints:
14
+
15
+
16
+ | Import | Role |
17
+ | --------------------- | -------------------------------------------------------------- |
18
+ | `ohpichamber-sdk` | Manifest parse, iframe protocol, `connectHost` |
19
+ | `ohpichamber-sdk/ui` | Optional DOM drawing kit (buttons, fields, lists, popups) |
20
+
21
+
22
+ ---
23
+
24
+ ## Ship checklist (install fails without these)
25
+
26
+ `inspectGuestPackage` (Settings → Extensions install) checks the folder or zip **on disk**. Parse alone is not enough. No OhPiChamber runtime compiles TypeScript: packaged desktop, `ohpichamber serve`, and the dev server all serve the built `.js` files as they sit in the package.
27
+
28
+
29
+ | Must exist | When | Failure code |
30
+ | -------------------------------------------------------------------------------- | ----------------------------------------------- | ------------------ |
31
+ | Semver `version` on `package.json` (`1.0.0`) | Always on install | `invalid-manifest` |
32
+ | `panel.entry` or `background.entry` HTML file | Every declared entry | `invalid-manifest` |
33
+ | Every relative `<script src="…">` `.js` from that HTML | Every declared entry | `missing-build` |
34
+ | File named by `panel.icon` | Only when icon ends in `.svg` (e.g. `icon.svg`) | `invalid-manifest` |
35
+ | File named by `service.entry` (e.g. `service/main.js`) | When `contributes.service` is set | `missing-build` |
36
+
37
+
38
+ **Icon.** Remixicon kebab name (`window`) needs no file. A package SVG path (`icon.svg`) must sit inside the package. URLs and absolute paths fail parse as `invalid-panel-icon`. Missing SVG on disk fails install as `invalid-manifest`.
39
+
40
+ **Panel JS.** Classic IIFE. The iframe cannot load ESM. Point `panel/index.html` at `./main.js` and ship that file.
41
+
42
+ **Service JS.** Same rule as the panel: `service.entry` must be compiled JS already in the package. `.ts` alone fails as `missing-build`.
43
+
44
+ Bundle with the SDK helper from the guest folder (`--node` targets Node for the service):
45
+
46
+ ```bash
47
+ bunx ohpichamber-guest-bundle panel/main.ts panel/main.js
48
+ bunx ohpichamber-guest-bundle --node service/main.ts service/main.js
49
+ bunx ohpichamber-guest-check # says what the host would refuse
50
+ ```
51
+
52
+ Zip or folder for install should include at least: `package.json`, `panel/index.html`, `panel/main.js`, and any declared `icon.svg` / `service/main.js`. Skip `node_modules` and TypeScript sources. Zip and git installs land in `{dataDir}/extensions/{id}`. See [GUEST_SERVICES.md](./GUEST_SERVICES.md).
53
+
54
+ ---
55
+
56
+ ## 1. `connectHost` — iframe client
57
+
58
+ ```ts
59
+ import { connectHost, HostRequestError } from 'ohpichamber-sdk';
60
+
61
+ const host = connectHost();
62
+ ```
63
+
64
+ Throws `HOST_UNAVAILABLE` when there is no `window`. Outside an iframe (`parent === self`) it still returns a client, but every call rejects with `HOST_UNAVAILABLE`. The host bootstrap runs before authored Guest metadata and scripts, creating a per-document private `MessageChannel`, transferring one end to the exact parent, and receiving the SDK port over that private channel. `connectHost` consumes that port through an internal same-document event; iframe `load` and window-message envelopes never grant capabilities. Call `dispose()` on teardown; in-flight RPCs reject as `HOST_UNAVAILABLE`. In-flight RPCs time out after 20 s with `HOST_TIMEOUT`.
65
+
66
+ ### 1.1 Subscriptions (host pushes)
67
+
68
+ Each returns an unsubscribe function. State subscriptions replay the last known value from `ready` or the last dedicated push. Control activations and popover-close events are delivered only to current listeners.
69
+
70
+
71
+ | Method | Payload | Notes |
72
+ | ------------------------------ | ----------------------- | ------------------------------------------------------------ |
73
+ | `onReady(listener)` | `HostReadyContext` | First snapshot and later full refreshes |
74
+ | `onDirectory(listener)` | `string \| null` | |
75
+ | `onSession(listener)` | `SessionSnapshot \| null` | |
76
+ | `onSessionLifecycle(listener)` | `SessionLifecycleEvent` | `{ sessionId, phase }` — `started` / `completed` / `failure` |
77
+ | `onConnection(listener)` | `GuestConnection` | `{ connected, account }` |
78
+ | `onSettings(listener)` | `GuestSettings` | Declared integration fields only (`Record<string, string>`) |
79
+ | `onItem(listener)` | `GuestItem \| null` | The item this surface was opened for: the chip (`AttachIssueRequest`), a message (`GuestMessageItem`), or a session (`GuestSessionItem`); `null` from the rail icon or + menu |
80
+ | `onStatusControl(listener)` | `{ id, value? }` | Host Work Status control activation. Register synchronously; only status frames with advertised status controls receive events |
81
+ | `onPopoverClosed(listener)` | `{ id, reason }` | Dismissal of this frame's anchored popover. Events go to the owner, are not replayed, and identify the opening being closed |
82
+ | `onResolve(handler)` | `{ command, args }` → `Promise<AttachIssueRequest \| null>` | Answers a `contributes.commands` slash command. Return the chip to attach, `null` for nothing (the user sees a short notice), or throw (the message reaches the user). One handler at a time |
83
+ | `onBlock(listener)` | `GuestBlockCall` | The call a `block` frame draws: `{ name, args, answered }`. Replays, and again once answered. The arguments are written by a model: treat them as untrusted |
84
+ | `onServiceEvent(listener)` | `{ topic, data }` | What the extension's service sent with `emit`. Nothing replays: read the current state from the service first |
85
+ | `onAction(handler)` | `GuestActionItem` → `void \| Promise<void>` | Runs a `mode: "background"` message or session action. Register synchronously after `connectHost`. Await every operation; the frame is removed when the handler settles. Throw to report an error. One handler at a time; returns an unsubscribe function |
86
+ | `onFileOpen(listener)` | `FileEditorDocument` | File editors only: `{ path, name, readOnly, encoding: 'text', content }` or `{ ..., encoding: 'binary', bytes }` (a `Uint8Array`) of the file this frame edits. Replays the last file; the same file pushed again is not repeated. Registering also sends Cmd/Ctrl+S inside the frame to the host's save |
87
+ | `onFileSnapshot(handler)` | `'save' \| 'handoff'` → `FileEditorSnapshot \| Promise<FileEditorSnapshot>` | File editors only: return the whole edited file (`{ content, version }` for a text editor, `{ bytes, version }` for a binary one) and a version of the state it came from. `save` writes it; `handoff` moves it into the host's source view. Throwing fails that save. One handler at a time |
88
+ | `onFileSaved(listener)` | `version: string` | File editors only: the snapshot with that version is on disk. Answer with `reportFileChange({ dirty, edited: false })` so edits made during the write stay unsaved |
89
+
90
+
91
+ `ready.session` and `onSession` return the current session with optional `context` and `tokens` fields. `context` is `{ tokens, limit }` for the latest measured context fill: `tokens` counts the most recent assistant step, while `limit` is the context window of the model that answered that step, or `null` if unknown. It is `null` before a measured reply or after a compaction until another reply. `tokens` contains `{ prompt, output, reasoning, cacheRead, cacheWrite, cacheHitPercent }`, the cumulative session totals shown in the app. `prompt` includes uncached input and cache reads/writes; `cacheHitPercent` is `null` without prompt tokens. `tokens` is `null` before the session reports usage. Both fields update with the session and are optional for older hosts.
92
+
93
+
94
+ `HostReadyContext`
95
+
96
+
97
+ | Field | Type | Meaning |
98
+ | -------------- | ------------------------ | ---------------------------------------------------------------------------------------- |
99
+ | `theme.mode` | `'light' \| 'dark'` | |
100
+ | `theme.tokens` | surfaces, text, interaction states, `primary`, status colors, `font`, `fontSize` (the app's body text in px, follows the interface font size; absent from older hosts), `mono`, `radius` | Pass to `applyHostReady` before mounting UI |
101
+ | `locale` | `string` | Host language tag |
102
+ | `directory` | `string \| null` | |
103
+ | `session` | snapshot or `null` | Title falls back to `id`. `busy` is live status. `model` is `providerID/id` when present |
104
+ | `surface` | `'panel' \| 'dialog' \| 'page' \| 'background' \| 'status' \| 'file' \| 'popover' \| 'block'` | Where the host mounted this frame |
105
+ | `popover` | optional `{ id, data }` | Present in a host-created popover frame. `data` is bounded JSON from the owning frame |
106
+ | `connection` | `{ connected, account }` | Integration link state; a tracker extension without an integration gets its tracker account |
107
+ | `settings` | `Record<string, string>` | Declared keys only, without `secret` fields |
108
+ | `item` | `GuestItem \| null` | Set when the user clicked this guest's chip on the composer, or ran one of this guest's `contributes.actions`. Narrow with `isGuestMessageItem` / `isGuestSessionItem` / `isGuestAttachItem` / `isGuestLinkItem` |
109
+
110
+
111
+ `theme.tokens` includes `primaryText`, `successText`, `warningText`, `errorText`, and `infoText` for text on neutral surfaces and tinted controls; keep using base colors for fills and `primaryForeground` on a solid primary fill. `applyHostReady` exposes these as `--primary-text`, `--success-text`, `--warning-text`, `--error-text`, `--info-text` (and `--oc-*-text`), plus optional syntax tokens (`syntaxKeyword`, `syntaxString`, `syntaxNumber`, `syntaxFunction`, `syntaxType`, `syntaxComment`, `syntaxVariable`, `syntaxOperator`) as `--oc-syntax-*` and `--syntax-*` (missing tokens clear on later snapshots). Apply each `onReady` snapshot to pick up theme changes.
112
+
113
+ `features` is optional and advertises implemented host capabilities: `deviceStorage?: true`, `statusControls?: true`, `popovers?: true`, `lateGenerateResults?: true`, and `microphone?: true`.
114
+ `GuestItem` is `AttachIssueRequest | GuestMessageItem | GuestSessionItem | GuestSelectionItem | GuestFileItem | GuestDiffItem | GuestLinkItem`:
115
+
116
+ ```ts
117
+ type GuestMessageItem = {
118
+ kind: 'message';
119
+ action: string; // the action id from the manifest
120
+ sessionId: string;
121
+ sessionTitle: string;
122
+ directory: string | null; // the session's project directory
123
+ messageId: string;
124
+ role: 'user' | 'assistant';
125
+ text: string; // what the Markdown export renders for that message, at most 200 000 chars
126
+ };
127
+
128
+ type GuestSessionItem = {
129
+ kind: 'session';
130
+ action: string;
131
+ sessionId: string;
132
+ sessionTitle: string;
133
+ directory: string | null; // the session's project directory
134
+ messages?: Array<{ id: string; role: 'user' | 'assistant'; text: string; createdAt: number }>; // oldest first; only with payload ["messages"] and the conversation grant. Same messages the Markdown export writes: the conversation plus context the user attached (`user`); OMP's own plumbing messages are left out
135
+ truncated?: boolean; // the oldest messages were dropped so the item stays under 2 000 000 serialized chars
136
+ };
137
+
138
+ type GuestLinkItem = {
139
+ kind: 'link'; // the user clicked an identifier or link `contributes.links` claims, with action "open"
140
+ identifier: string; // what the key or `{id}` matched, e.g. "DEMO-12"
141
+ url?: string; // the clicked link without its fragment and other query parameters; for an identifier in text, the link the first fillable template names; absent without one, or when the identifier lacks `urls.identifier`'s shape
142
+ };
143
+ ```
144
+
145
+
146
+ Access tokens never appear in `ready` or in request results.
147
+
148
+ **Session lifecycle phases:** live `busy` / `retry` → `started`; `idle` → `completed`; unknown status → `failure` (not abort/crash).
149
+
150
+ ### 1.2 Actions (RPC)
151
+
152
+
153
+ | Method | Arguments | Returns | Behavior |
154
+ | ----------------- | --------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------- |
155
+ | `toast` | `{ kind: 'info' \| 'success' \| 'error', message, copy?, dismiss?, persistent? }` | `Promise<void>` | Show a toast, optionally with host-owned Copy and OK buttons; see Toast buttons below |
156
+ | `openUrl` | `url: string` | `Promise<void>` | Open an http(s) URL. In the desktop app with a project open, a local address (`localhost`, `127.0.0.1`, `[::1]`) opens in the browser panel beside the chat, and other links follow the user's setting for chat links; elsewhere the system browser opens it |
157
+ | `openSurface` | `surfaceId: string` | `Promise<void>` | Show that surface; resolves once visible, rejects `NO_DIRECTORY` or `UNSUPPORTED` when it cannot open |
158
+ | `writeClipboard` | `text: string` | `Promise<void>` | Copy in the host (1–32 000 chars) |
159
+ | `compose` | `{ text, mode?: 'append' \| 'replace' }` | `Promise<void>` | Write text into the current composer |
160
+ | `attach` | `AttachIssueRequest` | `Promise<void>` | Composer chip, alongside other attached items |
161
+ | `startSession` | `StartSessionRequest` | `Promise<{ sessionId, sent }>` | Create session (+ optional worktree), write snapshot. `text` can become first message |
162
+ | `prompt` | `{ text, send?: boolean }` | `Promise<{ sent }>` | Current session: omit/`false` = replace-compose; `send: true` = send |
163
+ | `sessionLink` | `AttachIssueRequest` | `Promise<void>` | Write snapshot on **current** session. Does not create one |
164
+ | `close` | — | `Promise<void>` | Dismiss an attach dialog or the calling popover. No-op on the rail |
165
+ | `oauthStart` | — | `Promise<void>` | Open provider authorize URL (or first-party Linear) |
166
+ | `oauthDisconnect` | — | `Promise<void>` | Drop guest tokens / Linear connection |
167
+ | `request` | `{ method, path, query?, body? }` | `Promise<{ status, body }>` | HTTPS call on declared `apiOrigin`. Host attaches auth |
168
+ | `serviceRequest` | same shape as `request` | `Promise<{ status, body }>` | Proxy to this guest's local service on loopback |
169
+ | `serviceStatus` | — | `Promise<{ status }>` | `'stopped' \| 'starting' \| 'ready' \| 'failed'` |
170
+ | `readFile` | `path: string` | `Promise<{ content }>` | UTF-8 text. Relative = inside the open project (`files`); `/…` or `~/…` = declared `filesystem` pattern |
171
+ | `writeFile` | `path: string, content: string` | `Promise<{ written: true }>` | Atomic (temp + rename), creates parent folders. Same path rules |
172
+ | `listDir` | `path: string` | `Promise<{ entries }>` | `{ name, kind: 'file' \| 'directory' \| 'other' }[]`, sorted, capped at 2 000. Same path rules |
173
+ | `stat` | `path: string` | `Promise<{ kind, size, mtime }>` | `kind` adds `'missing'`; a missing path is not an error. Same path rules |
174
+ | `setBadge` | `count: number \| null` | `Promise<void>` | Number on this guest's rail icon, 0–999 (clamped); `null` clears. Opening the panel clears it too. In memory only |
175
+ | `openCommit` | `sha: string` | `Promise<void>` | Show that commit of the open project in the host's Diff view (commit scope). 7–64 hex chars. `NO_DIRECTORY` without a project, `NOT_FOUND` for an unknown commit, `UNSUPPORTED` where the host has no Diff view |
176
+ | `openWalkthrough` | `{ base: string }` | `Promise<void>` | Show Changes Walkthrough on "This branch" of the open project's checked-out branch, compared with `base` (a branch name, a remote-tracking branch of the bound remote like `origin/main`, or `refs/heads/…` / `refs/remotes/…`). A bare name prefers the bound remote's copy when present; a remote ref requires that remote-tracking branch and never falls back to a local branch. Without a bound remote, only local branches qualify. Unknown base/branch or detached HEAD rejects `NOT_FOUND`; `NO_DIRECTORY` without a project; `HOST_UNAVAILABLE` if unreadable or worktree is creating; `UNSUPPORTED` in Mini Chat or mobile. After `openSession` the frames reload, so persist state via `storage` before navigating |
177
+ | `setHeight` | `height: number` | `Promise<void>` | Content height in CSS px. Work Status clamps to 24–480 (taller content scrolls); docked shared surfaces size 24 px up to half the panel; other surfaces ignore it |
178
+ | `setStatusControls` | `GuestStatusControl[]` | `Promise<void>` | Replace host-rendered controls for this mounted status frame. Requires `features.statusControls`; old hosts reject with `UNSUPPORTED` |
179
+ | `openPopover` | `GuestPopoverRequest` | `Promise<void>` | Open a sandboxed frame outside this frame's bounds, anchored to a rectangle in its viewport. Requires `features.popovers` |
180
+ | `closePopover` | `id, reason?: 'closed' \| 'escape'` | `Promise<void>` | Close this frame's matching opening, or the popover frame itself. A stale id cannot close a replacement |
181
+ | `setPopoverAnchorActive` | `id, active: boolean` | `Promise<void>` | Report anchor pointer/focus activity so the host can allow travel between the anchor and popover |
182
+ | `generate` | `{ prompt, system?, maxOutputTokens? }` | `Promise<{ text }>` | One-off text from the user's Small Model (capability `model`). No session or history; waits up to 960 s (`GUEST_GENERATE_TIMEOUT_MS`) |
183
+ | `reportFileChange` | `{ dirty, edited }` | `void` | File editors only. `dirty` against the last saved version; `edited` when the document itself changed, which holds autosave back until edits stop |
184
+ | `requestFileSave` | — | `void` | File editors only. Save now, as Cmd/Ctrl+S does |
185
+ | `reportFileUnsupported` | — | `void` | File editors only. This file cannot be opened here; the host shows its source and a notice |
186
+ | `dispose` | — | `void` | Remove listener, reject pending RPCs |
187
+
188
+
189
+ `AttachIssueRequest`
190
+
191
+ ```ts
192
+ {
193
+ providerId: string; // usually panel id
194
+ id: string; // guest identifier, not a GitHub number
195
+ title: string;
196
+ url: string;
197
+ text?: string; // optional model context
198
+ kind?: 'issue' | 'pull'; // default issue
199
+ author?: string;
200
+ branches?: { head: string; base: string }; // for pull
201
+ data?: JsonValue; // opaque, comes back as ready.item.data; not sent to the model
202
+ }
203
+ ```
204
+
205
+ `data` is plain JSON (`string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }`). It is stored with the chip and the session snapshot and returned unchanged when the user clicks the chip. `JSON.stringify(data).length` must stay within `GUEST_ATTACH_DATA_MAX` (16 000): `clampAttachRequest` silently drops a larger `data`, and the host schema refuses the whole message if it arrives over the limit.
206
+
207
+ `StartSessionRequest` adds `projectId?`, `navigation?: 'preserve' | 'open'`, and `worktree?` to the attach fields. Navigation defaults to `preserve`. Without `projectId`, the current directory is used. With one, creation targets that registered project without switching the app first.
208
+
209
+ `worktree` is `false` or omitted for the target directory, `true` for a generated new worktree, `{ kind: 'existing', directory }` for a known worktree belonging to the project, or `{ kind: 'new', name?, baseBranch? }`. `name` names both the branch and worktree. Omitted name/base use the host's normal defaults. First-message model/agent/variant selection is captured when the call starts.
210
+
211
+ A created session returns `{ sessionId, directory, sent, linked, worktree? }`. `linked: false` means the session exists but saving the attached item failed. If a worktree was created but bootstrap or session creation failed, the result is `{ sessionId: null, sent: 'skipped', directory, worktree, failure }`, where `failure` is `bootstrap-failed` or `session-create-failed`. The worktree is retained. Inspect the result before offering Retry, which would otherwise create another worktree. The call waits up to 180 seconds; a timeout does not prove the server rolled back.
212
+
213
+ ### Workspace lists and subscriptions
214
+
215
+ These methods extend the existing `sessions` capability. They expose registered projects on the connected server, session metadata and live state, and known worktrees. They do not grant conversation content or file access.
216
+
217
+ | Method | Result |
218
+ | --- | --- |
219
+ | `listProjects()` | `Promise<GuestProjectsSnapshot>` |
220
+ | `listWorktrees(projectId)` | `Promise<GuestWorktreesSnapshot>` |
221
+ | `listSessions(projectId)` | `Promise<GuestSessionsSnapshot>` including known archived sessions |
222
+ | `onProjects(listener)` | `Promise<() => void>` |
223
+ | `onWorktrees(projectId, listener)` | `Promise<() => void>` |
224
+ | `onSessions(projectId, listener)` | `Promise<() => void>` |
225
+ | `openSession(sessionId)` | `Promise<void>`, explicitly opens the chat and closes the page |
226
+
227
+ Await subscription registration to handle refusal, then retain its returned unsubscribe function. Each subscription sends an initial snapshot, then changes. At most 32 subscriptions per iframe. `dispose()` releases them all. Unmount, disable, uninstall and runtime switch also release host subscriptions.
228
+
229
+ Snapshots carry `state: 'loading' | 'ready' | 'error'`; session snapshots also carry per-directory `coverage`. Loading/error may retain data. Only `ready` establishes complete empty success. Reads use existing shared stores and hydration, never a git scan per extension request.
230
+
231
+ Projects contain `id`, `name`, `directory`. Worktrees contain `directory`, `name`, `branch`, and `status: 'ready' | 'pending' | 'invalid' | 'missing'`. Session records contain `id`, `title`, `projectId`, `directory`, optional `agent`, `parentId`, `createdAt`, `updatedAt`, `archivedAt`, `worktree`, `activity`, `outcome`, `items`, `links`, `inWork`, and `unread` (newer optional fields are omitted by older hosts):
232
+
233
+ - `items` holds only this extension's `id` and optional `data`.
234
+ - `links` lists every thread linked to the session (`title`, `url`, `kind: 'issue' | 'change'`, `linkedAt`), read-only.
235
+ - `inWork` is `true` when the session sits in the sidebar's In work block (`false` when the setting is off).
236
+ - `unread` is `true` when the last turn ended and nobody has opened the session since (persisted in OMP).
237
+ - `tool` is present while `activity` is `running`: `{ name, target }` for the running or just-finished tool (`target` is relative to `directory` or bare name outside it, `null` when none; shell command text never appears).
238
+ - `context` (`{ tokens, limit }`) and `tokens` hold latest-step context fill and cumulative session usage as described above.
239
+ - `agent` is the session's agent name for top-level sessions and subsessions.
240
+ - `activity` is `unknown`, `idle`, `running`, `retrying`, `waiting-permission`, or `waiting-question`. `outcome` is the last observed `completed` or `failed` turn (`null` when unknown or working), kept in memory for the latest 2,000 observed sessions and reset on runtime switch. An idle event preserves an observed failure until another run starts. Blocking-request contents and approve/reply actions are not exposed.
241
+
242
+ ### Running shells
243
+
244
+ These methods need the `shells` capability. They expose the running shell commands in a scope — one session and its subagents, a registered project, or every session — and let the extension read their output and stop them. OhPiChamber answers from its local store; no network read happens per request.
245
+
246
+ | Method | Result |
247
+ | --- | --- |
248
+ | `onRunningShells(scope, listener)` | subscription: the running shell commands in scope — one session and its subagents (`{ kind: 'session', sessionId }`), a registered project (`{ kind: 'project', projectId }`), or every session (`{ kind: 'global' }`) — oldest first, with each command's `background` flag, plus the ones that ended since OhPiChamber started watching |
249
+ | `readShellOutput(shellId, { cursor?, tailBytes? })` | one page of a running or ended command's output; `tailBytes` is capped at 65536 |
250
+ | `stopShell(shellId)` | sends the agent the stop note first, then removes the command |
251
+
252
+ Await subscription registration to handle refusal, then retain its returned unsubscribe function. Each subscription sends an initial snapshot, then changes, and counts against the same 32-subscription limit as the workspace subscriptions. The snapshot is `{ kind: 'shells', scope, shells, ended }`, where `scope` echoes the subscription's scope; each shell is `{ id, sessionID, command, startedAt, background }`, at most 200, oldest first. `background` is `true` for a job the turn does not wait for, and `false` while the turn that ran it is blocked on it.
253
+
254
+ `ended` holds the commands in scope that OhPiChamber saw running and saw end, oldest end first, at most 200 with the newest kept. Each adds `status`, `endedAt`, and `exit` when the command exited with a code. `status` is `exited`, `timeout`, `killed` (a signal), `stopped` (by a user: Stop in the app, `stopShell`, or aborting the turn that waited on it), or `unknown` (the end fell into a reconnect and OhPiChamber only saw the command gone). The list lives in memory: it starts empty when the app loads and resets on a runtime switch, so keep anything you show across reloads in extension storage.
255
+
256
+ `readShellOutput` returns `{ output, cursor, skipped }`; omit `cursor` to start `tailBytes` before the end, and `skipped` says earlier output was dropped. OMP keeps an ended command's output until it evicts the command (the latest 25 ended commands per directory); a stopped command's output is removed with it. A shell OhPiChamber has not seen, a stopped one, and one whose output OMP no longer keeps are `NOT_FOUND`; `stopShell` on a shell that is not running is `NOT_FOUND` too. An unapproved `shells` capability is `NOT_GRANTED`.
257
+
258
+ ### Microphone
259
+
260
+ `openMicrophone()` needs the `microphone` capability and resolves to `{ stream, close, onEnded }`. `stream` is a `MediaStream` with one mono audio track carrying the user's microphone; hand it to an `RTCPeerConnection`, a `MediaRecorder` or an `AudioContext` as you would one from `getUserMedia`. The frame cannot call `getUserMedia` itself: its origin is opaque and the browser refuses it, so OhPiChamber captures and streams the audio in.
261
+
262
+ Call it from a click inside your frame, because the audio inside the frame starts only from the user's gesture. Check `features.microphone` on `onReady` first; older hosts and hidden background frames answer `UNSUPPORTED`. One microphone is open per frame at a time, and a second call while it is open is `HOST_REJECTED`. The user or the system refusing access is `DENIED`, no input device is `NOT_FOUND`, an unapproved capability is `NOT_GRANTED`. The open waits up to 120 s, since the system may be showing its permission prompt.
263
+
264
+ `close()` stops the capture and ends the track; calling it twice is safe. `onEnded(listener)` hears the host stop on its own, with `revoked` when the user withdrew the grant or paused the extension and `device-lost` when the input device went away; the handle is closed by then. Reloading or removing the frame stops the capture too. Echo cancellation, noise suppression and auto gain are on.
265
+
266
+ ### Extension storage
267
+
268
+ `host.storage.get(key, options?)` returns JSON or `undefined` for a missing key. JSON `null` is a stored value. `set(key, value, options?)` and `delete(key, options?)` return `Promise<void>`; `keys(options?)` returns `Promise<string[]>` in sorted order.
269
+
270
+ Storage belongs to the extension on the connected server and needs no extra capability. Keys contain 1 to 128 characters, each serialized value is at most 64 KiB UTF-8, and the complete namespace is at most 2 MiB and 2,000 keys. Use a project ID in your key when data belongs to one project. Concurrent operations serialize on the server, writes are atomic, and read/write failures preserve existing data. Uninstall deletes the namespace, including for folder installs.
271
+
272
+ Omit `options`, or pass `{ scope: 'instance' }`, for this existing server-owned storage. `{ scope: 'device' }` stores data in the current browser profile, scoped by the host runtime, guest ID, and server-issued installation identity. Use it only after `onReady` reports `features.deviceStorage: true`. Older hosts reject device requests with `UNSUPPORTED`; the SDK never changes them into instance requests. Different runtime identities keep separate preferences even when a server copies an installation identity. URL aliases are not guaranteed to share data; saved host and relay connections follow the host's existing runtime identity rules. Device namespaces have the same 2 MiB and 2,000-key limits, and serialized preference content across the browser database has a 16 MiB limit; browser metadata has separate overhead. A successful uninstall makes an installation namespace inaccessible, but an offline profile may retain those bytes until site data is removed. Device storage is for preferences, not secrets, credentials, or SSO state.
273
+
274
+ ### Full-screen pages
275
+
276
+ `contributes.page: true` reuses `panel.entry`; `{ entry: 'panel/page.html', title?: 'Board' }` uses separate package HTML and needs no `panel.entry` (`page: true`, `attach`, `actions`, and `commands` still need `panel.entry` or `background.entry`). Pages use the same installed/approved/enabled gate as panels, open only from the sidebar's Extension pages menu (`openSurface` does not open them), report `ctx.surface === 'page'`, close via `close()`, and reset to chat on reload or runtime switch.
277
+
278
+ ### Work Status sections
279
+
280
+ `contributes.statusSection: true` reuses `panel.entry`; `{ entry: 'status/index.html', title?: 'Recent commits', height?: 160, defaultExpanded?: false, requiresProject?: true }` uses separate package HTML (checked at install). The object form needs no `panel.entry`. `title` (1–60 chars) replaces `panel.name` on the header; `height` (24–480, default 120) sets initial height before `setHeight`. Omitted `defaultExpanded` preserves the default (a saved user choice wins). `requiresProject` hides the section when no project is open. `ctx.surface` is `'status'`; frames mount only while the panel is visible and expanded, so keep no state you cannot rebuild.
281
+
282
+ `setStatusControls` accepts 0–4 declarations (`kind: 'button' | 'select'`, id kebab-case 1–40 chars, label 1–60 chars; selects take 1–16 unique options with values 1–80 chars and a matching `value`). Register `onStatusControl` synchronously after `connectHost` and gate `setStatusControls` on `features.statusControls`. Controls belong to the expanded mounted frame and clear on fold, hide, or project change (re-publish from `onDirectory`). The host rejects stale, unknown, disabled, or invalid controls, and enforces 20 changed publications per second per frame. Keep a fallback body control visible until `setStatusControls` succeeds on older hosts (`UNSUPPORTED`).
283
+
284
+ ### File editors
285
+
286
+ `contributes.fileEditors` lists up to 8 editors: `{ id: 'canvas', title: 'Excalidraw', match: ['*.excalidraw', '*.excalidraw.md'], entry: 'editor/index.html' }`. `match` holds 1–16 case-insensitive filename patterns (no `/`, `*` any run, `?` one char, at least one non-wildcard). `content` is `"text"` (default; text files only, `\n` normalized, host restores original line endings on write) or `"binary"` (`Uint8Array`, no source view; host saves unsaved changes before fullscreen transitions). The first enabled, approved matching editor wins ahead of built-in viewers (`ctx.surface === 'file'`). Web and desktop only; `examples/checklist-editor` is a complete editor.
287
+
288
+ The host owns file I/O, saving, autosave, unsaved prompts, and external change detection (no `files` capability needed). It sends content via `onFileOpen`, requests snapshots via `onFileSnapshot` (`'save' | 'handoff'`), and confirms disk writes via `onFileSaved`. Report edits with `reportFileChange` (`createFileSaveTracker(version)` handles dirty state) and reject unsupported files with `reportFileUnsupported`. Files over 20 000 000 chars/bytes stay with the host view, wrong-kind snapshots fail the save, and external changes, discards, or fullscreen toggles reload the frame.
289
+ `sent` **values** (`startSession` / `prompt`): `sent` | `no-model` | `skipped` | `failed`. After `no-model` / `failed` on `startSession`, the session still exists.
290
+
291
+ **File path rules** (`readFile` / `writeFile` / `listDir` / `stat`): a relative path (`README.md`, `src/x.ts`, `.`) is joined to the project that is open when the call runs and needs the `files` capability; no open project is `NO_DIRECTORY`. A path starting with `/` or `~/` is outside the project, must match one of the package's `contributes.filesystem` globs, and needs the `filesystem` capability. Any `..` segment, a backslash, or a symlink that leads out of the allowed tree is `BAD_PATH`. The host compares canonical (realpath) paths, so `/tmp/x` on macOS is checked as `/private/tmp/x` and a pattern's literal prefix is canonicalized the same way. Content over 2 000 000 characters is `FILE_TOO_LARGE` in both directions; an OS permission refusal is `DENIED`.
292
+
293
+ `request` **/** `serviceRequest` **rules:** `method` is `GET` | `POST` | `PUT` | `PATCH` | `DELETE`. `path` must start with `/`, no scheme, stay on the declared origin (cloud API or service loopback). Guest parses `body` as JSON when needed.
294
+
295
+ ### Toast buttons
296
+
297
+ `ToastRequest.copy` is an optional boolean or `{ text: string }`. `true` copies the displayed message; an object supplies the clipboard value. `false` or omission adds no Copy button. The custom text must contain 1 to `GUEST_CLIPBOARD_TEXT_MAX` characters, with whitespace preserved. The displayed message is trimmed and must contain 1 to `GUEST_TOAST_MAX` characters. The client rejects invalid text lengths as `HOST_REJECTED` before sending; the host independently validates the wire payload.
298
+
299
+ `dismiss: true` adds OK. `persistent: true` disables automatic expiry and always adds OK regardless of `dismiss`, so every persistent toast can be closed. Omitted or false `persistent` retains the host's usual duration.
300
+
301
+ Copy leaves the toast open, reports success on the button, and shows a retryable error when the clipboard fails. OK dismisses only its own toast. Buttons use the host's locale and clipboard helper, retain only the supplied text and toast identity, work after guest disposal or a runtime switch, and never call back into the extension. The `toast` promise resolves after display acknowledgement.
302
+
303
+ ### Blocks in the chat
304
+
305
+ `contributes.blocks` adds components agents write in a UI block, drawn by your page with the grants of your panel. `host.onBlock` gives the call. `host.setHeight` sizes the frame, up to `GUEST_BLOCK_HEIGHT_MAX`. Set `answers: true` on a component that answers: agents are told to ask with it, a waiting page adds no Send button, and the block offers a note the agent reads with the answer; a note alone also answers, with `answered` holding its text. `host.answerBlock(text)`, called from a click, hands the agent `text` as a block's button does and starts its next turn; one answer per block, up to `GUEST_BLOCK_ANSWER_MAX` characters, and `answered` shows it after a reload. Without a click, or on a block that cannot take an answer, it rejects with `HOST_REJECTED`.
306
+
307
+ ### Background actions
308
+
309
+ `contributes.actions[].mode` accepts `"open"` or `"background"`. Omitted mode keeps panel/dialog routing and `onItem` delivery. Background actions load `background.entry` when declared, otherwise `panel.entry` (never attach-dialog HTML).
310
+
311
+ `contributes.background` is `{ entry: "<package-local .html>" }`. It starts on demand for an action or command and adds no rail icon, attach picker, or full-screen page. Identity remains in `panel.id/name/icon`. Open-mode actions, `page: true`, and enabled `attach` require `panel.entry`; invalid combinations fail as `invalid-panel`. With neither `panel.entry` nor `background.entry`, only `tools` and `providerLogos` are allowed.
312
+
313
+ When both entries exist, `background.entry` handles `onResolve` for slash commands (`surface: "background"`) instead of the visible panel. Clicking an attached chip from a background-only extension shows a no-panel notice; its browser action remains available.
314
+
315
+ Each background click mounts a fresh sandboxed iframe and sends one `action` request (`id`, `GuestActionItem`). `host.onAction` sends `action-result` (`{ ok: true }` or `{ ok: false, error }` capped at `GUEST_RESOLVE_ERROR_MAX` chars); there is no acknowledgement for `action-result`. `ready.surface` is `"background"` and `ready.item` is `null`; context updates never replay the action. The 20 s deadline covers loading and execution, with at most 8 concurrent invocations. Completion, failure, timeout, disabling, lost approval, update/removal, runtime switch, and host unmount release the frame without rolling back completed effects or retrying.
316
+
317
+ See [Actions without opening a panel](./README.md#actions-without-opening-a-panel) for a toast example.
318
+
319
+ ### Late generate answers
320
+
321
+ A `generate` call runs to the server's deadline with no cancellation even if the panel closes, switches projects, or reloads. If the original frame is gone when the answer arrives, the host keeps it for 1 hour (up to 8 per extension, oldest dropped) in memory for the same extension, surface, project, and window, delivering it once via `onLateGenerateResult` as soon as a listener registers (or immediately if one is active). Failed generations are kept as `{ ok: false, code, error }`. Hidden frames (background actions and slash-command resolver frames) do not receive or leave kept answers. Page reload, app restart, another window, disabling/removing/reinstalling, or withdrawing `model` approval drops kept answers. Older hosts omit `features.lateGenerateResults`.
322
+
323
+ `request` is the trimmed `{ prompt, system?, maxOutputTokens? }` the frame sent; use it to match against your pending requests.
324
+
325
+ ```ts
326
+ host.onLateGenerateResult((late) => {
327
+ if (late.request.system !== SUMMARY_SYSTEM) return;
328
+ if (late.ok) showSummary(late.result.text);
329
+ else showError(late.error);
330
+ });
331
+ ```
332
+
333
+ ### Anchored popovers
334
+
335
+ `openPopover` accepts `{ id, anchor: { x, y, width, height }, width, height, side?, focus?, data }`. The anchor uses CSS pixels relative to the calling iframe's viewport. Width is 160..640 pixels, height is 48..480 pixels, and `data` is JSON limited to 16,000 serialized characters. IDs contain 1..80 ASCII letters, digits, underscores or hyphens. Use a new id for each opening. `side` is `left`, `right`, `top` or `bottom`, defaulting to `left`; the host flips or shifts the card to fit the viewport. `focus` defaults to false, so pointer previews do not take keyboard focus.
336
+
337
+ The host loads the caller's existing package entry in a fresh `sandbox="allow-scripts"` iframe with `surface: 'popover'`. Render the card from `ready.popover.data` instead of mounting your ordinary page. Apply subsequent theme snapshots without repeating data loads. The child inherits the extension's approved capabilities and existing host APIs. It cannot open another popover or choose an entry, URL or HTML document.
338
+
339
+ Visible Web and Electron panel, page, and status frames advertise `features.popovers`; dialogs, background frames, file editors, and popovers do not. `mountPopoverAnchor` opens on mouse hover, keyboard focus, and touch/pen tap (on touch, the tap replaces the element's click). Older hosts reject with `UNSUPPORTED`. Each opening loads a new frame, so cold loading and relay transport can delay the preview.
340
+
341
+ Only one extension popover is active per host document. Opening another retires the previous one. Escape, outside interaction, owner scrolling, resizing, owner removal and changes to project, runtime, installation or authorization dismiss it. A host modal dialog takes precedence and closes previews. Close events name the opening and one of `escape`, `outside`, `anchor`, `owner`, `closed`, or `replaced`. A closing child uses `host.close()` or `closePopover(ready.popover.id)`. The SDK forwards Escape and pointer/focus activity from the child, whose events cannot bubble across the sandbox.
342
+
343
+ A `focus: true` request requires the source frame to have focus. Non-focusing previews are constrained to a visible anchor in the source frame; the host cannot verify pointer activity inside an opaque-origin guest document. The child can use `host.setHeight` to fit its content within the popover height limit; this resizes only that child and includes the host border. Scrolling an unrelated host panel does not dismiss the preview.
344
+
345
+ Use `mountPopoverAnchor` from `ohpichamber-sdk/ui` for DOM anchors. It measures the element, handles hover and keyboard opening, reports activity while the pointer crosses between frames, and retires the preview when the anchor scrolls away or is removed. Retain and call its `dispose()` when replacing rows. Low-level callers must perform those lifecycle steps themselves. The host can validate the source iframe and rectangle but cannot inspect an element inside its sandbox.
346
+
347
+ ### 1.3 Error codes (`HostRequestError.code`)
348
+
349
+
350
+ | Code | When |
351
+ | ------------------ | --------------------------------------------- |
352
+ | `HOST_UNAVAILABLE` | No window, not in iframe, or disposed |
353
+ | `HOST_TIMEOUT` | No answer for 20s |
354
+ | `HOST_REJECTED` | Host refusal, or unknown wire code |
355
+ | `DISCONNECTED` | No token / Linear connection |
356
+ | `DISABLED` | Extension paused in Settings |
357
+ | `BAD_PATH` | Path left origin or malformed |
358
+ | `NO_INTEGRATION` | Manifest has no `integration` |
359
+ | `NO_SESSION` | `prompt` / `sessionLink` with no open session |
360
+ | `SESSION_BUSY` | `prompt({ send: true })` while busy |
361
+ | `NO_SERVICE` | No service, not approved, or not running |
362
+ | `NOT_GRANTED` | The user has not approved this capability |
363
+ | `NO_DIRECTORY` | Relative file path with no open project |
364
+ | `NOT_FOUND` | `readFile` / `listDir` on a path that does not exist |
365
+ | `FILE_TOO_LARGE` | File or content over 2 000 000 characters |
366
+ | `DENIED` | The operating system refused the file access |
367
+ | `NO_MODEL` | `generate` with no usable Small Model |
368
+ | `MODEL_FAILED` | The Small Model returned an error |
369
+ | `UNSUPPORTED` | This host surface cannot do that (for example `openCommit` without a Diff view, or `openWalkthrough` in Mini Chat) |
370
+ | `SERVICE_FAILED` | Service crashed or never became ready |
371
+ | `REQUEST_FAILED` | `serviceRequest` was sent but got no usable answer; the service may have acted on it |
372
+ | `RESPONSE_TOO_LARGE` | `request` / `serviceRequest` answer over 8 000 000 bytes; the call ran, ask for a smaller page |
373
+
374
+
375
+ ### 1.4 Field limits (client clamps before send)
376
+
377
+
378
+ | Field | Max |
379
+ | -------------------------------- | --------- |
380
+ | Clipboard text | 32 000 |
381
+ | Compose / prompt / attach `text` | 16 000 |
382
+ | Attach `data` (serialized) | 16 000 |
383
+ | Attach `id` | 128 |
384
+ | Attach `title` | 200 |
385
+ | Attach `url` | 2 000 |
386
+ | Attach `author` | 80 |
387
+ | Branch name | 200 |
388
+ | Request path | 2 000 |
389
+ | Request body | 64 000 |
390
+ | Request response (bytes) | 8 000 000 |
391
+ | Request timeout | 20 000 ms |
392
+ | `resolve` answer (host waits) | 20 000 ms |
393
+ | Background action loading and execution | 20 000 ms |
394
+ | Badge count | 999 |
395
+ | Message item `text` | 200 000 |
396
+ | Session item (serialized) | 2 000 000 |
397
+ | File path | 1 024 |
398
+ | File content (read and write) | 2 000 000 |
399
+ | `listDir` entries | 2 000 |
400
+ | `generate` prompt / system | 64 000 / 8 000 |
401
+ | `generate` `maxOutputTokens` | 4 000 |
402
+ | `generate` answer | 256 000 |
403
+ | `generate` timeout | 960 000 ms |
404
+
405
+
406
+ ---
407
+
408
+ ## 2. `ohpichamber-sdk/ui` — drawing kit
409
+
410
+ DOM building blocks that use host tokens. They do **not** call the provider or `connectHost`. You compose the screen and wire callbacks yourself.
411
+
412
+ Always call theme first:
413
+
414
+ ```ts
415
+ import { applyHostReady, mountList } from 'ohpichamber-sdk/ui';
416
+
417
+ let mounted = false;
418
+ host.onReady((ctx) => {
419
+ applyHostReady(ctx, document.documentElement);
420
+ if (mounted) return;
421
+ mounted = true;
422
+ // then mount…
423
+ });
424
+ ```
425
+
426
+ Every mount returns `{ update(partial), dispose() }`. `update` merges the fields you pass and repaints; `dispose` removes the node and its listeners.
427
+
428
+ Selection controls report a proposed value; the caller commits it with `update`. Use `activeId` for tabs, `value` for selects, and `checked` for checkboxes and switches. Text and search inputs display typing immediately, but call `update({ value })` too so later updates do not restore stale props. Button clicks do not change `variant`; use tabs for mode selection. Preserve input state across tab changes instead of remounting empty fields.
429
+
430
+ ```ts
431
+ import { mountTabs } from 'ohpichamber-sdk/ui';
432
+
433
+ let activeId = 'convert';
434
+ const tabs = mountTabs(root, {
435
+ items: [{ id: 'convert', label: 'Convert' }, { id: 'format', label: 'Format' }],
436
+ activeId,
437
+ onChange: (next) => {
438
+ activeId = next;
439
+ tabs.update({ activeId });
440
+ // Show the matching panel while preserving its draft values.
441
+ },
442
+ });
443
+ ```
444
+
445
+ ### 2.1 Theme
446
+
447
+
448
+ | Function | Role |
449
+ | ----------------------------- | --------------------------------------------------------- |
450
+ | `applyHostReady(ctx, root)` | Writes theme tokens + `data-oc-surface` / `data-oc-theme` |
451
+ | `applyHostTheme(theme, root)` | Tokens only |
452
+
453
+
454
+ ### 2.2 Mount functions
455
+
456
+
457
+ | Function | Use for | Main props |
458
+ | --------------------------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------- |
459
+ | `mountButton(root, props)` | Button | `label`, `onClick`, `variant?` (`default` / `secondary` / `outline` / `ghost` / `destructive`), `size?` (`default` / `sm` / `xs`), `disabled?`, `loading?` |
460
+ | `mountTextField(root, props)` | Input or textarea | `value`, `onChange`, `label?`, `placeholder?`, `password?`, `multiline?`, `rows?`, `disabled?`, `error?`, `helper?`, `mono?` |
461
+ | `mountSearchField(root, props)` | Search box | `value`, `onChange`, `placeholder?`, `label?`, `autofocus?` |
462
+ | `mountSelect(root, props)` | Dropdown | `value`, `options: { id, label, hint? }[]`, `onChange`, `label?`, `placeholder?`, `searchable?`, `searchPlaceholder?`, `disabled?` |
463
+ | `mountCheckbox` / `mountSwitch` | Checkbox / toggle | `label`, `checked`, `onChange`, `disabled?`, `description?` |
464
+ | `mountTabs(root, props)` | Pill tabs | `items: { id, label, count? }[]`, `activeId`, `onChange`, `trackBackground?` |
465
+ | `mountBadge(root, props)` | Pill | `label`, `tone?` (`neutral` / `primary` / `success` / `warning` / `error` / `info`) |
466
+ | `mountList(root, props)` | Keyboard list | `items: { id, title, subtitle?, leading?, meta?, badge?, disabled? }[]`, `onSelect`, `selectedId?`, `emptyText?`, `ariaLabel?` |
467
+ | `mountEmpty(root, props)` | Empty / disconnected state | `title`, `body?`, `action?: { label, onClick }` |
468
+ | `mountSpinner(root, props?)` | Loading ring | `size?` (`sm` / `default`), `label?` |
469
+ | `mountBanner(root, props)` | Notice | `tone` (`info` / `success` / `warning` / `error`), `title`, `body?`, `action?` |
470
+ | `mountSeparator(root, props?)` | Divider | `label?` |
471
+ | `mountProgress(root, props)` | Progress bar | `value` (0..100), `tone?`, `label?` |
472
+ | `mountMenu(root, props)` | Action dropdown | `label`, `items: ({ id, label, destructive?, disabled? } \| { separator: true })[]`, `onSelect`, `variant?`, `size?` |
473
+ | `mountText(root, props)` | Provider text | `text`, `onOpenUrl?` |
474
+
475
+
476
+ ### 2.3 Helpers
477
+
478
+
479
+ | Function | Role |
480
+ | ------------------------------------------ | --------------------------------------------------------------------------- |
481
+ | `filterSelectOptions(options, query)` | Same case-insensitive label / id match `mountSelect` uses |
482
+ | `moveListSelection(items, currentId, key)` | Keyboard step (`next` / `previous` / `first` / `last`) that skips disabled items |
483
+ | `navigationKey(event, axis?)` | Maps arrows, Home, End, Ctrl+N / Ctrl+P to a step |
484
+ | `splitTextMedia(text)` | Splits text into runs, `![alt](https://…)` images, and `[label](https://…)` links |
485
+
486
+
487
+ `mountText` keeps everything as text except `http(s)` markdown images and links. A sandboxed iframe cannot open a link itself, so pass `onOpenUrl` and forward the URL to `host.openUrl`.
488
+
489
+ ---
490
+
491
+ ## 3. Manifest and host-side parse (`ohpichamber-sdk`)
492
+
493
+ Used by the OhPiChamber host and by tools that validate packages. Guests rarely call these from the iframe.
494
+
495
+ ### 3.1 Manifest block (inside `package.json`)
496
+
497
+ ```json
498
+ {
499
+ "name": "@acme/hello-panel",
500
+ "version": "1.0.0",
501
+ "ohpichamber": {
502
+ "apiVersion": 1,
503
+ "engines": { "ohpichamber": ">=1.0.0" },
504
+ "id": "acme-hello",
505
+ "name": "Hello",
506
+ "icon": "window",
507
+ "contributes": {
508
+ "panel": { "entry": "panel/index.html" },
509
+ "attach": "dialog",
510
+ "capabilities": ["prompt", "sessions", "files", "shells"],
511
+ "filesystem": ["~/.config/example/settings.json", "/tmp/acme/**"],
512
+ "actions": [
513
+ { "id": "create-task", "label": "Create task from message", "icon": "add-circle", "where": "message", "roles": ["assistant"] },
514
+ { "id": "summarize", "label": "Summarize session", "where": "session", "payload": ["messages"] }
515
+ ],
516
+ "commands": [{ "name": "task", "description": "Attach a task by id" }],
517
+ "tools": [{ "match": "tasks_*", "name": "Tasks", "icon": "checkbox-circle", "title": "{input.id}", "output": "table", "columns": ["id", "title", "status"] }],
518
+ "integration": { /* oauth | token | host */ },
519
+ "service": { /* optional local process */ }
520
+ }
521
+ }
522
+ }
523
+ ```
524
+
525
+
526
+ | Key | Rules |
527
+ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
528
+ | `version` | Semver required on install (`1.0.0`) |
529
+ | `apiVersion` | Must be `1` |
530
+ | `engines.ohpichamber` | Optional. Only `1.0.0` or `>=1.0.0`. Older host → `host-too-old` |
531
+ | `id`, `name`, `icon` | Beside `contributes`. Older packages keep them in `panel`, and that still works. `id` is kebab-case |
532
+ | `icon` | Remixicon kebab name (`window`) **or** package `.svg` path. Remixicon needs no file. An `.svg` path must exist on disk or install fails (`invalid-manifest`). No URLs/absolute paths |
533
+ | `panel.entry` | Optional visible-panel HTML path inside the package. No `..`, absolute path, or URL. Its scripts must be built. Omitting it removes the rail icon and visible views; `background.entry` can still run code. With neither entry, only `tools` and `providerLogos` plus package identity/version/engines are allowed. `hasGuestPage` means a visible panel, not background execution |
534
+ | `panel.mobile` | Optional `true` in manifest schema (inactive while `loadGuestCatalog` marks mobile `unsupported`) |
535
+ | `background.entry` | Optional package-local `.html` path. Loaded on demand for background actions and slash commands, preferred over `panel.entry` for these calls. Adds no rail icon. The file and its built scripts must exist. Malformed declarations are `invalid-background` |
536
+ | `attach` | `true` / `"panel"` → + menu opens rail; `"dialog"` → host window; omit/`false` → off menus. Object form `{ "mode": "panel" \| "dialog", "entry"?: "panel/attach.html" }`: `entry` (dialog only, same path rules as `panel.entry`, must exist with built scripts) loads instead of `panel.entry` |
537
+ | `capabilities` | Optional list of `prompt`, `sessions`, `files`, `model`, `shells`, `microphone`. `files` is read **and** write inside the open project; `model` is `generate`; `shells` is the running-shell methods; `microphone` is `openMicrophone`. Approved once at install |
538
+ | `actions` | Optional, 1–8 entries, unique kebab-case `id`, `label` 1–40 chars, optional `icon` with the `panel.icon` rules, `where: "message" \| "session" \| "selection" \| "file" \| "diff"`, optional `display: "label" \| "icon" \| "both"` on a selection, optional `mode: "open" \| "background"`. Message actions may narrow `roles` to `["user"]` / `["assistant"]`, default both. Session actions may request `payload: ["messages"]`, adding the `conversation` capability. Invalid shape is `invalid-actions`. Default `open` mode opens the guest with `ready.item`, using the attach dialog for `attach: "dialog"` and the rail otherwise. `background` calls `onAction` in a temporary hidden frame; see Background actions above |
539
+ | `commands` | Optional, 1–8 entries, unique `name` matching `/^[a-z][a-z0-9-]{0,23}$/`, optional `description` 1–80 chars (`invalid-commands`). `/name args` in the chat box calls `onResolve` instead of the model and attaches what it returns. A name the composer already has (built-in, OMP command, skill) is ignored with a console warning |
540
+ | `tools` | Optional, 1–16 entries formatting extension tool calls in chat (`invalid-tools`). `match` is the OMP tool name (`jira_search`), 1–128 chars of `[A-Za-z0-9_.:-]`, with optional trailing `*` (`jira_*`). Exact matches beat wildcards; among equals the first enabled, approved extension wins. Optional `name` (1–40), `icon` (Remixicon or package `.svg`), `title` / `subtitle` templates (1–200, `{input.path}` / `{output.path}` / `{metadata.path}`, missing paths render empty, values capped at 200), `output` (`"auto"` \| `"text"` \| `"json"` \| `"markdown"` \| `"code"` \| `"table"` \| `"card"`), `language` (`code`), `columns` (`table`, 1–16 dotted paths over output array or `output.items`), and `card` (`card`, see Tool cards below). With Code Mode, a finished script making one call matches its direct tool name (`example.findings` → `example_findings`) with the script return value as `output` |
541
+ | `providerLogos` | Optional map of 1–256 OMP provider IDs (`/^[a-z0-9][a-z0-9._-]{0,63}$/`) to package `.svg` or `.png` (up to 1 MiB each). Lookup order: uploaded logo, chosen icon, extension logo, bundled logo, models.dev logo, generic mark. First enabled, approved extension wins; SVG `currentColor` follows the theme. Bad shape is `invalid-provider-logos`; missing/empty/oversized file is `invalid-manifest` |
542
+ | `fileEditors` | Optional, 1–8 editors: unique kebab-case `id`, `title` 1–60 chars, `match` 1–16 file-name patterns (no `/`, not only wildcards), `entry` package `.html` with built scripts, optional `content` `"text"` (default) or `"binary"` (`invalid-file-editors`). See File editors above |
543
+ | `filesystem` | Optional, 1–16 globs, each 1–256 chars, starting with `/` or `~/`; `**` spans folders, `*` / `?` stay in one segment; no `..`, empty segment, or backslash (`invalid-filesystem`). Declaring it adds the `filesystem` capability and the dialog lists the globs |
544
+ | `integration` | Optional. Exactly one of `oauth`, `token`, or `host` (`provider: "linear"` only) |
545
+ | `service` | Optional local process (`entry` built `.js`, `runtime: "host"`). `provides` supports `"browser"`, `"source-control"` (needs `sourceControl`), `"notifications"` (needs `notifications`), `"tracker"` (needs `tracker`; mutually exclusive with `sourceControl`), and `"quota"` (needs `quota`). `surface: true` adds a host-drawn shared panel. See [GUEST_SERVICES.md](./GUEST_SERVICES.md) |
546
+ | `sessionEvents` | Optional, needs `service`. `{ "events": [1–4 distinct of "turn-finished", "turn-failed", "permission-asked", "question-asked"], "content"?: true }`. Host posts events across all projects to `POST /session-events`; `content: true` adds the `transcript` capability. Errors are `invalid-session-events`. See [GUEST_SERVICES.md](./GUEST_SERVICES.md#session-events-contributessessionevents) |
547
+ | `marks` | Optional `true`, needs `service` (`invalid-marks`). Adds the `marks` capability so `setMark(target, mark)` can set `{ icon, tone, text, url? }` or `null` on sidebar rows (`{ sessionId }`, `{ directory, branch }`, `{ directory }`). Declare `service.keepRunning` so marks persist |
548
+ | `notifications` | Required with `provides: ["notifications"]`, refused without it (`invalid-service`). Declares `label` (1–64), `instances`, and `token`; `panel.id` max 28 chars (`ext-<panel.id>`). See [GUEST_SERVICES.md](./GUEST_SERVICES.md#notification-channel-provides-notifications) |
549
+ | `tracker` | Required with `provides: ["tracker"]`, refused without it or alongside `sourceControl` (`invalid-service`). Declares `wire: 1`, `label` (1–64), `instances`, `auth` (`token` and/or `oauth`), `capabilities`, `stateFilters` (`open`, `all`, plus up to 14), `identifier` (`key-number` \| `number` \| `short-code`), `urls.item` (1–8 templates); `panel.id` max 28 chars (`ext-<panel.id>`). See [GUEST_SERVICES.md](./GUEST_SERVICES.md#tracker-provides-tracker) |
550
+ | `links` | Optional `{ "action": "open" \| "attach", "identifier"?: { "keys": [1–8 uppercase keys] }, "urls"?: { "origin", "identifier", "item": [1–8 templates] } }`, at least one of `identifier` / `urls`. Keys match whole words (`PROJ-123`) outside code/words/paths; `origin` is an exact `https` origin or `https://*.example.com` subdomain wildcard. `open` needs `panel.entry` (`GuestLinkItem`); `attach` adds a composer chip and disallows `{segment}`/`{segments+}` (and `identifier: "number"` with `identifier.keys`). Built-in app links keep priority. Adds `links` capability; edits re-prompt (`invalid-links`). Reference: `examples/tasks-demo` |
551
+ | `quota` | Required with `provides: ["quota"]`, refused without it (`invalid-service`). Lists up to 16 unique OMP provider IDs (`providers`) whose stored credentials the service receives; `panel.id` max 28 chars (`ext-<panel.id>`). See [GUEST_SERVICES.md](./GUEST_SERVICES.md#usage-provider-provides-quota) |
552
+ | `sourceControl` | Required with `provides: ["source-control"]`, refused without it (`invalid-service`). Declares `wire: 1`, `label`, `terminology`, `referencePrefix`, `repositoryPath`, `instances`, `capabilities`, `token`, `transport`, `limits`, `trackedItems`, `presentation`; `panel.id` max 28 chars (`ext-<panel.id>`). See [GUEST_SERVICES.md](./GUEST_SERVICES.md#source-control-provider-provides-source-control) |
553
+
554
+
555
+ Extra keys are dropped, not forwarded.
556
+
557
+ #### Tool cards
558
+
559
+ `output: "card"` draws a tool's JSON output as a card, from the output alone: no extension code runs.
560
+
561
+ ```json
562
+ {
563
+ "match": "jira_get_issue",
564
+ "name": "Jira issue",
565
+ "title": "{input.key}",
566
+ "output": "card",
567
+ "card": {
568
+ "label": "{output.key} · {output.fields.issuetype.name}",
569
+ "title": "{output.fields.summary}",
570
+ "status": { "value": "{output.fields.status.name}", "tones": { "In Progress": "info", "Blocked": "error", "Done": "success" } },
571
+ "fields": [
572
+ { "label": "Assignee", "value": "{output.fields.assignee.displayName}" },
573
+ { "label": "Priority", "value": "{output.fields.priority.name}" }
574
+ ],
575
+ "link": { "label": "Open in Jira", "url": "{output.url}" }
576
+ }
577
+ }
578
+ ```
579
+
580
+ | Part | Rules |
581
+ | ---- | ----- |
582
+ | `label`, `title` | Optional templates, 1–200 chars, at least one `{output.path}` placeholder; `{input.…}` and `{metadata.…}` are refused |
583
+ | `status` | Optional `{ value, tones? }`. `value` is a template like the above. `tones` maps up to 16 status texts (1–64 chars, matched exactly) to `"neutral"` \| `"info"` \| `"success"` \| `"warning"` \| `"error"`; a status without an entry is neutral |
584
+ | `fields` | Optional, 1–8 of `{ label, value }`: `label` plain text 1–40, `value` a template |
585
+ | `link` | Optional `{ label, url }`: `label` plain text 1–40. `url` is `{output.path}` alone (the output holds the address), or an `https://` address written around `{output.path}` placeholders, which may also read `{settings.<id>}`: a `contributes.integration.settings` field declared without `secret` |
586
+
587
+ At least one of `label`, `title`, `status`, `fields`. Unknown keys are refused. `card` without `output: "card"`, or the reverse, is `invalid-tools`, and the message names the place (`contributes.tools[0].card.link.url: …`).
588
+
589
+ - An object output is one card. An array, or an object with an `items` array, is a list: one row per item with its label, title, first field and status, the first 200 items, no link. In a row `{output.path}` reads the item.
590
+ - A path that is absent, or holds `null`, a blank string, an object or an array, is missing. A part with nothing resolved is hidden. When no label, title, status or field resolves, or the output is not JSON, the chat shows the output as it would without the rule.
591
+ - The link shows only for an `https` address without a user name or password, at most 2,048 characters. In a written address every placeholder has to resolve and each value is percent-encoded, so a value cannot change the host or path the manifest wrote; a value that would be a `.` or `..` path step gives no link. In the host a placeholder stands between dots or at either end: `https://tracker.example{output.path}` is refused, and a placeholder that ends the host lets its value choose the host. `https://{settings.site}/browse/{output.key}` works when `site` is a bare host name; a full address, a port or a path in the setting gives no link.
592
+ - `card` requires a host that supports `output: "card"`; older hosts reject it with `invalid-tools`.
593
+
594
+ ### 3.2 Parse / version helpers
595
+
596
+
597
+ | Export | Role |
598
+ | -------------------------------------------------- | --------------------------------------------------------- |
599
+ | `parseManifest(document)` (`ohpichamber-sdk/schemas`) | Typed document → success/failure (does not throw on junk) |
600
+ | `parseManifestJson(json)` (`ohpichamber-sdk/schemas`) | String → same result |
601
+ | `guestToolCardSchema` (`ohpichamber-sdk/schemas`) | The zod schema of a tool rule's `card`, for a host that re-reads a catalog row |
602
+ | `resolveAttachMode(attach)` | Normalize to `'panel' \| 'dialog' \| null` |
603
+ | `resolveAttachEntry(contributes)` | Dialog page from the object form, or `null` when the dialog reuses `panel.entry` |
604
+ | `hasGuestPage(contributes)` | `true` when `panel.entry` is set; background-only and tools-only packages return `false` |
605
+ | `resolveIntegrationAuth` / `resolveIntegrationApi` | Auth kind and API origin |
606
+ | `toPublicIntegration` / `toPublicService` | Catalog-safe public slices |
607
+ | `isGuestPackageSvgIcon` | Whether icon is a package SVG path |
608
+ | `compareOhPiChamberVersions` | Semver compare |
609
+ | `hostMeetsOhPiChamberEngine` | Host vs `engines.ohpichamber` floor |
610
+ | `ohPiChamberEngineMinimum` | Normalize `>=1.0.0` → floor string |
611
+ | `parseOhPiChamberVersion` | Parse `x.y.z` |
612
+
613
+
614
+ ### 3.3 Protocol helpers (host + guest tooling)
615
+
616
+
617
+ | Export | Role |
618
+ | ----------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
619
+ | `readHostMessage` (`ohpichamber-sdk`) | Guest-side read of a host push; no schema library |
620
+ | `parseHostMessage` / `parseGuestMessage` (`ohpichamber-sdk/schemas`) | Host-side typed parse |
621
+ | `hostMessageSchema` / `guestMessageSchema` (`ohpichamber-sdk/schemas`) | Zod schemas for `postMessage` data |
622
+ | `clampAttachRequest` / `clampStartSessionRequest` / `clampPromptRequest` | Enforce field max lengths |
623
+ | `isGuestRequestPath` / `isGuestRequestResult` / `isStartSessionResult` / `isPromptResult` / `isServiceStatusResult` | Narrow result payloads |
624
+ | `isGuestAttachItem` / `isGuestMessageItem` / `isGuestSessionItem` / `isGuestLinkItem` | Narrow `ready.item` |
625
+ | `clampBadgeCount` / `guestActionsNeedConversation` | Badge range; whether declared actions need `conversation` |
626
+ | `isHostRequestErrorCode` / `resolveHostRequestErrorCode` | Error code validation |
627
+
628
+
629
+ Constants: `OHPICHAMBER_SDK_CHANNEL`, `OHPICHAMBER_SDK_API_VERSION`, `HOST_LINEAR_API_ORIGIN`, `GUEST_*_MAX`, `GUEST_REQUEST_TIMEOUT_MS`, `GUEST_ACTIONS_MAX`, `GUEST_COMMANDS_MAX`, `GUEST_COMMAND_NAME`, `GUEST_TOOLS_MAX`, `GUEST_TOOL_MATCH`, `GUEST_TOOL_OUTPUTS`, `HOST_REQUEST_ERROR_CODES`, `SERVICE_STATUS_VALUES`, `SESSION_LIFECYCLE_PHASES`, `START_SESSION_SENT`.
630
+
631
+ Wire messages added for these: host → guest `resolve` (`{ id, payload: { command, args } }`), guest → host `resolve-result` (`{ id, payload: { item } | { error } }`, no `result` comes back) and `badge` (`{ count }`).
632
+
633
+ ---
634
+
635
+ ## 4. Local services (`contributes.service`)
636
+
637
+ For Docker sockets, CLI binaries, kubectl, and similar. The sandboxed iframe cannot dial Unix sockets; the host spawns a package entry and proxies HTTP.
638
+
639
+ Panel → `serviceRequest` → host → `127.0.0.1:port` → service process → socket/CLI.
640
+
641
+
642
+ | Panel call | Role |
643
+ | ----------------------------------------------- | -------------------------------- |
644
+ | `serviceRequest({ method, path, query?, body? })` | Proxy to this guest's service only |
645
+ | `serviceStatus()` | Lifecycle state |
646
+
647
+
648
+ Manifest sketch: `service.entry` (path to **built** JS, e.g. `service/main.js`), `runtime: "host"`, `permissions.sockets` and/or `permissions.exec`. Install refuses with `missing-build` when that file is absent. Declaring a service adds `service` to the capabilities the user approves at install; until then `serviceRequest` is `NO_SERVICE`.
649
+
650
+ Full local-service contracts, provider schemas, outbound proxies, and host callbacks (`createServiceHost`, `contributes.sessionEvents`, `contributes.waits`, `contributes.mentions`, `surface: true`, env vars, `/health`, grants, socket overrides) live in [GUEST_SERVICES.md](./GUEST_SERVICES.md).
651
+
652
+ Provider HTTP entrypoints and SDK helpers at a glance:
653
+ - `provides: ["browser"]` → `POST /browser-control`, `readBrowserProviderRequest` ([browser provider](./GUEST_SERVICES.md#browser-provider-provides-browser))
654
+ - `provides: ["source-control"]` → `POST /source-control` (`SOURCE_CONTROL_PROVIDER_PATH`), `readSourceControlProviderRequest`, `createSourceControlForge`, `sourceControlProviderSchemasV1` ([source-control provider](./GUEST_SERVICES.md#source-control-provider-provides-source-control), `examples/source-control-provider`)
655
+ - `provides: ["notifications"]` → `POST /notifications` (`NOTIFICATIONS_PROVIDER_PATH`), `readNotificationsProviderRequest`, `createNotificationsOutbound`, `notificationsProviderSchemasV1` ([notification channel](./GUEST_SERVICES.md#notification-channel-provides-notifications), `examples/notification-webhook`)
656
+ - `provides: ["tracker"]` → `POST /tracker` (`TRACKER_PROVIDER_PATH`), `readTrackerProviderRequest`, `createTrackerOutbound`, `trackerProviderSchemasV1` ([tracker](./GUEST_SERVICES.md#tracker-provides-tracker), `examples/tracker-provider`)
657
+ - `provides: ["quota"]` → `POST /quota` (`QUOTA_PROVIDER_PATH`), `readQuotaProviderRequest`, `quotaProviderSchemasV1` ([usage provider](./GUEST_SERVICES.md#usage-provider-provides-quota), `examples/quota-provider`)
658
+ - Host callbacks, marks, schedules, mentions → `createServiceHost`, `readServiceScheduleRequest`, `POST /schedule`, `MENTIONS_SEARCH_PATH`, `MENTIONS_RESOLVE_PATH` ([calling OhPiChamber](./GUEST_SERVICES.md#calling-ohpichamber))
659
+ - Session events (`contributes.sessionEvents`) → `POST /session-events` (`SESSION_EVENTS_PATH`), `readSessionEventRequest`, `sessionEventResultSchema` ([session events](./GUEST_SERVICES.md#session-events-contributessessionevents), `examples/session-events-log`)
660
+ - Shared surface (`surface: true`) → `GET /surface/frame`, `POST /surface/input`, `readSurface*` ([shared surface](./GUEST_SERVICES.md#shared-surface-surface-true))
661
+
662
+ Bundle the service with the Node target:
663
+
664
+ ```bash
665
+ bunx ohpichamber-guest-bundle --node service/main.ts service/main.js
666
+ ```
667
+
668
+ ---
669
+
670
+ ## 5. What this package does not provide
671
+
672
+ Frozen on `apiVersion` 1 — named in docs, no host hole yet:
673
+
674
+ - Host-side `issues.search` / `issues.get` (guest draws the list; chip is `attach`)
675
+ - Public OAuth broker
676
+ - Keyboard shortcuts for commands, raw git remotes, magic prompts
677
+ - Second `host.provider` beyond Linear
678
+ - Arbitrary filesystem access from the page (only the open project with `files`, or declared `contributes.filesystem` globs), terminal, pairing, or host React components. A declared `service` is outside these limits: it is a process with the user's rights and no sandbox
679
+ - Network access from the page. Pages run under a Content Security Policy: scripts, styles, images, fonts, media and workers come from the package itself or `data:`/`blob:`, and `fetch` reaches only the package's own files. Ship fonts and images inside the package. To talk to an outside service, use `request` (the integration's `apiOrigin`) or declare up to 8 https origins in `contributes.origins`, for example `"origins": ["https://fonts.example.com"]`. The user approves that list at install, and again when an update adds to it. Approved origins are open to `fetch`, images, fonts, styles and media, never to scripts or workers. A `fetch` whose response you read also needs that server to allow CORS for the `null` origin, since the page's origin is opaque
680
+
681
+ A self-navigation is refused by Electron's main-process guard when the destination falls outside that window's allowed app origins. Web/PWA has no equivalent navigation hook. Do not use guest navigation to transfer data or assume the browser host blocks it.
682
+
683
+ Do not go around the guest contract through `RuntimeAPIs`.
684
+
685
+ ---
686
+
687
+ ## 6. Minimal panel sketch
688
+
689
+ Mount once and keep the handles. `onReady` can repeat when the session or theme changes. Field listeners replay their current values too; compare relevant fields before fetching data again. For a complete request example with stale-response handling, see [the extension example](https://github.com/Shizuku-Yume/ohpichamber/tree/main/packages/sdk).
690
+
691
+ ```ts
692
+ import { connectHost } from 'ohpichamber-sdk';
693
+ import { applyHostReady, mountList, mountEmpty } from 'ohpichamber-sdk/ui';
694
+
695
+ const host = connectHost();
696
+ const root = document.querySelector('#root')!;
697
+
698
+ let mounted = false;
699
+ host.onReady((ctx) => {
700
+ applyHostReady(ctx, document.documentElement);
701
+ if (mounted) return;
702
+ mounted = true;
703
+
704
+ const signInRoot = root.appendChild(document.createElement('div'));
705
+ const listRoot = root.appendChild(document.createElement('div'));
706
+ mountEmpty(signInRoot, {
707
+ title: 'Connect Acme',
708
+ action: { label: 'Sign in', onClick: () => { void host.oauthStart(); } },
709
+ });
710
+
711
+ mountList(listRoot, {
712
+ items: [], // fill from host.request
713
+ onSelect: (id) => {
714
+ void host.attach({
715
+ providerId: 'acme-hello',
716
+ id,
717
+ title: id,
718
+ url: '',
719
+ });
720
+ },
721
+ });
722
+ host.onConnection((connection) => {
723
+ signInRoot.hidden = connection.connected;
724
+ listRoot.hidden = !connection.connected;
725
+ });
726
+ });
727
+ ```
728
+
729
+ ---
730
+
731
+ ## Related files
732
+
733
+
734
+ | File | Audience |
735
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
736
+ | [README.md](./README.md) | Package overview and first extension |
737
+ | [DOCUMENTATION.md](./DOCUMENTATION.md) | Agent / maintainer invariants |
738
+ | [GUEST_SERVICES.md](./GUEST_SERVICES.md) | Local service contract |
739
+ | [src/ui/DOCUMENTATION.md](./src/ui/DOCUMENTATION.md) | UI kit invariants |
740
+ | [sdk.mdx](https://github.com/Shizuku-Yume/ohpichamber/blob/main/packages/docs/content/docs/sdk.mdx) / [sdk/host.mdx](https://github.com/Shizuku-Yume/ohpichamber/blob/main/packages/docs/content/docs/sdk/host.mdx) / [sdk/ui.mdx](https://github.com/Shizuku-Yume/ohpichamber/blob/main/packages/docs/content/docs/sdk/ui.mdx) | Author-facing website pages |