@blackbelt-technology/pi-dashboard-chat-gateway-plugin 0.8.0 → 0.10.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 +5 -4
- package/src/adapters/base.ts +17 -0
- package/src/adapters/discord-payload.ts +18 -1
- package/src/adapters/discord.ts +41 -2
- package/src/client/ChatGatewaySettings.tsx +504 -0
- package/src/client/index.tsx +7 -328
- package/src/client/team-controls-panel.tsx +168 -133
- package/src/configSchema.json +16 -0
- package/src/server/config.ts +8 -0
- package/src/server/gateway.ts +349 -17
- package/src/server/seam.ts +23 -0
- package/src/server/team/controller.ts +3 -0
- package/src/server/team/tier.ts +11 -0
- package/src/shared/types.ts +28 -0
package/src/server/gateway.ts
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
* See change: add-chat-gateway.
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
|
+
import path from "node:path";
|
|
24
25
|
import type { InteractiveResponse, PlatformAdapter, PlatformMessage } from "../adapters/base.js";
|
|
25
26
|
import { chunkForDiscord } from "../adapters/discord-payload.js";
|
|
26
27
|
import type { ResolvedConfig } from "../shared/types.js";
|
|
@@ -41,7 +42,7 @@ import {
|
|
|
41
42
|
toPromptControl,
|
|
42
43
|
} from "./prompts.js";
|
|
43
44
|
import type { BindingStore, SpawnCorrelator } from "./routing.js";
|
|
44
|
-
import type { HostSeam, SpawnOutcome } from "./seam.js";
|
|
45
|
+
import type { HostSeam, SeamSession, SpawnOutcome } from "./seam.js";
|
|
45
46
|
import { createEditThrottle, type EditThrottle, shouldSteer, stripSteerPrefix } from "./stream.js";
|
|
46
47
|
import type { Grant } from "./team/authorize.js";
|
|
47
48
|
import { resolveCwdWithWorkspace, type WorkspaceResolveOutcome } from "./team/binding.js";
|
|
@@ -269,6 +270,7 @@ function toInbound(
|
|
|
269
270
|
const inbound: InboundMessage = {
|
|
270
271
|
platform,
|
|
271
272
|
channelId: m.channelId,
|
|
273
|
+
...(m.id ? { messageId: m.id } : {}),
|
|
272
274
|
userId: m.userId,
|
|
273
275
|
text: m.content,
|
|
274
276
|
isDM: md?.isDM === true,
|
|
@@ -285,6 +287,28 @@ function toInbound(
|
|
|
285
287
|
return inbound;
|
|
286
288
|
}
|
|
287
289
|
|
|
290
|
+
/** Discord thread-name limit. */
|
|
291
|
+
const THREAD_NAME_LIMIT = 100;
|
|
292
|
+
|
|
293
|
+
/** Whole-message `!sessions` (see change: chat-gateway-attach-dashboard-sessions). */
|
|
294
|
+
const SESSIONS_COMMAND = /^\s*!\s*sessions\s*$/i;
|
|
295
|
+
/** Whole-message `!attach <number | id-prefix>`. */
|
|
296
|
+
const ATTACH_COMMAND = /^\s*!\s*attach\s+(\S+)\s*$/i;
|
|
297
|
+
/** Whole-message `!close` (inside a thread). See change: chat-gateway-close-command. */
|
|
298
|
+
const CLOSE_COMMAND = /^\s*!\s*close\s*$/i;
|
|
299
|
+
/** Max rows in a `!sessions` reply (keeps it under Discord's 2000 chars). */
|
|
300
|
+
const LIST_LIMIT = 25;
|
|
301
|
+
|
|
302
|
+
/** The chokepoint's author shape for an inbound message. */
|
|
303
|
+
function authorOf(msg: InboundMessage) {
|
|
304
|
+
return {
|
|
305
|
+
id: msg.userId,
|
|
306
|
+
...(msg.bot === true ? { isBot: true } : {}),
|
|
307
|
+
...(msg.webhook === true ? { isWebhook: true } : {}),
|
|
308
|
+
...(msg.roleIds ? { roleIds: msg.roleIds } : {}),
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
|
|
288
312
|
export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
289
313
|
const { seam, adapter, config, store, correlator, platform, team } = deps;
|
|
290
314
|
const now = deps.now ?? Date.now;
|
|
@@ -302,6 +326,11 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
302
326
|
const pendingSpawns = new Map<string, string>();
|
|
303
327
|
/** channelKey → when the spawn started (for the stale-spawn sweep). */
|
|
304
328
|
const pendingSpawnAt = new Map<string, number>();
|
|
329
|
+
/** channelId → session ids of the last `!sessions` listing (for `!attach <n>`). */
|
|
330
|
+
const lastListing = new Map<string, string[]>();
|
|
331
|
+
/** Sessions the auto-mirror already considered this run. */
|
|
332
|
+
const mirrorConsidered = new Set<string>();
|
|
333
|
+
let offSessionEvents: (() => void) | null = null;
|
|
305
334
|
/** A spawn that never resolves must not block its channel forever. */
|
|
306
335
|
const SPAWN_TTL_MS = 5 * 60_000;
|
|
307
336
|
|
|
@@ -506,7 +535,7 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
506
535
|
// placeholder would strand a binding pointing at no session (X8).
|
|
507
536
|
const started = await spawnIn(msg, channelKey, resolved.cwd, resolved.source);
|
|
508
537
|
if (!started) return null;
|
|
509
|
-
await reply(msg.channelId, `Starting a session in ${resolved.cwd}…
|
|
538
|
+
await reply(msg.channelId, `Starting a session in ${resolved.cwd}… your message will run once it is up.`);
|
|
510
539
|
return null;
|
|
511
540
|
}
|
|
512
541
|
|
|
@@ -520,10 +549,7 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
520
549
|
// refused `scope_violation`. Attaching to the wrong session is not something
|
|
521
550
|
// a later refusal repairs, so the narrower net is the correct default (11.4).
|
|
522
551
|
const wsFolders = boundWorkspaceFolders(msg);
|
|
523
|
-
const inScope =
|
|
524
|
-
wsFolders && wsFolders.length > 0
|
|
525
|
-
? (cwd: string) => isWithinWorkspace(cwd, wsFolders)
|
|
526
|
-
: (cwd: string) => isWithinAllowedRoots(cwd, config.allowedRoots);
|
|
552
|
+
const inScope = scopeFor(msg);
|
|
527
553
|
const candidates = seam
|
|
528
554
|
.listSessions()
|
|
529
555
|
.filter((s) => typeof s.cwd === "string" && inScope(s.cwd));
|
|
@@ -587,6 +613,7 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
587
613
|
"L3 toolPolicy is configured but guardExtension is not — refusing to start an ungated session.",
|
|
588
614
|
};
|
|
589
615
|
}
|
|
616
|
+
const initialPrompt = stripSteerPrefix(msg.text, config.steerPrefix).trim();
|
|
590
617
|
const token = seam.mintSpawnToken();
|
|
591
618
|
correlator.expect(token, {
|
|
592
619
|
channelKey,
|
|
@@ -609,7 +636,16 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
609
636
|
cwd,
|
|
610
637
|
name: `chat:${channelKey}`,
|
|
611
638
|
spawnToken: token,
|
|
612
|
-
|
|
639
|
+
// Correlate through a key the plugin OWNS. `spawnToken` and `source` are
|
|
640
|
+
// core-reserved: the host's pending-ref registry strips them before
|
|
641
|
+
// `onSessionResolved`, so a ref keyed on them never binds the spawn.
|
|
642
|
+
pluginRef: { kind: "chat-gateway", channelKey, chatSpawnToken: token, bindSource: source },
|
|
643
|
+
// The message that caused the spawn is the session's first turn; without
|
|
644
|
+
// 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
|
+
...(initialPrompt ? { initialPrompt } : {}),
|
|
647
|
+
// Chat sessions stay off the board unless the operator opted in.
|
|
648
|
+
...(config.sessionVisibility === "hidden" ? { lifecycle: { hidden: true } } : {}),
|
|
613
649
|
...(resume ? { resume } : {}),
|
|
614
650
|
...(guardRef
|
|
615
651
|
? {
|
|
@@ -678,10 +714,30 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
678
714
|
await reply(msg.channelId, `Resume failed: ${res.message ?? "unknown error"}`);
|
|
679
715
|
return true;
|
|
680
716
|
}
|
|
681
|
-
await reply(msg.channelId, "Resuming the session…
|
|
717
|
+
await reply(msg.channelId, "Resuming the session… your message will run once it is up.");
|
|
682
718
|
return true;
|
|
683
719
|
}
|
|
684
720
|
|
|
721
|
+
/**
|
|
722
|
+
* Open a thread on the triggering message and return the message re-addressed
|
|
723
|
+
* INTO it (thread = channel; parent kept for L4/team fallbacks). `null` when
|
|
724
|
+
* the platform refuses (e.g. missing Create Public Threads): the caller keeps
|
|
725
|
+
* the channel-root conversation, so the message is never lost.
|
|
726
|
+
*/
|
|
727
|
+
async function openConversationThread(msg: InboundMessage): Promise<InboundMessage | null> {
|
|
728
|
+
if (!adapter.startThread || !msg.messageId) return null;
|
|
729
|
+
const name =
|
|
730
|
+
stripSteerPrefix(msg.text, config.steerPrefix).trim().replace(/\s+/g, " ").slice(0, THREAD_NAME_LIMIT) ||
|
|
731
|
+
"conversation";
|
|
732
|
+
try {
|
|
733
|
+
const { threadId } = await adapter.startThread(msg.channelId, msg.messageId, name);
|
|
734
|
+
return { ...msg, channelId: threadId, threadId, parentChannelId: msg.channelId };
|
|
735
|
+
} catch (err) {
|
|
736
|
+
seam.log("warn", `chat-gateway: could not open a thread (${String(err)}); answering in the channel`);
|
|
737
|
+
return null;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
|
|
685
741
|
function subscribeSession(sessionId: string): void {
|
|
686
742
|
if (subscriptions.has(sessionId)) return;
|
|
687
743
|
subscriptions.add(sessionId);
|
|
@@ -696,6 +752,232 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
696
752
|
return undefined;
|
|
697
753
|
}
|
|
698
754
|
|
|
755
|
+
// ── Dashboard sessions in Discord (`!sessions`, `!attach`, auto-mirror) ──
|
|
756
|
+
// See change: chat-gateway-attach-dashboard-sessions.
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* "In range" for this channel: the BOUND WORKSPACE's folders when there is
|
|
760
|
+
* one, else `allowedRoots` (same rule as the interactive attach, 11.4).
|
|
761
|
+
*/
|
|
762
|
+
function scopeFor(msg: InboundMessage): (cwd: string) => boolean {
|
|
763
|
+
const wsFolders = boundWorkspaceFolders(msg);
|
|
764
|
+
return wsFolders && wsFolders.length > 0
|
|
765
|
+
? (cwd: string) => isWithinWorkspace(cwd, wsFolders)
|
|
766
|
+
: (cwd: string) => isWithinAllowedRoots(cwd, config.allowedRoots);
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/** Live, non-hidden sessions in scope. Hidden = headless workers / plugin-hidden. */
|
|
770
|
+
function attachableSessions(inScope: (cwd: string) => boolean): SeamSession[] {
|
|
771
|
+
return seam
|
|
772
|
+
.listSessions()
|
|
773
|
+
.filter((s) => !s.hidden && s.status !== "ended" && typeof s.cwd === "string" && inScope(s.cwd));
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
function sessionLabel(s: SeamSession): string {
|
|
777
|
+
const raw = s.name ?? (s.cwd ? path.basename(s.cwd) : s.id.slice(0, 8));
|
|
778
|
+
return raw.replace(/\s+/g, " ").trim().slice(0, THREAD_NAME_LIMIT) || s.id.slice(0, 8);
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function threadMention(sessionId: string): string | undefined {
|
|
782
|
+
const key = channelKeyFor(sessionId);
|
|
783
|
+
const b = key ? store.get(key) : undefined;
|
|
784
|
+
return b ? `<#${b.threadId ?? b.channelId}>` : undefined;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** The chokepoint for a command verb. `false` ⇒ refused (author already told). */
|
|
788
|
+
async function gateCommand(msg: InboundMessage, verb: string, target?: SeamSession): Promise<boolean> {
|
|
789
|
+
if (!team) return true;
|
|
790
|
+
const decision = team.authorizeRequest({
|
|
791
|
+
author: authorOf(msg),
|
|
792
|
+
channelId: msg.channelId,
|
|
793
|
+
...(msg.parentChannelId ? { parentChannelId: msg.parentChannelId } : {}),
|
|
794
|
+
...(msg.threadId ? { threadId: msg.threadId } : {}),
|
|
795
|
+
verb,
|
|
796
|
+
...(target?.cwd ? { targetCwd: target.cwd, target: target.id } : {}),
|
|
797
|
+
});
|
|
798
|
+
if (decision.kind === "refusal") {
|
|
799
|
+
await reply(msg.channelId, `Refused: ${decision.reason}.`);
|
|
800
|
+
return false;
|
|
801
|
+
}
|
|
802
|
+
return true;
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/**
|
|
806
|
+
* Open a thread on `anchorId` named after the session, bind it (`attach` —
|
|
807
|
+
* the session is the operator's: never hidden, never re-policied) and stream
|
|
808
|
+
* the session there. `null` when the platform cannot open a thread.
|
|
809
|
+
*/
|
|
810
|
+
async function attachInThread(
|
|
811
|
+
channelId: string,
|
|
812
|
+
anchorId: string,
|
|
813
|
+
s: SeamSession,
|
|
814
|
+
boundBy: string,
|
|
815
|
+
): Promise<string | null> {
|
|
816
|
+
if (typeof adapter.startThread !== "function" || !s.cwd) return null;
|
|
817
|
+
const name = sessionLabel(s);
|
|
818
|
+
let threadId: string;
|
|
819
|
+
try {
|
|
820
|
+
({ threadId } = await adapter.startThread(channelId, anchorId, name));
|
|
821
|
+
} catch (err) {
|
|
822
|
+
seam.log("warn", `chat-gateway: could not open a thread for session ${s.id}: ${String(err)}`);
|
|
823
|
+
return null;
|
|
824
|
+
}
|
|
825
|
+
store.set({
|
|
826
|
+
platform,
|
|
827
|
+
channelId: threadId,
|
|
828
|
+
threadId,
|
|
829
|
+
parentChannelId: channelId,
|
|
830
|
+
sessionId: s.id,
|
|
831
|
+
cwd: s.cwd,
|
|
832
|
+
boundBy,
|
|
833
|
+
source: "attach",
|
|
834
|
+
isDM: false,
|
|
835
|
+
createdAt: now(),
|
|
836
|
+
});
|
|
837
|
+
subscribeSession(s.id);
|
|
838
|
+
await reply(threadId, `Attached to ${name}. Its activity shows here; messages you send here go to that session.`);
|
|
839
|
+
return threadId;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
async function handleSessionsCommand(msg: InboundMessage): Promise<void> {
|
|
843
|
+
if (!(await gateCommand(msg, "list_sessions"))) return;
|
|
844
|
+
const list = attachableSessions(scopeFor(msg)).slice(0, LIST_LIMIT);
|
|
845
|
+
lastListing.set(msg.channelId, list.map((s) => s.id));
|
|
846
|
+
if (list.length === 0) {
|
|
847
|
+
await reply(msg.channelId, "No live dashboard sessions in this workspace.");
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
const lines = list.map((s, i) => {
|
|
851
|
+
const where = threadMention(s.id);
|
|
852
|
+
return `${i + 1}. ${sessionLabel(s)} — ${s.status ?? "unknown"} · \`${s.id.slice(0, 8)}\`${where ? ` · ${where}` : ""}`;
|
|
853
|
+
});
|
|
854
|
+
await reply(msg.channelId, `${lines.join("\n")}\nAttach one with \`!attach <number>\`.`);
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
function resolveAttachTarget(msg: InboundMessage, arg: string): SeamSession | undefined {
|
|
858
|
+
const candidates = attachableSessions(scopeFor(msg));
|
|
859
|
+
if (/^\d+$/.test(arg)) {
|
|
860
|
+
const id = lastListing.get(msg.channelId)?.[Number(arg) - 1];
|
|
861
|
+
return candidates.find((s) => s.id === id);
|
|
862
|
+
}
|
|
863
|
+
const matches = candidates.filter((s) => s.id.startsWith(arg));
|
|
864
|
+
return matches.length === 1 ? matches[0] : undefined;
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
async function handleAttachCommand(msg: InboundMessage, arg: string): Promise<void> {
|
|
868
|
+
if (msg.threadId) {
|
|
869
|
+
await reply(msg.channelId, "Run `!attach` in the channel itself, not inside a thread.");
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
const target = resolveAttachTarget(msg, arg);
|
|
873
|
+
if (!(await gateCommand(msg, "attach_session", target))) return;
|
|
874
|
+
if (!target) {
|
|
875
|
+
await reply(msg.channelId, `No live session \`${arg}\` in this workspace. Use \`!sessions\` to list them.`);
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
const existing = threadMention(target.id);
|
|
879
|
+
if (existing) {
|
|
880
|
+
await reply(msg.channelId, `Already attached: ${existing}.`);
|
|
881
|
+
return;
|
|
882
|
+
}
|
|
883
|
+
const opened = msg.messageId ? await attachInThread(msg.channelId, msg.messageId, target, msg.userId) : null;
|
|
884
|
+
if (!opened) {
|
|
885
|
+
await reply(msg.channelId, "Could not open a thread here (does the bot have Create Public Threads?).");
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* `!close` inside a bound thread. A conversation the gateway STARTED
|
|
891
|
+
* (`spawn`/`resume`) is shut down like the dashboard Shutdown; an ATTACHED
|
|
892
|
+
* session is the operator's and only detached. Either way the binding is
|
|
893
|
+
* dropped and the thread archived. Authorized as `close_session` (control).
|
|
894
|
+
* See change: chat-gateway-close-command.
|
|
895
|
+
*/
|
|
896
|
+
/** Drop a binding; stop streaming the session when no other binding needs it. */
|
|
897
|
+
function unbind(key: string, sessionId: string): void {
|
|
898
|
+
store.remove(key);
|
|
899
|
+
if (channelKeyFor(sessionId)) return;
|
|
900
|
+
unsubscribes.get(sessionId)?.();
|
|
901
|
+
unsubscribes.delete(sessionId);
|
|
902
|
+
subscriptions.delete(sessionId);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/** Shut down a gateway-started session that is still live. `false` ⇒ host refused. */
|
|
906
|
+
async function endOwnedSession(binding: Binding, live: boolean): Promise<boolean> {
|
|
907
|
+
if (binding.source === "attach" || !live) return true;
|
|
908
|
+
return seam.shutdownSession(binding.sessionId);
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/** The thread binding `!close` acts on; `null` after telling the author why not. */
|
|
912
|
+
async function closeTarget(
|
|
913
|
+
msg: InboundMessage,
|
|
914
|
+
): Promise<{ key: string; binding: Binding; threadId: string } | null> {
|
|
915
|
+
if (!msg.threadId) {
|
|
916
|
+
await reply(msg.channelId, "Use `!close` inside a thread to close that conversation.");
|
|
917
|
+
return null;
|
|
918
|
+
}
|
|
919
|
+
const key = bindingKey({ platform, channelId: msg.channelId, threadId: msg.threadId });
|
|
920
|
+
const binding = store.get(key);
|
|
921
|
+
if (!binding) {
|
|
922
|
+
await reply(msg.channelId, "Nothing to close here: this thread is not linked to a session.");
|
|
923
|
+
return null;
|
|
924
|
+
}
|
|
925
|
+
return { key, binding, threadId: msg.threadId };
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
async function handleCloseCommand(msg: InboundMessage): Promise<void> {
|
|
929
|
+
const target = await closeTarget(msg);
|
|
930
|
+
if (!target) return;
|
|
931
|
+
const { key, binding, threadId } = target;
|
|
932
|
+
const session = seam.listSessions().find((s) => s.id === binding.sessionId);
|
|
933
|
+
if (!(await gateCommand(msg, "close_session", session ?? { id: binding.sessionId, cwd: binding.cwd }))) return;
|
|
934
|
+
if (!(await endOwnedSession(binding, session !== undefined))) {
|
|
935
|
+
await reply(msg.channelId, "Could not close the session (the gateway lacks the trust level to shut it down).");
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
unbind(key, binding.sessionId);
|
|
939
|
+
await reply(
|
|
940
|
+
msg.channelId,
|
|
941
|
+
binding.source === "attach"
|
|
942
|
+
? "Detached. The session keeps running on the dashboard. Archiving this thread."
|
|
943
|
+
: "Session closed. Archiving this thread.",
|
|
944
|
+
);
|
|
945
|
+
await adapter.archiveThread?.(threadId).catch((err) =>
|
|
946
|
+
seam.log("warn", `chat-gateway: could not archive thread ${threadId}: ${String(err)}`),
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/** The workspace channel whose folders contain `cwd` (team-controls only). */
|
|
951
|
+
function workspaceChannelFor(cwd: string): string | undefined {
|
|
952
|
+
if (!team) return undefined;
|
|
953
|
+
for (const channelId of team.boundChannelIds()) {
|
|
954
|
+
const folders = team.bindingFor(channelId)?.binding.folders;
|
|
955
|
+
if (folders && folders.length > 0 && isWithinWorkspace(cwd, folders)) return channelId;
|
|
956
|
+
}
|
|
957
|
+
return undefined;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
/**
|
|
961
|
+
* Opt-in auto-mirror: attach a live, non-hidden, unbound session into its
|
|
962
|
+
* workspace channel. Considered ONCE per gateway run (marked before any await,
|
|
963
|
+
* so an event burst cannot open two threads); persisted bindings make it
|
|
964
|
+
* idempotent across restarts.
|
|
965
|
+
*/
|
|
966
|
+
async function maybeAutoMirror(sessionId: string): Promise<void> {
|
|
967
|
+
if (!config.mirrorDashboardSessions || mirrorConsidered.has(sessionId)) return;
|
|
968
|
+
mirrorConsidered.add(sessionId);
|
|
969
|
+
if (channelKeyFor(sessionId)) return;
|
|
970
|
+
const s = seam.getSession(sessionId);
|
|
971
|
+
if (!s || s.hidden || s.status === "ended" || !s.cwd) return;
|
|
972
|
+
const channelId = workspaceChannelFor(s.cwd);
|
|
973
|
+
if (!channelId) return;
|
|
974
|
+
const anchor = await adapter.sendMessage(
|
|
975
|
+
channelId,
|
|
976
|
+
`🖥 Dashboard session: ${sessionLabel(s)} (\`${path.basename(s.cwd)}\`)`,
|
|
977
|
+
);
|
|
978
|
+
await attachInThread(channelId, anchor, s, "dashboard");
|
|
979
|
+
}
|
|
980
|
+
|
|
699
981
|
/** Render the next un-answered sub-prompt (or the multiselect submit gate). */
|
|
700
982
|
async function renderSequenceStep(state: SequenceState): Promise<void> {
|
|
701
983
|
const next =
|
|
@@ -856,7 +1138,7 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
856
1138
|
if (running) return;
|
|
857
1139
|
running = true;
|
|
858
1140
|
offResolved = seam.onSessionResolved((sessionId, pluginRef) => {
|
|
859
|
-
const token = pluginRef?.
|
|
1141
|
+
const token = pluginRef?.chatSpawnToken;
|
|
860
1142
|
if (typeof token !== "string") return;
|
|
861
1143
|
const meta = correlator.resolve(token, sessionId);
|
|
862
1144
|
if (!meta) return;
|
|
@@ -981,12 +1263,31 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
981
1263
|
for (const b of store.all()) {
|
|
982
1264
|
subscribeSession(b.sessionId);
|
|
983
1265
|
}
|
|
1266
|
+
|
|
1267
|
+
// Opt-in auto-mirror: newly seen sessions (first forwarded event), plus
|
|
1268
|
+
// every eligible live one right now. See change: chat-gateway-attach-dashboard-sessions.
|
|
1269
|
+
offSessionEvents = seam.onSessionEvent((sessionId) => {
|
|
1270
|
+
void maybeAutoMirror(sessionId).catch((err) =>
|
|
1271
|
+
seam.log("warn", `chat-gateway: auto-mirror failed for ${sessionId}: ${String(err)}`),
|
|
1272
|
+
);
|
|
1273
|
+
});
|
|
1274
|
+
if (config.mirrorDashboardSessions) {
|
|
1275
|
+
for (const s of seam.listSessions()) {
|
|
1276
|
+
await maybeAutoMirror(s.id).catch((err) =>
|
|
1277
|
+
seam.log("warn", `chat-gateway: auto-mirror failed for ${s.id}: ${String(err)}`),
|
|
1278
|
+
);
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
984
1281
|
},
|
|
985
1282
|
|
|
986
1283
|
async stop() {
|
|
987
1284
|
running = false;
|
|
988
1285
|
offResolved?.();
|
|
989
1286
|
offResolved = null;
|
|
1287
|
+
offSessionEvents?.();
|
|
1288
|
+
offSessionEvents = null;
|
|
1289
|
+
mirrorConsidered.clear();
|
|
1290
|
+
lastListing.clear();
|
|
990
1291
|
for (const off of unsubscribes.values()) off();
|
|
991
1292
|
unsubscribes.clear();
|
|
992
1293
|
subscriptions.clear();
|
|
@@ -1049,7 +1350,24 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
1049
1350
|
return;
|
|
1050
1351
|
}
|
|
1051
1352
|
|
|
1052
|
-
|
|
1353
|
+
// Dashboard sessions: `!sessions` lists, `!attach <n|id>` binds a thread.
|
|
1354
|
+
// Whole-message match, like `!disarm`, so ordinary steer text is never
|
|
1355
|
+
// taken for a command. Authorized through the same chokepoint.
|
|
1356
|
+
if (SESSIONS_COMMAND.test(msg.text)) {
|
|
1357
|
+
await handleSessionsCommand(msg);
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
if (CLOSE_COMMAND.test(msg.text)) {
|
|
1361
|
+
await handleCloseCommand(msg);
|
|
1362
|
+
return;
|
|
1363
|
+
}
|
|
1364
|
+
const attachArg = ATTACH_COMMAND.exec(msg.text)?.[1];
|
|
1365
|
+
if (attachArg !== undefined) {
|
|
1366
|
+
await handleAttachCommand(msg, attachArg);
|
|
1367
|
+
return;
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
let key = bindingKey({ platform, channelId: msg.channelId, threadId: msg.threadId });
|
|
1053
1371
|
|
|
1054
1372
|
// Team-controls: the disarm switch (spec "Disarm switch" — ANY `observe`+
|
|
1055
1373
|
// principal may disarm from chat; only the DASHBOARD re-arms). The whole
|
|
@@ -1061,18 +1379,24 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
1061
1379
|
// verb `disarm`.
|
|
1062
1380
|
const disarmCommand = team !== undefined && /^\s*!\s*disarm\s*$/i.test(msg.text);
|
|
1063
1381
|
|
|
1382
|
+
// Thread per conversation: a guild message in the channel ROOT starts a
|
|
1383
|
+
// NEW conversation — it is authorized as a spawn (never routed into an
|
|
1384
|
+
// older channel-root session) and moved into its own thread once granted.
|
|
1385
|
+
const newConversation =
|
|
1386
|
+
config.threadPerConversation &&
|
|
1387
|
+
!msg.isDM &&
|
|
1388
|
+
!msg.threadId &&
|
|
1389
|
+
!disarmCommand &&
|
|
1390
|
+
typeof msg.messageId === "string" &&
|
|
1391
|
+
typeof adapter.startThread === "function";
|
|
1392
|
+
|
|
1064
1393
|
// Team-controls chokepoint (X11): every action-bearing request passes
|
|
1065
1394
|
// through `authorizeRequest` BEFORE any session is spawned or driven.
|
|
1066
1395
|
let gate: Grant | undefined;
|
|
1067
1396
|
if (team) {
|
|
1068
|
-
const existing = store.get(key);
|
|
1397
|
+
const existing = newConversation ? undefined : store.get(key);
|
|
1069
1398
|
const decision = team.authorizeRequest({
|
|
1070
|
-
author:
|
|
1071
|
-
id: msg.userId,
|
|
1072
|
-
...(msg.bot === true ? { isBot: true } : {}),
|
|
1073
|
-
...(msg.webhook === true ? { isWebhook: true } : {}),
|
|
1074
|
-
...(msg.roleIds ? { roleIds: msg.roleIds } : {}),
|
|
1075
|
-
},
|
|
1399
|
+
author: authorOf(msg),
|
|
1076
1400
|
channelId: msg.channelId,
|
|
1077
1401
|
// Threads carry the thread id as `channelId`; pass the parent so the
|
|
1078
1402
|
// chokepoint can resolve the binding the operator actually created.
|
|
@@ -1118,6 +1442,14 @@ export function createChatGateway(deps: ChatGatewayDeps): ChatGateway {
|
|
|
1118
1442
|
}
|
|
1119
1443
|
}
|
|
1120
1444
|
|
|
1445
|
+
if (newConversation) {
|
|
1446
|
+
const threaded = await openConversationThread(msg);
|
|
1447
|
+
if (threaded) {
|
|
1448
|
+
msg = threaded;
|
|
1449
|
+
key = bindingKey({ platform, channelId: msg.channelId, threadId: msg.threadId });
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1121
1453
|
const binding = await ensureBinding(msg, key);
|
|
1122
1454
|
if (!binding || !binding.sessionId) return; // spawn pending; resolution binds it
|
|
1123
1455
|
|
package/src/server/seam.ts
CHANGED
|
@@ -26,6 +26,10 @@ export interface SeamSession {
|
|
|
26
26
|
status?: string;
|
|
27
27
|
/** Transcript path, present when the session is resumable (`mode: continue`). */
|
|
28
28
|
sessionFile?: string;
|
|
29
|
+
/** Display name, for `!sessions` / attach thread names. */
|
|
30
|
+
name?: string;
|
|
31
|
+
/** Auto-hidden (headless worker) or plugin-hidden — never auto-mirrored or listed. */
|
|
32
|
+
hidden?: boolean;
|
|
29
33
|
}
|
|
30
34
|
|
|
31
35
|
export interface SeamSpawnOptions {
|
|
@@ -38,6 +42,8 @@ export interface SeamSpawnOptions {
|
|
|
38
42
|
initialPrompt?: string;
|
|
39
43
|
/** Resume a prior pi session instead of creating a fresh one (task 4.3). */
|
|
40
44
|
resume?: { sessionFile: string };
|
|
45
|
+
/** Core-owned lifecycle declaration (`hidden` keeps the session off the board). */
|
|
46
|
+
lifecycle?: { hidden?: boolean };
|
|
41
47
|
/** Additive extension allowlist (the L3 tool guard rides here). */
|
|
42
48
|
extensions?: string[];
|
|
43
49
|
/**
|
|
@@ -59,6 +65,8 @@ export interface HostSeam {
|
|
|
59
65
|
/** Answer a PromptBus request. Returns false when the session is unreachable. */
|
|
60
66
|
sendPromptResponse(sessionId: string, response: Record<string, unknown>): boolean;
|
|
61
67
|
abort(sessionId: string): boolean;
|
|
68
|
+
/** End a session like the dashboard Shutdown (trusted hook). See change: chat-gateway-close-command. */
|
|
69
|
+
shutdownSession(sessionId: string): Promise<boolean>;
|
|
62
70
|
spawn(opts: SeamSpawnOptions): Promise<SpawnOutcome>;
|
|
63
71
|
/** Live sessions, for the attach-to-existing source. */
|
|
64
72
|
listSessions(): SeamSession[];
|
|
@@ -74,6 +82,12 @@ export interface HostSeam {
|
|
|
74
82
|
assignSessionRef(sessionId: string, ref: Record<string, unknown>): boolean;
|
|
75
83
|
/** Persist the plugin allowlist after a successful pairing redemption. */
|
|
76
84
|
persistAllowlist(ids: string[]): void;
|
|
85
|
+
/**
|
|
86
|
+
* Fires with the sessionId of EVERY forwarded session event (any session, not
|
|
87
|
+
* just this plugin's) — the auto-mirror's "first time seen" signal. Rides the
|
|
88
|
+
* host's generic `onEvent`; the event payload is not read. See change: chat-gateway-attach-dashboard-sessions.
|
|
89
|
+
*/
|
|
90
|
+
onSessionEvent(handler: (sessionId: string) => void): () => void;
|
|
77
91
|
/** Subscribe to resolution of THIS plugin's own spawned sessions. */
|
|
78
92
|
onSessionResolved(handler: (sessionId: string, pluginRef: Record<string, unknown>) => void): () => void;
|
|
79
93
|
log(level: "info" | "warn" | "error", message: string): void;
|
|
@@ -89,6 +103,8 @@ function sessionShape(raw: unknown): SeamSession | null {
|
|
|
89
103
|
cwd: typeof r.cwd === "string" ? r.cwd : undefined,
|
|
90
104
|
status: typeof r.status === "string" ? r.status : undefined,
|
|
91
105
|
sessionFile: typeof r.sessionFile === "string" ? r.sessionFile : undefined,
|
|
106
|
+
name: typeof r.name === "string" && r.name.trim() !== "" ? r.name : undefined,
|
|
107
|
+
hidden: r.hidden === true,
|
|
92
108
|
};
|
|
93
109
|
}
|
|
94
110
|
|
|
@@ -124,6 +140,9 @@ export function createHostSeam(ctx: ServerPluginContext): HostSeam {
|
|
|
124
140
|
abort(sessionId) {
|
|
125
141
|
return ctx.abortSession(sessionId);
|
|
126
142
|
},
|
|
143
|
+
shutdownSession(sessionId) {
|
|
144
|
+
return ctx.shutdownSession(sessionId);
|
|
145
|
+
},
|
|
127
146
|
async spawn(opts) {
|
|
128
147
|
const res = await ctx.spawnSession({
|
|
129
148
|
cwd: opts.cwd,
|
|
@@ -132,6 +151,7 @@ export function createHostSeam(ctx: ServerPluginContext): HostSeam {
|
|
|
132
151
|
pluginRef: opts.pluginRef,
|
|
133
152
|
initialPrompt: opts.initialPrompt,
|
|
134
153
|
resume: opts.resume,
|
|
154
|
+
...(opts.lifecycle ? { lifecycle: opts.lifecycle } : {}),
|
|
135
155
|
scope:
|
|
136
156
|
opts.extensions || opts.extensionConfig
|
|
137
157
|
? { extensions: opts.extensions, extensionConfig: opts.extensionConfig }
|
|
@@ -160,6 +180,9 @@ export function createHostSeam(ctx: ServerPluginContext): HostSeam {
|
|
|
160
180
|
ctx.logger.warn(`chat-gateway: could not persist allowlist: ${String(err)}`),
|
|
161
181
|
);
|
|
162
182
|
},
|
|
183
|
+
onSessionEvent(handler) {
|
|
184
|
+
return ctx.onEvent((sessionId) => handler(sessionId));
|
|
185
|
+
},
|
|
163
186
|
onSessionResolved(handler) {
|
|
164
187
|
return ctx.onSessionResolved(handler);
|
|
165
188
|
},
|
|
@@ -87,6 +87,8 @@ export interface TeamController {
|
|
|
87
87
|
*/
|
|
88
88
|
syncDisarmFromConfig(disarmed: boolean): void;
|
|
89
89
|
bindingFor(channelId: string, parentChannelId?: string): ResolvedBinding | undefined;
|
|
90
|
+
/** Every provisioned channel bound to a workspace (auto-mirror target lookup). */
|
|
91
|
+
boundChannelIds(): string[];
|
|
90
92
|
mirrorLevel(channelId: string, parentChannelId?: string): MirrorLevel;
|
|
91
93
|
/**
|
|
92
94
|
* Record a trusted-gated verb's host no-op (D5). Sticky; returns the reason
|
|
@@ -145,6 +147,7 @@ export function createTeamController(deps: TeamControllerDeps): TeamController {
|
|
|
145
147
|
|
|
146
148
|
return {
|
|
147
149
|
isDisarmed: () => disarmed,
|
|
150
|
+
boundChannelIds: () => [...deps.channelBindings().keys()],
|
|
148
151
|
disarm() {
|
|
149
152
|
setDisarmed(true);
|
|
150
153
|
},
|
package/src/server/team/tier.ts
CHANGED
|
@@ -55,6 +55,12 @@ export const CHAT_COMMAND_ALLOWLIST: readonly string[] = [
|
|
|
55
55
|
"get_tool_result",
|
|
56
56
|
// The spec's emergency switch. A chat-ONLY verb (see CHAT_LOCAL_VERB_TIERS).
|
|
57
57
|
"disarm",
|
|
58
|
+
// Bind a thread to an existing dashboard session (watch it). Chat-ONLY.
|
|
59
|
+
// See change: chat-gateway-attach-dashboard-sessions.
|
|
60
|
+
"attach_session",
|
|
61
|
+
// `!close` in a thread: shut down a gateway-started session (or detach an
|
|
62
|
+
// attached one), archive the thread. Chat-ONLY. See change: chat-gateway-close-command.
|
|
63
|
+
"close_session",
|
|
58
64
|
];
|
|
59
65
|
|
|
60
66
|
/**
|
|
@@ -70,6 +76,11 @@ export const CHAT_COMMAND_ALLOWLIST: readonly string[] = [
|
|
|
70
76
|
*/
|
|
71
77
|
export const CHAT_LOCAL_VERB_TIERS: ReadonlyMap<string, Tier> = new Map([
|
|
72
78
|
["disarm", "observe"],
|
|
79
|
+
// Attaching only WATCHES (mirroring is never gated, X15); every prompt sent
|
|
80
|
+
// into the thread is still authorized as `send_prompt` (control).
|
|
81
|
+
["attach_session", "observe"],
|
|
82
|
+
// Ending a session is at least as strong as prompting it (`send_prompt`).
|
|
83
|
+
["close_session", "control"],
|
|
73
84
|
]);
|
|
74
85
|
|
|
75
86
|
/** The effective per-verb tier table, read from the shared generated manifest. */
|
package/src/shared/types.ts
CHANGED
|
@@ -50,6 +50,26 @@ export interface ChatGatewayConfig {
|
|
|
50
50
|
steerPrefix?: string;
|
|
51
51
|
/** Minimum ms between `editMessage` calls on one channel. Default 1000. */
|
|
52
52
|
editThrottleMs?: number;
|
|
53
|
+
/**
|
|
54
|
+
* Board visibility of gateway-SPAWNED/RESUMED sessions. Default `hidden`:
|
|
55
|
+
* chat sessions stay off the board (revealed by "show hidden"). Attached
|
|
56
|
+
* sessions are the operator's own and are never touched.
|
|
57
|
+
*/
|
|
58
|
+
sessionVisibility?: "hidden" | "shown";
|
|
59
|
+
/**
|
|
60
|
+
* Open a platform thread on every NEW conversation (a guild message in the
|
|
61
|
+
* channel root) and bind its session to that thread. Default `true`; `false`
|
|
62
|
+
* binds the channel root to one shared session.
|
|
63
|
+
*/
|
|
64
|
+
threadPerConversation?: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Opt-in: attach every live, non-hidden session inside a bound workspace into
|
|
67
|
+
* that workspace's channel (one thread each) — at gateway start and whenever a
|
|
68
|
+
* new one is first seen. Sends transcripts to Discord at the channel's mirror
|
|
69
|
+
* level. Default `false`; only an explicit `true` enables.
|
|
70
|
+
* See change: chat-gateway-attach-dashboard-sessions.
|
|
71
|
+
*/
|
|
72
|
+
mirrorDashboardSessions?: boolean;
|
|
53
73
|
/**
|
|
54
74
|
* L3 tool policy for gateway-SPAWNED sessions (attached sessions stay
|
|
55
75
|
* ungated by design). Present ⇒ the companion guard extension is loaded.
|
|
@@ -105,6 +125,9 @@ export interface ResolvedConfig {
|
|
|
105
125
|
groupChannels: string[];
|
|
106
126
|
steerPrefix: string;
|
|
107
127
|
editThrottleMs: number;
|
|
128
|
+
sessionVisibility: "hidden" | "shown";
|
|
129
|
+
threadPerConversation: boolean;
|
|
130
|
+
mirrorDashboardSessions: boolean;
|
|
108
131
|
toolPolicy?: {
|
|
109
132
|
allow?: string[];
|
|
110
133
|
approval?: string[];
|
|
@@ -117,6 +140,9 @@ export const CONFIG_DEFAULTS = {
|
|
|
117
140
|
enabled: true,
|
|
118
141
|
steerPrefix: "!",
|
|
119
142
|
editThrottleMs: 1000,
|
|
143
|
+
sessionVisibility: "hidden",
|
|
144
|
+
threadPerConversation: true,
|
|
145
|
+
mirrorDashboardSessions: false,
|
|
120
146
|
} as const;
|
|
121
147
|
|
|
122
148
|
// ── Inbound message ───────────────────────────────────────────────────────
|
|
@@ -137,6 +163,8 @@ export interface InboundMessage {
|
|
|
137
163
|
* configured); without this a thread id is never in `groupChannels`.
|
|
138
164
|
*/
|
|
139
165
|
parentChannelId?: string;
|
|
166
|
+
/** Platform message id (the anchor a conversation thread is opened on). */
|
|
167
|
+
messageId?: string;
|
|
140
168
|
/** Platform user id of the sender. */
|
|
141
169
|
userId: string;
|
|
142
170
|
/** Display name, for logs only — never an authorization input. */
|