@blackbelt-technology/pi-dashboard-chat-gateway-plugin 0.10.0 → 0.12.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.
- package/package.json +6 -4
- package/src/client/ChatGatewaySettings.tsx +1 -12
- package/src/client/team-controls-panel.tsx +1 -9
- package/src/guard/index.ts +43 -0
- package/src/server/gateway.ts +277 -31
- package/src/server/routing.ts +1 -1
- package/src/server/seam.ts +15 -0
- package/src/server/team/authorize.ts +1 -1
- package/src/server/team/tier.ts +13 -6
- package/src/shared/guard-ready.ts +21 -0
- package/src/shared/index.ts +1 -0
package/package.json
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blackbelt-technology/pi-dashboard-chat-gateway-plugin",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
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
|
+
"keywords": [
|
|
6
|
+
"pi-dashboard-plugin"
|
|
7
|
+
],
|
|
5
8
|
"license": "MIT",
|
|
6
9
|
"publishConfig": {
|
|
7
10
|
"access": "public"
|
|
@@ -68,9 +71,8 @@
|
|
|
68
71
|
"react-dom": ">=18.0.0"
|
|
69
72
|
},
|
|
70
73
|
"dependencies": {
|
|
71
|
-
"@blackbelt-technology/dashboard-plugin-runtime": "^0.
|
|
72
|
-
"@blackbelt-technology/pi-dashboard-
|
|
73
|
-
"@blackbelt-technology/pi-dashboard-shared": "^0.10.0",
|
|
74
|
+
"@blackbelt-technology/dashboard-plugin-runtime": "^0.12.0",
|
|
75
|
+
"@blackbelt-technology/pi-dashboard-shared": "^0.12.0",
|
|
74
76
|
"discord.js": "^14.27.0"
|
|
75
77
|
},
|
|
76
78
|
"devDependencies": {
|
|
@@ -18,18 +18,7 @@
|
|
|
18
18
|
* See change: add-chat-gateway, retro-ux-plugin-settings-wave-2.
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
|
-
import {
|
|
22
|
-
SelectField,
|
|
23
|
-
SettingsGroup,
|
|
24
|
-
SettingsNotice,
|
|
25
|
-
SettingsStatusPill,
|
|
26
|
-
SettingsTable,
|
|
27
|
-
TextAreaField,
|
|
28
|
-
TextField,
|
|
29
|
-
ToggleField,
|
|
30
|
-
useSettingsDraftSource,
|
|
31
|
-
} from "@blackbelt-technology/dashboard-plugin-runtime";
|
|
32
|
-
import { usePluginConfig, usePluginSend } from "@blackbelt-technology/dashboard-plugin-runtime/context";
|
|
21
|
+
import { SelectField, SettingsGroup, SettingsNotice, SettingsStatusPill, SettingsTable, TextAreaField, TextField, ToggleField, usePluginConfig, usePluginSend, useSettingsDraftSource } from "@blackbelt-technology/dashboard-plugin-runtime";
|
|
33
22
|
import type { SlotProps } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/slot-props.js";
|
|
34
23
|
import type React from "react";
|
|
35
24
|
import { useEffect, useState } from "react";
|
|
@@ -18,15 +18,7 @@
|
|
|
18
18
|
*
|
|
19
19
|
* See change: add-chat-gateway-team-controls, retro-ux-plugin-settings-wave-2.
|
|
20
20
|
*/
|
|
21
|
-
import {
|
|
22
|
-
SettingsFacts,
|
|
23
|
-
SettingsGroup,
|
|
24
|
-
SettingsItem,
|
|
25
|
-
SettingsNotice,
|
|
26
|
-
SettingsStatusPill,
|
|
27
|
-
SettingsTable,
|
|
28
|
-
} from "@blackbelt-technology/dashboard-plugin-runtime";
|
|
29
|
-
import { usePluginConfig, usePluginMessage, usePluginSend } from "@blackbelt-technology/dashboard-plugin-runtime/context";
|
|
21
|
+
import { SettingsFacts, SettingsGroup, SettingsItem, SettingsNotice, SettingsStatusPill, SettingsTable, usePluginConfig, usePluginMessage, usePluginSend } from "@blackbelt-technology/dashboard-plugin-runtime";
|
|
30
22
|
import type React from "react";
|
|
31
23
|
import { useCallback, useEffect, useState } from "react";
|
|
32
24
|
import {
|
package/src/guard/index.ts
CHANGED
|
@@ -10,6 +10,12 @@
|
|
|
10
10
|
* PromptBus → the gateway → a Discord yes/no. An unanswered approval FAILS
|
|
11
11
|
* CLOSED (C3): the tool is blocked, never auto-allowed.
|
|
12
12
|
*
|
|
13
|
+
* Readiness (harden-agent-tool-guards D6): at `session_start` the guard announces
|
|
14
|
+
* `chat_gateway_guard_ready` with the spawn's token over `dashboard:plugin-message`, so the
|
|
15
|
+
* gateway can hold the triggering message back until the guard is proven loaded (pi treats an
|
|
16
|
+
* unresolvable `-e <ref>` as non-fatal, so a typo'd `guardExtension` would otherwise run ungated).
|
|
17
|
+
* A custom `guardExtension` MUST do the same or its spawns are refused.
|
|
18
|
+
*
|
|
13
19
|
* Trust asymmetry (by design): attached sessions (owner's own open session) are
|
|
14
20
|
* never handed this extension, so they stay ungated. This module is loaded ONLY
|
|
15
21
|
* on the spawn path.
|
|
@@ -17,6 +23,7 @@
|
|
|
17
23
|
* See change: add-chat-gateway.
|
|
18
24
|
*/
|
|
19
25
|
|
|
26
|
+
import { CHAT_GATEWAY_PLUGIN_ID, GUARD_READY_MESSAGE, GUARD_TOKEN_ENV } from "../shared/guard-ready.js";
|
|
20
27
|
import { decideToolCall, type ToolPolicy } from "./policy.js";
|
|
21
28
|
|
|
22
29
|
/** Minimal slice of the pi extension API this guard needs. */
|
|
@@ -25,6 +32,9 @@ export interface GuardPi {
|
|
|
25
32
|
event: "tool_call",
|
|
26
33
|
handler: (event: { toolName: string; toolCallId?: string; input?: unknown }, ctx: GuardCtx) => unknown,
|
|
27
34
|
): void;
|
|
35
|
+
on(event: "session_start", handler: () => unknown): void;
|
|
36
|
+
/** Bridge channel: `dashboard:plugin-message` is forwarded to the plugin server with the sender's session id. */
|
|
37
|
+
events?: { emit: (name: string, payload: unknown) => void };
|
|
28
38
|
}
|
|
29
39
|
|
|
30
40
|
/** Minimal slice of pi's extension context this guard needs. */
|
|
@@ -137,7 +147,40 @@ export function policyFromEnv(
|
|
|
137
147
|
return { defaultAction: "deny" };
|
|
138
148
|
}
|
|
139
149
|
|
|
150
|
+
/** The spawn's readiness token (same env projection as the policy); absent/empty → no announcement. */
|
|
151
|
+
export function tokenFromEnv(env: Record<string, string | undefined> = process.env): string | undefined {
|
|
152
|
+
const raw = env[GUARD_TOKEN_ENV];
|
|
153
|
+
return typeof raw === "string" && raw !== "" ? raw : undefined;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Delays (ms after `session_start`) at which the readiness announcement is repeated. pi runs the
|
|
158
|
+
* `session_start` handlers of `-e` extensions (this guard) BEFORE those registered through settings or
|
|
159
|
+
* packages (the dashboard bridge), and the bridge only starts listening for `dashboard:plugin-message`
|
|
160
|
+
* inside its own `session_start`: a single emit from here can be lost. The gateway ignores duplicates
|
|
161
|
+
* (unknown, released or refused tokens), so repeating is harmless; it stops after the last entry (the
|
|
162
|
+
* gateway's own readiness window is 30 s).
|
|
163
|
+
*/
|
|
164
|
+
export const READY_REANNOUNCE_MS: readonly number[] = [250, 1_000, 3_000, 8_000, 15_000];
|
|
165
|
+
|
|
140
166
|
export default function chatGatewayGuard(pi: GuardPi, options?: Partial<GuardOptions>): void {
|
|
141
167
|
const policy: ToolPolicy = options?.policy ?? policyFromEnv();
|
|
168
|
+
// The enforcement point is registered BEFORE readiness can be announced.
|
|
142
169
|
pi.on("tool_call", createToolCallGuard({ ...options, policy }));
|
|
170
|
+
const token = tokenFromEnv();
|
|
171
|
+
if (!token) return; // no token (older gateway / manual load): nothing to prove readiness to
|
|
172
|
+
const announce = (): void => {
|
|
173
|
+
pi.events?.emit("dashboard:plugin-message", {
|
|
174
|
+
pluginId: CHAT_GATEWAY_PLUGIN_ID,
|
|
175
|
+
messageType: GUARD_READY_MESSAGE,
|
|
176
|
+
payload: { token },
|
|
177
|
+
});
|
|
178
|
+
};
|
|
179
|
+
pi.on("session_start", () => {
|
|
180
|
+
announce();
|
|
181
|
+
for (const delay of READY_REANNOUNCE_MS) {
|
|
182
|
+
const timer = setTimeout(announce, delay);
|
|
183
|
+
(timer as { unref?: () => void }).unref?.(); // never keep the pi process alive for an announcement
|
|
184
|
+
}
|
|
185
|
+
});
|
|
143
186
|
}
|
package/src/server/gateway.ts
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
import path from "node:path";
|
|
25
25
|
import type { InteractiveResponse, PlatformAdapter, PlatformMessage } from "../adapters/base.js";
|
|
26
26
|
import { chunkForDiscord } from "../adapters/discord-payload.js";
|
|
27
|
+
import { CHAT_GATEWAY_PLUGIN_ID, GUARD_READY_MESSAGE, GUARD_READY_TIMEOUT_MS } from "../shared/guard-ready.js";
|
|
27
28
|
import type { ResolvedConfig } from "../shared/types.js";
|
|
28
29
|
import {
|
|
29
30
|
type Binding,
|
|
@@ -41,7 +42,7 @@ import {
|
|
|
41
42
|
type PromptControl,
|
|
42
43
|
toPromptControl,
|
|
43
44
|
} from "./prompts.js";
|
|
44
|
-
import type { BindingStore, SpawnCorrelator } from "./routing.js";
|
|
45
|
+
import type { BindingStore, SpawnCorrelator, SpawnMeta } from "./routing.js";
|
|
45
46
|
import type { HostSeam, SeamSession, SpawnOutcome } from "./seam.js";
|
|
46
47
|
import { createEditThrottle, type EditThrottle, shouldSteer, stripSteerPrefix } from "./stream.js";
|
|
47
48
|
import type { Grant } from "./team/authorize.js";
|
|
@@ -66,8 +67,38 @@ export interface ChatGatewayDeps {
|
|
|
66
67
|
now?: () => number;
|
|
67
68
|
/** The L1 pairing code state machine; a fresh one is minted by default. */
|
|
68
69
|
pairing?: Pairing;
|
|
70
|
+
/** Guard readiness window (D6). Injectable for tests ONLY: no config key, fixed 30 000 ms in production. */
|
|
71
|
+
guardReadyTimeoutMs?: number;
|
|
69
72
|
}
|
|
70
73
|
|
|
74
|
+
/**
|
|
75
|
+
* A guarded spawn awaiting its tool guard's readiness announcement (harden-agent-tool-guards D6).
|
|
76
|
+
* The triggering message is held here (never in `initialPrompt`); it is delivered through
|
|
77
|
+
* `send_prompt` only once the announcement carries this spawn's token AND comes from the session
|
|
78
|
+
* the spawn resolved to. `waiting` → `delivering` (released) | `refused` (timeout).
|
|
79
|
+
*/
|
|
80
|
+
interface GuardedSpawn {
|
|
81
|
+
token: string;
|
|
82
|
+
channelKey: string;
|
|
83
|
+
channelId: string;
|
|
84
|
+
/** The stripped triggering message; empty when there is nothing to deliver. */
|
|
85
|
+
prompt: string;
|
|
86
|
+
state: "waiting" | "delivering" | "refused";
|
|
87
|
+
/** Set by `onSessionResolved` for this spawn's token. */
|
|
88
|
+
sessionId?: string;
|
|
89
|
+
meta?: SpawnMeta;
|
|
90
|
+
/** Sessions that announced readiness with this spawn's token. */
|
|
91
|
+
ready: Set<string>;
|
|
92
|
+
timer?: ReturnType<typeof setTimeout>;
|
|
93
|
+
/**
|
|
94
|
+
* Team layer only: re-runs the spawn authorization at release time. The window between the
|
|
95
|
+
* authorization and the delivery is up to the readiness timeout, so a `!disarm` (or any other
|
|
96
|
+
* policy change) inside it must still stop the held message.
|
|
97
|
+
*/
|
|
98
|
+
recheck?: () => { kind: string; reason?: string };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
|
|
71
102
|
interface GatewayStatus {
|
|
72
103
|
running: boolean;
|
|
73
104
|
boundChannels: number;
|
|
@@ -333,6 +364,13 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
333
364
|
let offSessionEvents: (() => void) | null = null;
|
|
334
365
|
/** A spawn that never resolves must not block its channel forever. */
|
|
335
366
|
const SPAWN_TTL_MS = 5 * 60_000;
|
|
367
|
+
/** token → guarded spawn awaiting readiness (D6). Empty when no guard is configured. */
|
|
368
|
+
const guardedSpawns = new Map<string, GuardedSpawn>();
|
|
369
|
+
/** Tokens of guarded spawns refused before their session resolved: a late resolution is shut down. */
|
|
370
|
+
const refusedTokens = new Set<string>();
|
|
371
|
+
let offGuardReady: (() => void) | null = null;
|
|
372
|
+
let guardReadyUnavailable = false;
|
|
373
|
+
const guardReadyTimeoutMs = deps.guardReadyTimeoutMs ?? GUARD_READY_TIMEOUT_MS;
|
|
336
374
|
|
|
337
375
|
/**
|
|
338
376
|
* Team-controls mirror lane (D9): STRUCTURED session activity posted into the
|
|
@@ -380,6 +418,7 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
380
418
|
const at = pendingSpawnAt.get(key);
|
|
381
419
|
if (at === undefined || at < cutoff) {
|
|
382
420
|
correlator.reject(token);
|
|
421
|
+
dropGuarded(token);
|
|
383
422
|
pendingSpawns.delete(key);
|
|
384
423
|
pendingSpawnAt.delete(key);
|
|
385
424
|
}
|
|
@@ -495,16 +534,17 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
495
534
|
}
|
|
496
535
|
|
|
497
536
|
async function ensureBinding(msg: InboundMessage, channelKey: string): Promise<Binding | null> {
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
//
|
|
502
|
-
// A second message inside that window must NOT start a second session.
|
|
537
|
+
// F7: a spawn takes seconds and the binding is written only at resolution (with a guard: only once
|
|
538
|
+
// the guard proved ready). A second message inside that window must NOT start a second session and
|
|
539
|
+
// must NEVER reach an unverified one - so a pending spawn is tested BEFORE an existing binding
|
|
540
|
+
// (a resumed session's old binding must not route the message either). Never queued.
|
|
503
541
|
sweepStaleSpawns();
|
|
504
542
|
if (pendingSpawns.has(channelKey)) {
|
|
505
543
|
await reply(msg.channelId, "A session is already starting for this channel — one moment.");
|
|
506
544
|
return null;
|
|
507
545
|
}
|
|
546
|
+
const existing = store.get(channelKey);
|
|
547
|
+
if (existing) return existing;
|
|
508
548
|
|
|
509
549
|
// L2: CREATING a binding is a privileged op. An allowlisted non-admin may
|
|
510
550
|
// TALK on an already-bound channel but may not bind a new one; otherwise
|
|
@@ -613,6 +653,24 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
613
653
|
"L3 toolPolicy is configured but guardExtension is not — refusing to start an ungated session.",
|
|
614
654
|
};
|
|
615
655
|
}
|
|
656
|
+
// L3 (task 9): the companion guard is loaded into SPAWNED sessions only.
|
|
657
|
+
// Attached sessions never reach this code path, so they stay ungated by
|
|
658
|
+
// design — and no interceptor can be retrofitted into a running session
|
|
659
|
+
// anyway. The extension identifier is NEVER invented: an unresolvable
|
|
660
|
+
// reference would break every spawn, so it must be operator-supplied.
|
|
661
|
+
const guardRef = config.toolPolicy && config.guardExtension ? config.guardExtension : undefined;
|
|
662
|
+
// D6: a guarded spawn needs a host that can deliver the readiness announcement. Without one the
|
|
663
|
+
// guard cannot be proven loaded, so refuse (fail closed) instead of spawning an unverified session.
|
|
664
|
+
if (guardRef && !ensureGuardReadyListener()) {
|
|
665
|
+
seam.log(
|
|
666
|
+
"error",
|
|
667
|
+
"chat-gateway: the host cannot deliver plugin messages (no registerPiHandler) - refusing to start a guarded session it cannot verify",
|
|
668
|
+
);
|
|
669
|
+
return {
|
|
670
|
+
success: false,
|
|
671
|
+
message: "this host cannot verify the tool guard (no plugin-message support) - refusing to start an unverified session.",
|
|
672
|
+
};
|
|
673
|
+
}
|
|
616
674
|
const initialPrompt = stripSteerPrefix(msg.text, config.steerPrefix).trim();
|
|
617
675
|
const token = seam.mintSpawnToken();
|
|
618
676
|
correlator.expect(token, {
|
|
@@ -626,12 +684,32 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
626
684
|
});
|
|
627
685
|
pendingSpawns.set(channelKey, token);
|
|
628
686
|
pendingSpawnAt.set(channelKey, now());
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
687
|
+
const guarded: GuardedSpawn | undefined = guardRef
|
|
688
|
+
? {
|
|
689
|
+
token,
|
|
690
|
+
channelKey,
|
|
691
|
+
channelId: msg.channelId,
|
|
692
|
+
prompt: initialPrompt,
|
|
693
|
+
state: "waiting",
|
|
694
|
+
ready: new Set(),
|
|
695
|
+
...(team
|
|
696
|
+
? {
|
|
697
|
+
recheck: () =>
|
|
698
|
+
team.authorizeRequest({
|
|
699
|
+
author: authorOf(msg),
|
|
700
|
+
channelId: msg.channelId,
|
|
701
|
+
...(msg.parentChannelId ? { parentChannelId: msg.parentChannelId } : {}),
|
|
702
|
+
...(msg.threadId ? { threadId: msg.threadId } : {}),
|
|
703
|
+
verb: "spawn_session",
|
|
704
|
+
// The cwd the session was actually spawned at: a workspace change during the readiness wait
|
|
705
|
+
// must refuse the release (the spawn-time authorization above carries no target).
|
|
706
|
+
targetCwd: cwd,
|
|
707
|
+
}),
|
|
708
|
+
}
|
|
709
|
+
: {}),
|
|
710
|
+
}
|
|
711
|
+
: undefined;
|
|
712
|
+
if (guarded) guardedSpawns.set(token, guarded);
|
|
635
713
|
const res = await seam.spawn({
|
|
636
714
|
cwd,
|
|
637
715
|
name: `chat:${channelKey}`,
|
|
@@ -642,8 +720,9 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
642
720
|
pluginRef: { kind: "chat-gateway", channelKey, chatSpawnToken: token, bindSource: source },
|
|
643
721
|
// The message that caused the spawn is the session's first turn; without
|
|
644
722
|
// it the operator's request was dropped and they had to repeat it. A
|
|
645
|
-
// fresh/resumed session has no in-flight turn, so a steer prefix is moot.
|
|
646
|
-
|
|
723
|
+
// fresh/resumed session has no in-flight turn, so a steer prefix is moot. With a guard the message
|
|
724
|
+
// is HELD BACK (delivered through `send_prompt` once the guard announces readiness, D6).
|
|
725
|
+
...(initialPrompt && !guarded ? { initialPrompt } : {}),
|
|
647
726
|
// Chat sessions stay off the board unless the operator opted in.
|
|
648
727
|
...(config.sessionVisibility === "hidden" ? { lifecycle: { hidden: true } } : {}),
|
|
649
728
|
...(resume ? { resume } : {}),
|
|
@@ -651,7 +730,8 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
651
730
|
? {
|
|
652
731
|
extensions: [guardRef],
|
|
653
732
|
extensionConfig: {
|
|
654
|
-
|
|
733
|
+
// `token` is the spawn's readiness token (projected to PI_EXT_CHAT_GATEWAY_GUARD_TOKEN).
|
|
734
|
+
"chat-gateway-guard": { policy: JSON.stringify(config.toolPolicy), token },
|
|
655
735
|
},
|
|
656
736
|
}
|
|
657
737
|
: {}),
|
|
@@ -659,12 +739,167 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
659
739
|
if (!res.success) {
|
|
660
740
|
// X8: no dangling binding, no half-correlated spawn.
|
|
661
741
|
correlator.reject(token);
|
|
742
|
+
dropGuarded(token);
|
|
662
743
|
pendingSpawns.delete(channelKey);
|
|
663
744
|
pendingSpawnAt.delete(channelKey);
|
|
745
|
+
} else if (guarded) {
|
|
746
|
+
startGuardTimer(guarded);
|
|
747
|
+
tryRelease(guarded); // the announcement and the resolution may both have arrived during the spawn call
|
|
664
748
|
}
|
|
665
749
|
return res;
|
|
666
750
|
}
|
|
667
751
|
|
|
752
|
+
/** Register (once) for the guard's readiness announcement. False = the host cannot deliver it. */
|
|
753
|
+
function ensureGuardReadyListener(): boolean {
|
|
754
|
+
if (offGuardReady) return true;
|
|
755
|
+
if (guardReadyUnavailable) return false;
|
|
756
|
+
try {
|
|
757
|
+
const off = seam.onGuardReady(handleGuardReady);
|
|
758
|
+
if (!off) {
|
|
759
|
+
guardReadyUnavailable = true;
|
|
760
|
+
return false;
|
|
761
|
+
}
|
|
762
|
+
offGuardReady = off;
|
|
763
|
+
return true;
|
|
764
|
+
} catch {
|
|
765
|
+
guardReadyUnavailable = true; // a throwing registration is an unsupported host
|
|
766
|
+
return false;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/** Forget a guarded spawn (timer + map entry). */
|
|
771
|
+
function dropGuarded(token: string): void {
|
|
772
|
+
const g = guardedSpawns.get(token);
|
|
773
|
+
if (g?.timer) clearTimeout(g.timer);
|
|
774
|
+
guardedSpawns.delete(token);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* The readiness announcement. Honoured only with the spawn's OWN token from the session the spawn
|
|
779
|
+
* resolved to: the token travels in the spawned process's environment, so a token alone (any other
|
|
780
|
+
* process, any other session) proves nothing. Anything else is ignored.
|
|
781
|
+
*/
|
|
782
|
+
function handleGuardReady(sessionId: string, message: unknown): void {
|
|
783
|
+
const m = message as { pluginId?: unknown; messageType?: unknown; payload?: { token?: unknown } } | null | undefined;
|
|
784
|
+
if (!m || m.pluginId !== CHAT_GATEWAY_PLUGIN_ID || m.messageType !== GUARD_READY_MESSAGE) return;
|
|
785
|
+
const token = m.payload?.token;
|
|
786
|
+
if (typeof token !== "string" || token === "" || typeof sessionId !== "string") return;
|
|
787
|
+
const g = guardedSpawns.get(token);
|
|
788
|
+
if (g?.state !== "waiting") return; // unknown, already released, or refused: ignored
|
|
789
|
+
g.ready.add(sessionId);
|
|
790
|
+
tryRelease(g);
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
function startGuardTimer(g: GuardedSpawn): void {
|
|
794
|
+
if (g.state !== "waiting" || g.timer) return;
|
|
795
|
+
g.timer = setTimeout(() => void refuseGuarded(g), guardReadyTimeoutMs);
|
|
796
|
+
(g.timer as { unref?: () => void }).unref?.();
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** Release: ready AND resolved AND the two agree. Persist the binding only now, then deliver. */
|
|
800
|
+
function tryRelease(g: GuardedSpawn): void {
|
|
801
|
+
if (g.state !== "waiting" || !g.sessionId || !g.meta || !g.ready.has(g.sessionId)) return;
|
|
802
|
+
const recheck = g.recheck?.();
|
|
803
|
+
if (recheck?.kind === "refusal") {
|
|
804
|
+
void refuseHeld(g, recheck.reason ?? "refused");
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
g.state = "delivering";
|
|
808
|
+
if (g.timer) clearTimeout(g.timer);
|
|
809
|
+
g.timer = undefined;
|
|
810
|
+
bindSpawned(g.meta, g.sessionId);
|
|
811
|
+
void deliverHeld(g);
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
async function deliverHeld(g: GuardedSpawn): Promise<void> {
|
|
815
|
+
try {
|
|
816
|
+
if (g.prompt && g.sessionId) {
|
|
817
|
+
let ok = false;
|
|
818
|
+
try {
|
|
819
|
+
ok = (await Promise.resolve(seam.sendPrompt(g.sessionId, g.prompt, "followUp"))) !== false;
|
|
820
|
+
} catch {
|
|
821
|
+
ok = false;
|
|
822
|
+
}
|
|
823
|
+
if (!ok) {
|
|
824
|
+
seam.log("error", `chat-gateway: the held message could not be delivered to session ${g.sessionId}`);
|
|
825
|
+
// The binding stays and the session keeps running: the user simply retries.
|
|
826
|
+
await reply(g.channelId, "message not delivered");
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
} finally {
|
|
830
|
+
// The channel stops being pending only now, so a message that arrived while delivering was refused.
|
|
831
|
+
if (pendingSpawns.get(g.channelKey) === g.token) {
|
|
832
|
+
pendingSpawns.delete(g.channelKey);
|
|
833
|
+
pendingSpawnAt.delete(g.channelKey);
|
|
834
|
+
}
|
|
835
|
+
guardedSpawns.delete(g.token);
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/** Re-authorization at release failed (e.g. disarmed meanwhile): end the session, send nothing, say why. */
|
|
840
|
+
async function refuseHeld(g: GuardedSpawn, reason: string): Promise<void> {
|
|
841
|
+
g.state = "refused";
|
|
842
|
+
if (g.timer) clearTimeout(g.timer);
|
|
843
|
+
g.timer = undefined;
|
|
844
|
+
correlator.reject(g.token);
|
|
845
|
+
guardedSpawns.delete(g.token);
|
|
846
|
+
if (pendingSpawns.get(g.channelKey) === g.token) {
|
|
847
|
+
pendingSpawns.delete(g.channelKey);
|
|
848
|
+
pendingSpawnAt.delete(g.channelKey);
|
|
849
|
+
}
|
|
850
|
+
if (g.sessionId) {
|
|
851
|
+
try {
|
|
852
|
+
await seam.shutdownSession(g.sessionId);
|
|
853
|
+
} catch (err) {
|
|
854
|
+
seam.log("error", `chat-gateway: could not shut down session ${g.sessionId}: ${String(err)}`);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
await reply(g.channelId, `Refused: ${reason}.`);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/** Timeout: the guard never announced. End the session (if it resolved), tell the user, send nothing. */
|
|
861
|
+
async function refuseGuarded(g: GuardedSpawn): Promise<void> {
|
|
862
|
+
if (g.state !== "waiting") return; // (stop() clears every timer, so a stopped gateway never gets here)
|
|
863
|
+
g.state = "refused";
|
|
864
|
+
g.timer = undefined;
|
|
865
|
+
correlator.reject(g.token);
|
|
866
|
+
seam.log("error", `chat-gateway: the tool guard of channel ${g.channelKey} did not announce readiness - ending the session`);
|
|
867
|
+
guardedSpawns.delete(g.token);
|
|
868
|
+
if (pendingSpawns.get(g.channelKey) === g.token) {
|
|
869
|
+
pendingSpawns.delete(g.channelKey);
|
|
870
|
+
pendingSpawnAt.delete(g.channelKey);
|
|
871
|
+
}
|
|
872
|
+
if (g.sessionId) {
|
|
873
|
+
try {
|
|
874
|
+
await seam.shutdownSession(g.sessionId);
|
|
875
|
+
} catch (err) {
|
|
876
|
+
seam.log("error", `chat-gateway: could not shut down session ${g.sessionId}: ${String(err)}`);
|
|
877
|
+
}
|
|
878
|
+
} else {
|
|
879
|
+
// Not resolved yet: shut it down the moment it is (see the resolution handler).
|
|
880
|
+
refusedTokens.add(g.token);
|
|
881
|
+
if (refusedTokens.size > 100) refusedTokens.delete(refusedTokens.values().next().value as string);
|
|
882
|
+
}
|
|
883
|
+
await reply(g.channelId, "session refused: its tool guard did not start");
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/** Persist the spawn's binding (exact binding identity: a thread spawn lands on the thread key, F3). */
|
|
887
|
+
function bindSpawned(meta: SpawnMeta, sessionId: string): void {
|
|
888
|
+
store.set({
|
|
889
|
+
platform,
|
|
890
|
+
channelId: meta.channelId,
|
|
891
|
+
threadId: meta.threadId,
|
|
892
|
+
parentChannelId: meta.parentChannelId,
|
|
893
|
+
sessionId,
|
|
894
|
+
cwd: meta.cwd,
|
|
895
|
+
boundBy: meta.by,
|
|
896
|
+
source: "spawn",
|
|
897
|
+
isDM: meta.isDM,
|
|
898
|
+
createdAt: now(),
|
|
899
|
+
});
|
|
900
|
+
subscribeSession(sessionId);
|
|
901
|
+
}
|
|
902
|
+
|
|
668
903
|
/** Spawn a fresh session in `cwd`; correlate it via the token echoed on resolution. */
|
|
669
904
|
async function spawnIn(
|
|
670
905
|
msg: InboundMessage,
|
|
@@ -1140,26 +1375,26 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
1140
1375
|
offResolved = seam.onSessionResolved((sessionId, pluginRef) => {
|
|
1141
1376
|
const token = pluginRef?.chatSpawnToken;
|
|
1142
1377
|
if (typeof token !== "string") return;
|
|
1378
|
+
if (refusedTokens.delete(token)) {
|
|
1379
|
+
// A guarded spawn refused before it resolved: end it now, never bind it.
|
|
1380
|
+
void Promise.resolve()
|
|
1381
|
+
.then(() => seam.shutdownSession(sessionId))
|
|
1382
|
+
.catch((err) => seam.log("error", `chat-gateway: could not shut down refused session ${sessionId}: ${String(err)}`));
|
|
1383
|
+
return;
|
|
1384
|
+
}
|
|
1143
1385
|
const meta = correlator.resolve(token, sessionId);
|
|
1144
1386
|
if (!meta) return;
|
|
1387
|
+
const guarded = guardedSpawns.get(token);
|
|
1388
|
+
if (guarded) {
|
|
1389
|
+
// D6: the channel stays pending and NO binding is persisted until the guard proves ready.
|
|
1390
|
+
guarded.sessionId = sessionId;
|
|
1391
|
+
guarded.meta = meta;
|
|
1392
|
+
tryRelease(guarded);
|
|
1393
|
+
return;
|
|
1394
|
+
}
|
|
1145
1395
|
pendingSpawns.delete(meta.channelKey);
|
|
1146
1396
|
pendingSpawnAt.delete(meta.channelKey);
|
|
1147
|
-
|
|
1148
|
-
// the thread key, not its parent — otherwise the thread binding never
|
|
1149
|
-
// resolves and every follow-up message spawns ANOTHER session.
|
|
1150
|
-
store.set({
|
|
1151
|
-
platform,
|
|
1152
|
-
channelId: meta.channelId,
|
|
1153
|
-
threadId: meta.threadId,
|
|
1154
|
-
parentChannelId: meta.parentChannelId,
|
|
1155
|
-
sessionId,
|
|
1156
|
-
cwd: meta.cwd,
|
|
1157
|
-
boundBy: meta.by,
|
|
1158
|
-
source: "spawn",
|
|
1159
|
-
isDM: meta.isDM,
|
|
1160
|
-
createdAt: now(),
|
|
1161
|
-
});
|
|
1162
|
-
subscribeSession(sessionId);
|
|
1397
|
+
bindSpawned(meta, sessionId);
|
|
1163
1398
|
});
|
|
1164
1399
|
await adapter.start({
|
|
1165
1400
|
onMessage: async (m: PlatformMessage) => {
|
|
@@ -1296,6 +1531,17 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
1296
1531
|
prompts.clear();
|
|
1297
1532
|
sequences.clear();
|
|
1298
1533
|
for (const token of correlator.pending()) correlator.reject(token);
|
|
1534
|
+
// A restart while a guarded spawn awaits readiness leaves that session idle and unbound (it received
|
|
1535
|
+
// no chat message); no cleanup, documented residual. Timers must not outlive the gateway.
|
|
1536
|
+
for (const g of guardedSpawns.values()) {
|
|
1537
|
+
if (g.timer) clearTimeout(g.timer);
|
|
1538
|
+
g.state = "refused"; // a seam.spawn still pending must not arm a timer or release after the stop
|
|
1539
|
+
}
|
|
1540
|
+
guardedSpawns.clear();
|
|
1541
|
+
refusedTokens.clear();
|
|
1542
|
+
offGuardReady?.();
|
|
1543
|
+
offGuardReady = null;
|
|
1544
|
+
guardReadyUnavailable = false;
|
|
1299
1545
|
pendingSpawns.clear();
|
|
1300
1546
|
pendingSpawnAt.clear();
|
|
1301
1547
|
lastInvoker.clear();
|
package/src/server/routing.ts
CHANGED
|
@@ -95,7 +95,7 @@ export function createBindingStore(deps: BindingStoreDeps): BindingStore {
|
|
|
95
95
|
* Pending-spawn metadata: the binding identity to persist when the spawn
|
|
96
96
|
* resolves.
|
|
97
97
|
*/
|
|
98
|
-
interface SpawnMeta {
|
|
98
|
+
export interface SpawnMeta {
|
|
99
99
|
channelKey: string;
|
|
100
100
|
/** Binding identity to persist on resolution (threadId preserved). */
|
|
101
101
|
channelId: string;
|
package/src/server/seam.ts
CHANGED
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
* See change: add-chat-gateway.
|
|
20
20
|
*/
|
|
21
21
|
import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
|
|
22
|
+
import { GUARD_READY_MESSAGE } from "../shared/guard-ready.js";
|
|
22
23
|
|
|
23
24
|
export interface SeamSession {
|
|
24
25
|
id: string;
|
|
@@ -90,6 +91,14 @@ export interface HostSeam {
|
|
|
90
91
|
onSessionEvent(handler: (sessionId: string) => void): () => void;
|
|
91
92
|
/** Subscribe to resolution of THIS plugin's own spawned sessions. */
|
|
92
93
|
onSessionResolved(handler: (sessionId: string, pluginRef: Record<string, unknown>) => void): () => void;
|
|
94
|
+
/**
|
|
95
|
+
* Register for the in-session guard's readiness announcement (`chat_gateway_guard_ready`). The handler
|
|
96
|
+
* receives the SENDING session's id and the plugin-message envelope. Returns an unsubscribe, or
|
|
97
|
+
* `undefined` when the host cannot deliver plugin messages (older host: no `registerPiHandler`) -
|
|
98
|
+
* the gateway then refuses guarded spawns instead of falling back to an unverified one.
|
|
99
|
+
* See change: harden-agent-tool-guards (D6).
|
|
100
|
+
*/
|
|
101
|
+
onGuardReady(handler: (sessionId: string, message: unknown) => void): (() => void) | undefined;
|
|
93
102
|
log(level: "info" | "warn" | "error", message: string): void;
|
|
94
103
|
}
|
|
95
104
|
|
|
@@ -186,6 +195,12 @@ export function createHostSeam(ctx: ServerPluginContext): HostSeam {
|
|
|
186
195
|
onSessionResolved(handler) {
|
|
187
196
|
return ctx.onSessionResolved(handler);
|
|
188
197
|
},
|
|
198
|
+
onGuardReady(handler) {
|
|
199
|
+
if (typeof ctx.registerPiHandler !== "function") return undefined;
|
|
200
|
+
// Handlers cannot be removed on this host; the gateway ignores a stale/foreign announcement itself.
|
|
201
|
+
ctx.registerPiHandler(GUARD_READY_MESSAGE, (msg, sessionId) => handler(sessionId, msg));
|
|
202
|
+
return () => {};
|
|
203
|
+
},
|
|
189
204
|
log(level, message) {
|
|
190
205
|
ctx.logger[level](message);
|
|
191
206
|
},
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*
|
|
10
10
|
* Pure over (author, binding, verb, targetCwd, disarmed) — the verb→tier table
|
|
11
11
|
* and command allowlist are injectable purely to make the table-driven tests
|
|
12
|
-
* possible; production uses the shared `
|
|
12
|
+
* possible; production uses the shared `GENERATED_VERB_TIERS` table.
|
|
13
13
|
*
|
|
14
14
|
* See change: add-chat-gateway-team-controls (D2).
|
|
15
15
|
*/
|
package/src/server/team/tier.ts
CHANGED
|
@@ -2,16 +2,17 @@
|
|
|
2
2
|
* Verb→tier resolution for the chat team-controls layer.
|
|
3
3
|
*
|
|
4
4
|
* The tier required by a verb is READ from the dashboard's shared effective
|
|
5
|
-
* table (`
|
|
6
|
-
*
|
|
5
|
+
* table (`GENERATED_VERB_TIERS`, generated into `packages/shared/src/mcp/` by the
|
|
6
|
+
* mcp-server codegen), never re-declared here — so the chat surface and the MCP surface
|
|
7
7
|
* cannot drift apart. A curated command allowlist narrows what chat may invoke
|
|
8
8
|
* at all, and a non-configurable deny-list carves credential/state-minting
|
|
9
9
|
* verbs out of `operate`.
|
|
10
10
|
*
|
|
11
|
-
* See change: add-chat-gateway-team-controls (D3).
|
|
11
|
+
* See change: add-chat-gateway-team-controls (D3); decouple-plugins-from-core (task 2.6).
|
|
12
12
|
*/
|
|
13
|
-
import {
|
|
13
|
+
import { GENERATED_VERB_TIERS } from "@blackbelt-technology/pi-dashboard-shared/mcp/verb-tiers.generated.js";
|
|
14
14
|
import { minTier, rank, type Tier } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
|
|
15
|
+
import { wsMessageTier } from "@blackbelt-technology/pi-dashboard-shared/ws-message-tiers.js";
|
|
15
16
|
|
|
16
17
|
/** Roles may never grant `operate` — see `authorize.ts` / `tier-config.ts`. */
|
|
17
18
|
export type RoleTier = "observe" | "control";
|
|
@@ -81,11 +82,17 @@ export const CHAT_LOCAL_VERB_TIERS: ReadonlyMap<string, Tier> = new Map([
|
|
|
81
82
|
["attach_session", "observe"],
|
|
82
83
|
// Ending a session is at least as strong as prompting it (`send_prompt`).
|
|
83
84
|
["close_session", "control"],
|
|
85
|
+
// A verb with no MCP-manifest row: agent prompt answers left the MCP surface
|
|
86
|
+
// (human-in-the-loop), so the generated table no longer carries it. The tier is
|
|
87
|
+
// READ from the dashboard's WS table (never a literal) so chat follows it;
|
|
88
|
+
// an unlisted row fails closed to `operate`.
|
|
89
|
+
// See change: close-security-map-high-findings (D2).
|
|
90
|
+
["prompt_response", wsMessageTier("prompt_response")],
|
|
84
91
|
]);
|
|
85
92
|
|
|
86
|
-
/** The effective per-verb tier table, read from the shared generated
|
|
93
|
+
/** The effective per-verb tier table, read from the shared generated table. */
|
|
87
94
|
export const VERB_TIERS: ReadonlyMap<string, Tier> = new Map(
|
|
88
|
-
|
|
95
|
+
GENERATED_VERB_TIERS.map((t) => [t.name, t.tier] as const),
|
|
89
96
|
);
|
|
90
97
|
|
|
91
98
|
/** `undefined` means the verb has no row in the shared table — never infer one. */
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guard readiness handshake constants (harden-agent-tool-guards D6), shared by the in-session guard
|
|
3
|
+
* extension (announces) and the gateway server (waits). Import-free leaf.
|
|
4
|
+
*
|
|
5
|
+
* The guard emits `dashboard:plugin-message` `{pluginId, messageType, payload:{token}}` at
|
|
6
|
+
* `session_start`; the bridge forwards it with the sender's session id; the gateway releases a
|
|
7
|
+
* guarded spawn only when the token is the spawn's own AND the sender is the session the spawn
|
|
8
|
+
* resolved to.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** `pluginId` of the readiness message (this plugin's id). */
|
|
12
|
+
export const CHAT_GATEWAY_PLUGIN_ID = "chat-gateway";
|
|
13
|
+
|
|
14
|
+
/** `messageType` of the readiness message. */
|
|
15
|
+
export const GUARD_READY_MESSAGE = "chat_gateway_guard_ready";
|
|
16
|
+
|
|
17
|
+
/** Env var carrying the spawn's readiness token (`extensionConfig["chat-gateway-guard"].token`). */
|
|
18
|
+
export const GUARD_TOKEN_ENV = "PI_EXT_CHAT_GATEWAY_GUARD_TOKEN";
|
|
19
|
+
|
|
20
|
+
/** Fixed readiness window after the spawn. A guard that announces at exactly this instant loses. */
|
|
21
|
+
export const GUARD_READY_TIMEOUT_MS = 30_000;
|
package/src/shared/index.ts
CHANGED