@blackbelt-technology/pi-dashboard-chat-gateway-plugin 0.0.0-stage → 0.8.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 (38) hide show
  1. package/NOTICE +29 -0
  2. package/README.md +29 -2
  3. package/package.json +80 -4
  4. package/src/adapters/base.ts +309 -0
  5. package/src/adapters/discord-payload.ts +464 -0
  6. package/src/adapters/discord.ts +709 -0
  7. package/src/adapters/fake.ts +289 -0
  8. package/src/client/index.tsx +332 -0
  9. package/src/client/team-controls-panel.tsx +287 -0
  10. package/src/configSchema.json +145 -0
  11. package/src/guard/index.ts +143 -0
  12. package/src/guard/policy.ts +57 -0
  13. package/src/server/auth.ts +121 -0
  14. package/src/server/binding.ts +121 -0
  15. package/src/server/config.ts +114 -0
  16. package/src/server/dispatch.ts +40 -0
  17. package/src/server/gateway.ts +1276 -0
  18. package/src/server/index.ts +507 -0
  19. package/src/server/prompts.ts +189 -0
  20. package/src/server/routing.ts +144 -0
  21. package/src/server/seam.ts +170 -0
  22. package/src/server/stream.ts +115 -0
  23. package/src/server/team/audit.ts +137 -0
  24. package/src/server/team/authorize.ts +150 -0
  25. package/src/server/team/binding.ts +73 -0
  26. package/src/server/team/controller.ts +205 -0
  27. package/src/server/team/disarm-store.ts +60 -0
  28. package/src/server/team/health.ts +54 -0
  29. package/src/server/team/output-filter.ts +75 -0
  30. package/src/server/team/pacing.ts +115 -0
  31. package/src/server/team/provisioner.ts +320 -0
  32. package/src/server/team/provisioning-store.ts +167 -0
  33. package/src/server/team/surface.ts +199 -0
  34. package/src/server/team/team-config.ts +257 -0
  35. package/src/server/team/tier.ts +107 -0
  36. package/src/server/team/workspace.ts +112 -0
  37. package/src/shared/index.ts +1 -0
  38. package/src/shared/types.ts +325 -0
