@blackbelt-technology/pi-dashboard-chat-gateway-plugin 0.8.0 → 0.9.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 +4 -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/index.tsx +53 -0
- 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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blackbelt-technology/pi-dashboard-chat-gateway-plugin",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.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
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|
|
@@ -67,9 +67,9 @@
|
|
|
67
67
|
"react-dom": ">=18.0.0"
|
|
68
68
|
},
|
|
69
69
|
"dependencies": {
|
|
70
|
-
"@blackbelt-technology/dashboard-plugin-runtime": "^0.
|
|
71
|
-
"@blackbelt-technology/pi-dashboard-mcp-server-plugin": "^0.
|
|
72
|
-
"@blackbelt-technology/pi-dashboard-shared": "^0.
|
|
70
|
+
"@blackbelt-technology/dashboard-plugin-runtime": "^0.9.0",
|
|
71
|
+
"@blackbelt-technology/pi-dashboard-mcp-server-plugin": "^0.9.0",
|
|
72
|
+
"@blackbelt-technology/pi-dashboard-shared": "^0.9.0",
|
|
73
73
|
"discord.js": "^14.27.0"
|
|
74
74
|
},
|
|
75
75
|
"devDependencies": {
|
package/src/adapters/base.ts
CHANGED
|
@@ -185,6 +185,23 @@ export interface PlatformAdapter {
|
|
|
185
185
|
|
|
186
186
|
/** Rename a bound channel (a workspace rename). Never deletes. */
|
|
187
187
|
renameChannel?(channelId: string, name: string): Promise<void>;
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Open a thread anchored on `messageId` in `channelId`; resolves the new
|
|
191
|
+
* thread's id (a channel id messages can be sent to). Optional — a platform
|
|
192
|
+
* without threads omits it and the gateway keeps channel-root sessions.
|
|
193
|
+
*/
|
|
194
|
+
startThread?(
|
|
195
|
+
channelId: string,
|
|
196
|
+
messageId: string,
|
|
197
|
+
name: string,
|
|
198
|
+
): Promise<{ threadId: string }>;
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Archive (close) a thread. Optional — without it `!close` still unbinds.
|
|
202
|
+
* See change: chat-gateway-close-command.
|
|
203
|
+
*/
|
|
204
|
+
archiveThread?(threadId: string): Promise<void>;
|
|
188
205
|
}
|
|
189
206
|
|
|
190
207
|
/**
|
|
@@ -308,6 +308,15 @@ export function toDiscordControl(prompt: InteractivePrompt): DiscordControlSpec
|
|
|
308
308
|
*/
|
|
309
309
|
const VIEW_CHANNEL = 1n << 10n;
|
|
310
310
|
|
|
311
|
+
/**
|
|
312
|
+
* What the bot grants ITSELF on a channel it provisions: view, send, embed,
|
|
313
|
+
* read history, create public threads, send in threads. Required because the
|
|
314
|
+
* `@everyone` VIEW deny applies to the bot too, so a channel without this
|
|
315
|
+
* overwrite locks the bot out of the channel it just created.
|
|
316
|
+
*/
|
|
317
|
+
const BOT_SELF_ALLOW =
|
|
318
|
+
VIEW_CHANNEL | (1n << 11n) | (1n << 14n) | (1n << 16n) | (1n << 35n) | (1n << 38n);
|
|
319
|
+
|
|
311
320
|
/** Discord overwrite `type`: 0 = role, 1 = member. */
|
|
312
321
|
const OVERWRITE_ROLE = 0 as const;
|
|
313
322
|
const OVERWRITE_MEMBER = 1 as const;
|
|
@@ -359,11 +368,15 @@ export function channelNameFor(name: string): string {
|
|
|
359
368
|
export function channelOverwrites(
|
|
360
369
|
guildId: string,
|
|
361
370
|
grants: readonly ChannelOverwrite[],
|
|
371
|
+
selfId?: string,
|
|
362
372
|
): DiscordOverwrite[] {
|
|
363
373
|
const overwrites: DiscordOverwrite[] = [
|
|
364
374
|
{ id: guildId, type: OVERWRITE_ROLE, allow: 0n, deny: VIEW_CHANNEL },
|
|
365
375
|
];
|
|
366
376
|
for (const grant of grants) {
|
|
377
|
+
// The bot-self allow is appended last and wins; a grant for the bot's own
|
|
378
|
+
// id must not be able to lock it out.
|
|
379
|
+
if (selfId && grant.targetId === selfId) continue;
|
|
367
380
|
overwrites.push({
|
|
368
381
|
id: grant.targetId,
|
|
369
382
|
type: grant.kind === "role" ? OVERWRITE_ROLE : OVERWRITE_MEMBER,
|
|
@@ -371,6 +384,9 @@ export function channelOverwrites(
|
|
|
371
384
|
deny: grant.viewChannel ? 0n : VIEW_CHANNEL,
|
|
372
385
|
});
|
|
373
386
|
}
|
|
387
|
+
if (selfId) {
|
|
388
|
+
overwrites.push({ id: selfId, type: OVERWRITE_MEMBER, allow: BOT_SELF_ALLOW, deny: 0n });
|
|
389
|
+
}
|
|
374
390
|
return overwrites;
|
|
375
391
|
}
|
|
376
392
|
|
|
@@ -380,10 +396,11 @@ export function channelOverwrites(
|
|
|
380
396
|
*/
|
|
381
397
|
export function channelCreatePayload(
|
|
382
398
|
input: ProvisionChannelInput,
|
|
399
|
+
selfId?: string,
|
|
383
400
|
): DiscordChannelCreatePayload {
|
|
384
401
|
return {
|
|
385
402
|
name: channelNameFor(input.name),
|
|
386
|
-
permissionOverwrites: channelOverwrites(input.guildId, input.overwrites),
|
|
403
|
+
permissionOverwrites: channelOverwrites(input.guildId, input.overwrites, selfId),
|
|
387
404
|
};
|
|
388
405
|
}
|
|
389
406
|
|
package/src/adapters/discord.ts
CHANGED
|
@@ -96,6 +96,12 @@ export interface DiscordChannelOps {
|
|
|
96
96
|
* IS the guild id, so a reconcile must name it even for an existing channel.
|
|
97
97
|
*/
|
|
98
98
|
guildIdFor(channelId: string): Promise<string>;
|
|
99
|
+
/**
|
|
100
|
+
* The bot's own user id. Every provisioned channel carries an allow for it:
|
|
101
|
+
* the `@everyone` view deny would otherwise lock the bot out of the channel
|
|
102
|
+
* it created (real-guild 403 Missing Access).
|
|
103
|
+
*/
|
|
104
|
+
selfId(): string;
|
|
99
105
|
}
|
|
100
106
|
|
|
101
107
|
/**
|
|
@@ -309,6 +315,29 @@ export class DiscordAdapter extends BaseAdapter {
|
|
|
309
315
|
|
|
310
316
|
// ── Outbound ────────────────────────────────────────────────────────────
|
|
311
317
|
|
|
318
|
+
/** Open a public thread on the user's message (needs Create Public Threads). */
|
|
319
|
+
async startThread(
|
|
320
|
+
channelId: string,
|
|
321
|
+
messageId: string,
|
|
322
|
+
name: string,
|
|
323
|
+
): Promise<{ threadId: string }> {
|
|
324
|
+
const channel = await this.requireClient().channels.fetch(channelId);
|
|
325
|
+
if (!channel?.isTextBased() || !("messages" in channel)) {
|
|
326
|
+
throw new Error(`[discord] channel ${channelId} cannot hold threads`);
|
|
327
|
+
}
|
|
328
|
+
const message = await channel.messages.fetch(messageId);
|
|
329
|
+
// 1 day of inactivity before Discord auto-archives; a reply un-archives it.
|
|
330
|
+
const thread = await message.startThread({ name, autoArchiveDuration: 1440 });
|
|
331
|
+
return { threadId: thread.id };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Archive a thread (`!close`). See change: chat-gateway-close-command. */
|
|
335
|
+
async archiveThread(threadId: string): Promise<void> {
|
|
336
|
+
const channel = await this.requireClient().channels.fetch(threadId);
|
|
337
|
+
if (!channel?.isThread()) throw new Error(`[discord] ${threadId} is not a thread`);
|
|
338
|
+
await channel.setArchived(true, "closed from chat (!close)");
|
|
339
|
+
}
|
|
340
|
+
|
|
312
341
|
async sendMessage(channelId: string, content: string): Promise<string> {
|
|
313
342
|
const channel = await this.sendableChannel(channelId);
|
|
314
343
|
const chunks = chunkForDiscord(content);
|
|
@@ -353,7 +382,7 @@ export class DiscordAdapter extends BaseAdapter {
|
|
|
353
382
|
async provisionChannel(
|
|
354
383
|
input: ProvisionChannelInput,
|
|
355
384
|
): Promise<{ channelId: string }> {
|
|
356
|
-
const payload = channelCreatePayload(input);
|
|
385
|
+
const payload = channelCreatePayload(input, this.channelOps().selfId());
|
|
357
386
|
return this.channelOps().create(input.guildId, payload);
|
|
358
387
|
}
|
|
359
388
|
|
|
@@ -367,7 +396,7 @@ export class DiscordAdapter extends BaseAdapter {
|
|
|
367
396
|
): Promise<void> {
|
|
368
397
|
const guildId = await this.channelOps().guildIdFor(channelId);
|
|
369
398
|
await this.channelOps().update(channelId, {
|
|
370
|
-
permissionOverwrites: channelOverwrites(guildId, overwrites),
|
|
399
|
+
permissionOverwrites: channelOverwrites(guildId, overwrites, this.channelOps().selfId()),
|
|
371
400
|
});
|
|
372
401
|
}
|
|
373
402
|
|
|
@@ -459,6 +488,16 @@ export class DiscordAdapter extends BaseAdapter {
|
|
|
459
488
|
/** Real Discord channel management. */
|
|
460
489
|
private defaultOps(): DiscordChannelOps {
|
|
461
490
|
return {
|
|
491
|
+
// Refuses rather than writing an overwrite list without the bot-self allow.
|
|
492
|
+
selfId: () => {
|
|
493
|
+
const id = this.requireClient().user?.id;
|
|
494
|
+
if (!id) {
|
|
495
|
+
throw new Error(
|
|
496
|
+
"[discord] bot identity unknown (client not ready); refusing to write overwrites without the bot-self allow",
|
|
497
|
+
);
|
|
498
|
+
}
|
|
499
|
+
return id;
|
|
500
|
+
},
|
|
462
501
|
create: async (guildId, payload) => {
|
|
463
502
|
const guild = await this.requireClient().guilds.fetch(guildId);
|
|
464
503
|
const created = await guild.channels.create({
|
package/src/client/index.tsx
CHANGED
|
@@ -64,6 +64,12 @@ export function ChatGatewaySettings(_props: SlotProps<"settings-section">): Reac
|
|
|
64
64
|
const send = usePluginSend();
|
|
65
65
|
|
|
66
66
|
const [enabled, setEnabled] = useState(config?.enabled ?? true);
|
|
67
|
+
const [threadPerConversation, setThreadPerConversation] = useState(
|
|
68
|
+
config?.threadPerConversation ?? true,
|
|
69
|
+
);
|
|
70
|
+
const [mirrorDashboardSessions, setMirrorDashboardSessions] = useState(
|
|
71
|
+
config?.mirrorDashboardSessions ?? false,
|
|
72
|
+
);
|
|
67
73
|
const [token, setToken] = useState("");
|
|
68
74
|
const [allowedRoots, setAllowedRoots] = useState("");
|
|
69
75
|
const [defaultCwd, setDefaultCwd] = useState("");
|
|
@@ -72,6 +78,9 @@ export function ChatGatewaySettings(_props: SlotProps<"settings-section">): Reac
|
|
|
72
78
|
const [admins, setAdmins] = useState("");
|
|
73
79
|
const [groupChannels, setGroupChannels] = useState("");
|
|
74
80
|
const [steerPrefix, setSteerPrefix] = useState(config?.steerPrefix ?? "!");
|
|
81
|
+
const [sessionVisibility, setSessionVisibility] = useState<"hidden" | "shown">(
|
|
82
|
+
config?.sessionVisibility ?? "hidden",
|
|
83
|
+
);
|
|
75
84
|
|
|
76
85
|
const [busy, setBusy] = useState(false);
|
|
77
86
|
const [notice, setNotice] = useState<{ kind: "ok" | "error"; text: string } | null>(null);
|
|
@@ -86,6 +95,8 @@ export function ChatGatewaySettings(_props: SlotProps<"settings-section">): Reac
|
|
|
86
95
|
|
|
87
96
|
const saved = {
|
|
88
97
|
enabled: config?.enabled ?? true,
|
|
98
|
+
threadPerConversation: config?.threadPerConversation ?? true,
|
|
99
|
+
mirrorDashboardSessions: config?.mirrorDashboardSessions ?? false,
|
|
89
100
|
allowedRoots: (config?.allowedRoots ?? []).join("\n"),
|
|
90
101
|
defaultCwd: config?.defaultCwd ?? "",
|
|
91
102
|
fixedMap: formatFixedMap(config?.fixedMap ?? {}),
|
|
@@ -93,6 +104,7 @@ export function ChatGatewaySettings(_props: SlotProps<"settings-section">): Reac
|
|
|
93
104
|
admins: (config?.admins ?? []).join(", "),
|
|
94
105
|
groupChannels: (config?.groupChannels ?? []).join(", "),
|
|
95
106
|
steerPrefix: config?.steerPrefix ?? "!",
|
|
107
|
+
sessionVisibility: config?.sessionVisibility ?? "hidden",
|
|
96
108
|
};
|
|
97
109
|
|
|
98
110
|
const savedKey = JSON.stringify(saved);
|
|
@@ -100,6 +112,8 @@ export function ChatGatewaySettings(_props: SlotProps<"settings-section">): Reac
|
|
|
100
112
|
useEffect(() => {
|
|
101
113
|
const d = dirtyFields.current;
|
|
102
114
|
if (!d.has("enabled")) setEnabled(saved.enabled);
|
|
115
|
+
if (!d.has("threadPerConversation")) setThreadPerConversation(saved.threadPerConversation);
|
|
116
|
+
if (!d.has("mirrorDashboardSessions")) setMirrorDashboardSessions(saved.mirrorDashboardSessions);
|
|
103
117
|
if (!d.has("allowedRoots")) setAllowedRoots(saved.allowedRoots);
|
|
104
118
|
if (!d.has("defaultCwd")) setDefaultCwd(saved.defaultCwd);
|
|
105
119
|
if (!d.has("fixedMap")) setFixedMap(saved.fixedMap);
|
|
@@ -107,6 +121,7 @@ export function ChatGatewaySettings(_props: SlotProps<"settings-section">): Reac
|
|
|
107
121
|
if (!d.has("admins")) setAdmins(saved.admins);
|
|
108
122
|
if (!d.has("groupChannels")) setGroupChannels(saved.groupChannels);
|
|
109
123
|
if (!d.has("steerPrefix")) setSteerPrefix(saved.steerPrefix);
|
|
124
|
+
if (!d.has("sessionVisibility")) setSessionVisibility(saved.sessionVisibility);
|
|
110
125
|
}, [savedKey]);
|
|
111
126
|
|
|
112
127
|
useEffect(() => {
|
|
@@ -140,6 +155,8 @@ export function ChatGatewaySettings(_props: SlotProps<"settings-section">): Reac
|
|
|
140
155
|
try {
|
|
141
156
|
const partial: Record<string, unknown> = {
|
|
142
157
|
enabled,
|
|
158
|
+
threadPerConversation,
|
|
159
|
+
mirrorDashboardSessions,
|
|
143
160
|
allowedRoots: parseLines(allowedRoots),
|
|
144
161
|
defaultCwd,
|
|
145
162
|
fixedMap: parseFixedMap(fixedMap),
|
|
@@ -147,6 +164,7 @@ export function ChatGatewaySettings(_props: SlotProps<"settings-section">): Reac
|
|
|
147
164
|
admins: parseList(admins),
|
|
148
165
|
groupChannels: parseList(groupChannels),
|
|
149
166
|
steerPrefix,
|
|
167
|
+
sessionVisibility,
|
|
150
168
|
};
|
|
151
169
|
// A blank token means "keep the stored secret" — never send it, so a
|
|
152
170
|
// save cannot erase the token by omission-through-the-form.
|
|
@@ -182,6 +200,26 @@ export function ChatGatewaySettings(_props: SlotProps<"settings-section">): Reac
|
|
|
182
200
|
Enabled
|
|
183
201
|
</label>
|
|
184
202
|
|
|
203
|
+
<label className="flex items-center gap-2 text-xs text-[var(--text-secondary)]">
|
|
204
|
+
<input
|
|
205
|
+
type="checkbox"
|
|
206
|
+
data-testid="chat-gateway-thread-per-conversation"
|
|
207
|
+
checked={threadPerConversation}
|
|
208
|
+
onChange={(e) => markDirty("threadPerConversation", setThreadPerConversation)(e.target.checked)}
|
|
209
|
+
/>
|
|
210
|
+
One thread per conversation (new channel message → new thread + session)
|
|
211
|
+
</label>
|
|
212
|
+
|
|
213
|
+
<label className="flex items-center gap-2 text-xs text-[var(--text-secondary)]">
|
|
214
|
+
<input
|
|
215
|
+
type="checkbox"
|
|
216
|
+
data-testid="chat-gateway-mirror-dashboard-sessions"
|
|
217
|
+
checked={mirrorDashboardSessions}
|
|
218
|
+
onChange={(e) => markDirty("mirrorDashboardSessions", setMirrorDashboardSessions)(e.target.checked)}
|
|
219
|
+
/>
|
|
220
|
+
Show dashboard sessions on Discord (one thread each; sends their activity to Discord)
|
|
221
|
+
</label>
|
|
222
|
+
|
|
185
223
|
<div>
|
|
186
224
|
<span className={label}>Discord bot token</span>
|
|
187
225
|
<input
|
|
@@ -268,6 +306,21 @@ export function ChatGatewaySettings(_props: SlotProps<"settings-section">): Reac
|
|
|
268
306
|
/>
|
|
269
307
|
</div>
|
|
270
308
|
|
|
309
|
+
<label className="block">
|
|
310
|
+
<span className={label}>Chat sessions on the board</span>
|
|
311
|
+
<select
|
|
312
|
+
data-testid="chat-gateway-session-visibility"
|
|
313
|
+
value={sessionVisibility}
|
|
314
|
+
onChange={(e) =>
|
|
315
|
+
markDirty("sessionVisibility", setSessionVisibility)(e.target.value as "hidden" | "shown")
|
|
316
|
+
}
|
|
317
|
+
className={`${field} max-w-[16rem]`}
|
|
318
|
+
>
|
|
319
|
+
<option value="hidden">Hidden (show with "show hidden")</option>
|
|
320
|
+
<option value="shown">Shown</option>
|
|
321
|
+
</select>
|
|
322
|
+
</label>
|
|
323
|
+
|
|
271
324
|
<div className="flex items-center gap-2">
|
|
272
325
|
<button
|
|
273
326
|
type="button"
|
package/src/configSchema.json
CHANGED
|
@@ -49,6 +49,22 @@
|
|
|
49
49
|
"default": [],
|
|
50
50
|
"description": "L4: guild channel ids explicitly opted in. Any other guild channel is inert; DMs are isolated."
|
|
51
51
|
},
|
|
52
|
+
"threadPerConversation": {
|
|
53
|
+
"type": "boolean",
|
|
54
|
+
"default": true,
|
|
55
|
+
"description": "Open a Discord thread on every new message in the channel root and run that conversation in its own session inside the thread. false = one shared session for the whole channel."
|
|
56
|
+
},
|
|
57
|
+
"mirrorDashboardSessions": {
|
|
58
|
+
"type": "boolean",
|
|
59
|
+
"default": false,
|
|
60
|
+
"description": "Show sessions started in the dashboard on Discord: each live, non-hidden session inside a bound workspace gets its own thread in that workspace's channel (existing ones when turned on, new ones as they start). Sends their activity to Discord at the channel's mirror level. You can always attach one by hand with !sessions / !attach."
|
|
61
|
+
},
|
|
62
|
+
"sessionVisibility": {
|
|
63
|
+
"type": "string",
|
|
64
|
+
"enum": ["hidden", "shown"],
|
|
65
|
+
"default": "hidden",
|
|
66
|
+
"description": "Board visibility of sessions the gateway starts or resumes. hidden (default) keeps Discord sessions off the board (revealed by \"show hidden\"); attached sessions are never touched."
|
|
67
|
+
},
|
|
52
68
|
"steerPrefix": {
|
|
53
69
|
"type": "string",
|
|
54
70
|
"default": "!",
|
package/src/server/config.ts
CHANGED
|
@@ -77,6 +77,14 @@ export function resolveConfig(raw: ChatGatewayConfig | undefined): ResolvedConfi
|
|
|
77
77
|
groupChannels: normalizeStringArray(src.groupChannels),
|
|
78
78
|
steerPrefix,
|
|
79
79
|
editThrottleMs: normalizeThrottle(src.editThrottleMs),
|
|
80
|
+
// Only an explicit "shown" opts out; anything else stays hidden.
|
|
81
|
+
sessionVisibility: src.sessionVisibility === "shown" ? "shown" : CONFIG_DEFAULTS.sessionVisibility,
|
|
82
|
+
threadPerConversation:
|
|
83
|
+
typeof src.threadPerConversation === "boolean"
|
|
84
|
+
? src.threadPerConversation
|
|
85
|
+
: CONFIG_DEFAULTS.threadPerConversation,
|
|
86
|
+
// Opt-in: sends transcripts to Discord, so only an explicit `true` enables.
|
|
87
|
+
mirrorDashboardSessions: src.mirrorDashboardSessions === true,
|
|
80
88
|
...(normalizeToolPolicy(src.toolPolicy) === undefined
|
|
81
89
|
? {}
|
|
82
90
|
: { toolPolicy: normalizeToolPolicy(src.toolPolicy) }),
|
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. */
|