package/NOTICE ADDED
@@ -0,0 +1,29 @@
1
+ chat-gateway vendors the platform-adapter contract from @gamalan/pi-gateway.
2
+
3
+ Upstream: @gamalan/pi-gateway
4
+ Version: 1.10.1
5
+ License: MIT
6
+ Copyright: (c) the pi-gateway authors
7
+
8
+ Vendored files:
9
+ - src/adapters/base.ts — the `PlatformAdapter` contract / `BaseAdapter`
10
+ abstract class. Copied VERBATIM (it is pure: no
11
+ imports, no side effects).
12
+
13
+ NOT vendored (deliberately), and why:
14
+ - upstream `index.ts` — its hub. The dashboard is the hub.
15
+ - upstream `sessions/store.ts` — SQLite session store. The dashboard
16
+ already owns a session registry.
17
+ - upstream `extensions/pi-gateway-ask-user-rpc.ts`
18
+ — an rpc-mode hack. Replaced by the
19
+ dashboard's PromptBus path.
20
+ - upstream `adapters/discord.ts` — its transport is the ambient global
21
+ `WebSocket` + `fetch`, it derives the bot
22
+ id from the token prefix (incorrect), and
23
+ its `stop()` leaks a reconnect timer
24
+ (`onclose` unconditionally re-arms
25
+ `setTimeout(start, 5000)`). This package
26
+ implements the SAME contract on `discord.js`
27
+ instead (see design.md, "Vendoring").
28
+
29
+ The MIT license requires this attribution to travel with the derived work.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # @blackbelt-technology/pi-dashboard-chat-gateway-plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Dashboard plugin that drives dashboard pi sessions from a chat platform —
4
+ **Discord ships first**, behind a pluggable `PlatformAdapter` contract
5
+ (vendored MIT `base.ts`; see `NOTICE`).
6
+
7
+ Headless browser-protocol client: it consumes the same session frames the React
8
+ client does (an in-process `subscribeSession` seam) and speaks the existing
9
+ `send_prompt` / `prompt_response` / `spawnSession` control lane, so **no bridge
10
+ or server protocol changes**.
11
+
12
+ - **Settings section** (`settings-section` → `ChatGatewaySettings`) — bot token
13
+ (write-only), mandatory `allowedRoots` whitelist, fixed `channelKey → cwd`
14
+ map, default cwd, L1 allowlist, L2 admins, L4 group-channel opt-in, steer
15
+ prefix, plus a read-only bindings view.
16
+ - **Inbound** — allowlisted message → bind (admin-only) / attach / resume / spawn
17
+ → `send_prompt`; a `!`-prefixed message forces `delivery: steer`.
18
+ - **Outbound** — assistant deltas edit ONE Discord message in place (throttled),
19
+ chunking past 2000 chars into a new message; `prompt_request` renders native
20
+ Discord controls, with `multiselect`/`batch` sequenced into sub-prompts.
21
+ - **L3 tool guard** — a companion `tool_call` extension (exported at
22
+ `./guard`) loaded into gateway-**spawned** sessions; deny-first, fail-closed.
23
+
24
+ Security posture: **inert** until a token is set (no adapter, no socket, no
25
+ timer). Every spawn cwd passes a real-path `allowedRoots` containment boundary,
26
+ including on resume. Binding is admin-gated; interactive clicks are
27
+ re-authorized; the bot token is `writeOnly` and never logged or returned.
28
+
29
+ Setup: [`docs/chat-gateway.md`](../../docs/chat-gateway.md).
30
+ See change: `add-chat-gateway`.
package/package.json CHANGED
@@ -1,6 +1,82 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-chat-gateway-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.8.0",
4
+ "description": "Inbound chat control plane — drive dashboard pi sessions from a chat platform (Discord shipped). Extensible adapter layer; no bridge or server protocol change.",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "type": "module",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
13
+ "directory": "packages/chat-gateway"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./src/client/index.tsx",
18
+ "default": "./src/client/index.tsx"
19
+ },
20
+ "./client": {
21
+ "types": "./src/client/index.tsx",
22
+ "default": "./src/client/index.tsx"
23
+ },
24
+ "./server": {
25
+ "types": "./src/server/index.ts",
26
+ "default": "./src/server/index.ts"
27
+ },
28
+ "./guard": {
29
+ "types": "./src/guard/index.ts",
30
+ "default": "./src/guard/index.ts"
31
+ },
32
+ "./shared": {
33
+ "types": "./src/shared/index.ts",
34
+ "default": "./src/shared/index.ts"
35
+ }
36
+ },
37
+ "files": [
38
+ "src/",
39
+ "NOTICE",
40
+ "!**/AGENTS.md",
41
+ "!**/*.AGENTS.md",
42
+ "!**/__tests__",
43
+ "!**/*.test.ts",
44
+ "!**/*.test.tsx"
45
+ ],
46
+ "pi-dashboard-plugin": {
47
+ "id": "chat-gateway",
48
+ "displayName": "Chat Gateway",
49
+ "priority": 100,
50
+ "requiredApi": "^0.x",
51
+ "client": "./src/client/index.tsx",
52
+ "server": "./src/server/index.ts",
53
+ "configSchema": "./src/configSchema.json",
54
+ "claims": [
55
+ {
56
+ "slot": "settings-section",
57
+ "component": "ChatGatewaySettings",
58
+ "config": {
59
+ "tab": "general"
60
+ }
61
+ }
62
+ ]
63
+ },
64
+ "peerDependencies": {
65
+ "fastify": "^5.0.0",
66
+ "react": ">=18.0.0",
67
+ "react-dom": ">=18.0.0"
68
+ },
69
+ "dependencies": {
70
+ "@blackbelt-technology/dashboard-plugin-runtime": "^0.8.0",
71
+ "@blackbelt-technology/pi-dashboard-mcp-server-plugin": "^0.8.0",
72
+ "@blackbelt-technology/pi-dashboard-shared": "^0.8.0",
73
+ "discord.js": "^14.27.0"
74
+ },
75
+ "devDependencies": {
76
+ "@testing-library/react": "^16.1.0",
77
+ "@types/react": "^19.0.0",
78
+ "@types/react-dom": "^19.0.0",
79
+ "react": "^19.0.0",
80
+ "react-dom": "^19.0.0"
81
+ }
82
+ }
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Platform Adapter Base - Interface for Hermes-style platform adapters
3
+ */
4
+
5
+ // ── Interactive UI types ──────────────────────────────────────────────────
6
+
7
+ /** Platform-agnostic description of an interactive prompt from pi. */
8
+ export interface InteractivePrompt {
9
+ requestId: string;
10
+ method:
11
+ | "select"
12
+ | "confirm"
13
+ | "input"
14
+ | "editor"
15
+ | "notify"
16
+ | "setStatus"
17
+ | "setWidget"
18
+ | "setTitle"
19
+ | "set_editor_text";
20
+ title: string;
21
+ message?: string;
22
+ options?: string[];
23
+ placeholder?: string;
24
+ prefill?: string;
25
+ notifyType?: "info" | "warning" | "error";
26
+ }
27
+
28
+ /** User's response to an interactive prompt. */
29
+ export interface InteractiveResponse {
30
+ requestId: string;
31
+ value?: string;
32
+ confirmed?: boolean;
33
+ cancelled?: boolean;
34
+ /**
35
+ * Platform user id of the actor. REQUIRED for L1/L4 authorization at the
36
+ * gateway edge: a group-channel member who is not allowlisted can SEE the
37
+ * bot's buttons, so a click must be re-authorized, not trusted from the
38
+ * fact that the prompt was rendered. Missing ⇒ treated as unknown ⇒ refused.
39
+ */
40
+ userId?: string;
41
+ }
42
+
43
+ // ── Message types ─────────────────────────────────────────────────────────
44
+
45
+ export interface PlatformMessage {
46
+ id: string;
47
+ platform: string;
48
+ channelId: string;
49
+ userId: string;
50
+ content: string;
51
+ timestamp: number;
52
+ metadata?: Record<string, unknown>;
53
+ }
54
+
55
+ export interface PlatformConfig {
56
+ enabled: boolean;
57
+ platform: string;
58
+ token?: string;
59
+ botToken?: string;
60
+ webhookSecret?: string;
61
+ }
62
+
63
+ export interface AdapterCallbacks {
64
+ onMessage: (message: PlatformMessage) => Promise<void>;
65
+ onTyping?: (userId: string, isTyping: boolean) => void;
66
+ onDisconnect?: () => void;
67
+ /** Fired when a user responds to an interactive prompt (button click, reply). */
68
+ onInteractiveResponse?: (response: InteractiveResponse) => void;
69
+ }
70
+
71
+ // ── Channel provisioning types ───────────────────────────────────────────
72
+
73
+ /**
74
+ * One entry in a channel's access list. Platform-agnostic: `role` covers the
75
+ * platform-default role (`@everyone` in Discord) as well as named roles.
76
+ */
77
+ export interface ChannelOverwrite {
78
+ /** Platform role id, or member id when `kind` is `"member"`. */
79
+ targetId: string;
80
+ kind: "role" | "member";
81
+ /** `true` grants view access to the channel, `false` denies it. */
82
+ viewChannel: boolean;
83
+ }
84
+
85
+ export interface ProvisionChannelInput {
86
+ /** Guild/space the channel is created in. */
87
+ guildId: string;
88
+ /** Desired channel name (a workspace name). The adapter normalizes it. */
89
+ name: string;
90
+ /**
91
+ * FULL access list, INCLUDING the platform-default-role deny. The caller
92
+ * supplies it pre-built so the create payload is a pure function of the
93
+ * input and the deny cannot be forgotten by an adapter that "just" creates.
94
+ */
95
+ overwrites: ChannelOverwrite[];
96
+ }
97
+
98
+ export interface PlatformAdapter {
99
+ readonly platform: string;
100
+ readonly config: PlatformConfig;
101
+
102
+ /**
103
+ * Initialize the adapter
104
+ */
105
+ initialize(): Promise<void>;
106
+
107
+ /**
108
+ * Start listening for messages
109
+ */
110
+ start(callbacks: AdapterCallbacks): Promise<void>;
111
+
112
+ /**
113
+ * Stop listening
114
+ */
115
+ stop(): Promise<void>;
116
+
117
+ /**
118
+ * Send a message to a channel
119
+ */
120
+ sendMessage(channelId: string, content: string): Promise<string>; // Returns message ID
121
+
122
+ /**
123
+ * Edit an existing message
124
+ */
125
+ editMessage(
126
+ channelId: string,
127
+ messageId: string,
128
+ content: string,
129
+ ): Promise<void>;
130
+
131
+ /**
132
+ * Delete a message
133
+ */
134
+ deleteMessage(channelId: string, messageId: string): Promise<void>;
135
+
136
+ /**
137
+ * Set typing indicator
138
+ */
139
+ setTyping(channelId: string, isTyping: boolean): Promise<void>;
140
+
141
+ /**
142
+ * Get adapter health status
143
+ */
144
+ getStatus(): Promise<{ connected: boolean; latency?: number }>;
145
+
146
+ /**
147
+ * Send an interactive prompt (select, confirm, input, etc.).
148
+ * Returns the platform-specific message ID for potential cleanup.
149
+ */
150
+ sendInteractive(
151
+ channelId: string,
152
+ prompt: InteractivePrompt,
153
+ ): Promise<{ messageId: string }>;
154
+
155
+ /**
156
+ * Clean up interactive elements from a message (remove buttons, etc.).
157
+ * Optional — only needed if the platform can't auto-expire interactions.
158
+ */
159
+ cleanupInteractive?(channelId: string, messageId: string): Promise<void>;
160
+
161
+ /**
162
+ * Create a PRIVATE channel in ONE operation, carrying `overwrites` in the
163
+ * creation request itself.
164
+ *
165
+ * Implementations MUST NOT create a channel and then adjust its permissions: a
166
+ * platform with no transactional create-then-permission (Discord) would leave a
167
+ * world-readable window. A platform that cannot set overwrites at create time
168
+ * MUST REJECT, not create a visible channel — a visible failure beats a leaky
169
+ * success.
170
+ */
171
+ provisionChannel?(
172
+ input: ProvisionChannelInput,
173
+ ): Promise<{ channelId: string }>;
174
+
175
+ /**
176
+ * Replace a channel's access list so it matches a changed mapping, WITHOUT
177
+ * recreating the channel. Awaitable and ordered by contract: a caller may not
178
+ * report a configuration write as succeeded until the platform reflects the
179
+ * new access, so no interval exists in which a removed principal still sees.
180
+ */
181
+ setChannelOverwrites?(
182
+ channelId: string,
183
+ overwrites: ChannelOverwrite[],
184
+ ): Promise<void>;
185
+
186
+ /** Rename a bound channel (a workspace rename). Never deletes. */
187
+ renameChannel?(channelId: string, name: string): Promise<void>;
188
+ }
189
+
190
+ /**
191
+ * Abstract base class for adapters
192
+ */
193
+ export abstract class BaseAdapter implements PlatformAdapter {
194
+ abstract readonly platform: string;
195
+ abstract config: PlatformConfig;
196
+ protected callbacks: AdapterCallbacks | null = null;
197
+ protected running = false;
198
+
199
+ async initialize(): Promise<void> {
200
+ // Override in subclass
201
+ }
202
+
203
+ async start(callbacks: AdapterCallbacks): Promise<void> {
204
+ this.callbacks = callbacks;
205
+ this.running = true;
206
+ }
207
+
208
+ async stop(): Promise<void> {
209
+ this.running = false;
210
+ this.callbacks = null;
211
+ }
212
+
213
+ /** Clean up interactive elements (remove buttons, etc.). No-op by default. */
214
+ async cleanupInteractive(
215
+ _channelId: string,
216
+ _messageId: string,
217
+ ): Promise<void> {
218
+ // Default: nothing to clean up
219
+ }
220
+
221
+ abstract sendMessage(channelId: string, content: string): Promise<string>;
222
+ abstract editMessage(
223
+ channelId: string,
224
+ messageId: string,
225
+ content: string,
226
+ ): Promise<void>;
227
+ abstract deleteMessage(channelId: string, messageId: string): Promise<void>;
228
+ abstract setTyping(channelId: string, isTyping: boolean): Promise<void>;
229
+ abstract getStatus(): Promise<{ connected: boolean; latency?: number }>;
230
+
231
+ /**
232
+ * Default interactive prompt — sends as text with instructions.
233
+ * Override in platform-specific adapters for native interactive UI.
234
+ */
235
+ async sendInteractive(
236
+ channelId: string,
237
+ prompt: InteractivePrompt,
238
+ ): Promise<{ messageId: string }> {
239
+ const text = formatGenericPrompt(prompt);
240
+ // Skip empty notifications (e.g. widget/status clears with no content)
241
+ if (!text) {
242
+ return { messageId: "0" };
243
+ }
244
+ const messageId = await this.sendMessage(channelId, text);
245
+ return { messageId };
246
+ }
247
+
248
+ protected emitMessage(message: PlatformMessage): Promise<void> {
249
+ if (this.callbacks?.onMessage) {
250
+ return this.callbacks.onMessage(message).catch((err) => {
251
+ // Log but don't crash the adapter loop
252
+ console.error(`[${this.platform}] Error in onMessage callback:`, err);
253
+ }) as Promise<void>;
254
+ }
255
+ return Promise.resolve();
256
+ }
257
+
258
+ protected generateMessageId(): string {
259
+ return `${this.platform}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
260
+ }
261
+ }
262
+
263
+ // ── Generic interactive prompt formatter (fallback for non-interactive platforms) ─┐
264
+
265
+ function formatGenericPrompt(prompt: InteractivePrompt): string {
266
+ switch (prompt.method) {
267
+ case "select": {
268
+ const options = prompt.options || [];
269
+ const numbered = options.map((opt, i) => `${i + 1}. ${opt}`).join("\n");
270
+ return `**${prompt.title}**\n\n${numbered}\n\n_Reply with the number of your choice._`;
271
+ }
272
+ case "confirm": {
273
+ const msg = prompt.message ? `\n\n_${prompt.message}_` : "";
274
+ return `**${prompt.title}**${msg}\n\n_Reply yes or no._`;
275
+ }
276
+ case "input":
277
+ case "editor": {
278
+ const hint = prompt.placeholder ? `\n\n_(${prompt.placeholder})_` : "";
279
+ const pre = prompt.prefill
280
+ ? `\n\n\`\`\`\n${prompt.prefill}\n\`\`\`\n\n_Reply with your ${prompt.method === "editor" ? "changes" : "input"}._`
281
+ : `\n\n_Reply with your ${prompt.method === "editor" ? "text" : "input"}._`;
282
+ return `**${prompt.title}**${hint}${pre}`;
283
+ }
284
+ case "notify":
285
+ case "setStatus":
286
+ case "setWidget":
287
+ case "setTitle":
288
+ case "set_editor_text": {
289
+ const text = prompt.message || prompt.title;
290
+ // Skip if pi clears a widget/status with no content (e.g. setWidget(name, undefined))
291
+ if (!text) {
292
+ return "";
293
+ }
294
+ const icon =
295
+ prompt.notifyType === "warning"
296
+ ? "⚠️"
297
+ : prompt.notifyType === "error"
298
+ ? "❌"
299
+ : "ℹ️";
300
+ return `${icon} ${text}`;
301
+ }
302
+ default: {
303
+ console.warn(
304
+ `[base] Unknown interactive method "${prompt.method}", falling back to plain text`,
305
+ );
306
+ return `**${prompt.title}**${prompt.message ? `\n\n_${prompt.message}_` : ""}\n\n_Reply with your response._`;
307
+ }
308
+ }
309
+ }