Проектные каналы Slack и huddle: project_channel, режим проектного канала, промт, спецификация ассистента CEO
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -19,7 +19,18 @@ export interface ManagerInfo {
|
||||
ttsVoice?: string | null;
|
||||
}
|
||||
|
||||
/** Проектный канал Slack: проект задан каналом, уточнять его у пользователя не нужно. */
|
||||
export interface ProjectContext {
|
||||
jobId: string;
|
||||
jobName: string | null;
|
||||
channel: string;
|
||||
senderName: string | null;
|
||||
isHuddle: boolean;
|
||||
}
|
||||
|
||||
export interface IncomingMessage {
|
||||
/** Контекст проектного канала (если сообщение пришло из него). */
|
||||
project?: ProjectContext;
|
||||
channel: string;
|
||||
ts: string;
|
||||
text: string;
|
||||
@@ -145,11 +156,21 @@ export async function handleManagerMessages(
|
||||
const attBlock = attachments.length
|
||||
? attachments.map((a) => `- ${a.path} (${a.mimetype || "?"}, ${a.size} байт)${a.link ? ` | Drive: ${a.link}` : ""}`).join("\n")
|
||||
: "(вложений нет)";
|
||||
const proj = messages.find((m) => m.project)?.project;
|
||||
const projectBlock = proj
|
||||
? [
|
||||
"",
|
||||
`# Проектный канал\nЭто канал проекта «${proj.jobName ?? proj.jobId}» (JobTread job id ${proj.jobId}). Всё написанное здесь относится к этому проекту - проект НЕ уточняй. Отправители (Slack id): ${messages.map((m) => m.senderUserId).filter(Boolean).join(", ") || "неизвестны"}${proj.senderName ? ` (последний: ${proj.senderName})` : ""}.${
|
||||
writableJobs.includes(proj.jobId) ? "" : "\nЗапись в JobTread по этому проекту сейчас НЕ разрешена: ничего не записывай, только отвечай и опиши, что записал бы."
|
||||
}`,
|
||||
]
|
||||
: [];
|
||||
const prompt = [
|
||||
loadPrompt("step4_manager_chat.md", { media_dir: mediaDir }),
|
||||
loadPrompt(proj ? "project_channel.md" : "step4_manager_chat.md", { media_dir: mediaDir }),
|
||||
"",
|
||||
`# Дата и время\n${now.toISOString()} (UTC); дата по Тампе: ${today}; сообщений менеджера за последние сутки: ${todayCount}`,
|
||||
...(opts.systemEvent ? ["", `# Системное событие\n${opts.systemEvent}`] : []),
|
||||
...projectBlock,
|
||||
"",
|
||||
`# Список задач на сегодня\n${await todayList(ctx, manager.personId, today)}`,
|
||||
"",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Pool } from "khb_common";
|
||||
import { isReplyMode } from "./tts.js";
|
||||
import { handleManagerMessages, type ChatDeps, type IncomingMessage, type ManagerInfo } from "./chat.js";
|
||||
import { handleManagerMessages, type ChatDeps, type IncomingMessage, type ManagerInfo, type ProjectContext } from "./chat.js";
|
||||
|
||||
interface Pending {
|
||||
manager: ManagerInfo;
|
||||
@@ -57,11 +57,14 @@ export class SlackIntake {
|
||||
}
|
||||
|
||||
private async handle(ev: Record<string, unknown>): Promise<void> {
|
||||
if (ev.type !== "message" || ev.bot_id || !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
|
||||
if (ev.type !== "message") return;
|
||||
const channel = String(ev.channel ?? "");
|
||||
const user = String(ev.user ?? "");
|
||||
const ts = String(ev.ts ?? "");
|
||||
if (!channel || !user || !ts) return;
|
||||
if (!channel || !ts) return;
|
||||
const project = await this.findProjectByChannel(channel);
|
||||
if (project) return this.handleProjectEvent(ev, project);
|
||||
if (ev.bot_id || !user || !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
|
||||
// чат менеджера: пишет любой участник канала, обрабатывается как сообщение менеджера (отправитель сохраняется в журнале)
|
||||
let manager = await this.findManagerByChannel(channel);
|
||||
if (!manager && this.opts.channelIds.includes(channel)) manager = await this.findManagerBySlackUser(user);
|
||||
@@ -70,6 +73,56 @@ export class SlackIntake {
|
||||
await this.accept(manager, { channel, ts, text: String(ev.text ?? ""), fileIds: files, senderUserId: user });
|
||||
}
|
||||
|
||||
/** Проектный канал: проект определяется каналом (таблица project_channel). */
|
||||
async findProjectByChannel(channel: string): Promise<{ jobId: string; jobName: string | null } | null> {
|
||||
const { rows } = await this.pool.query(
|
||||
"select pc.jt_job_id, j.name from project_channel pc left join jt_job j on j.id = pc.jt_job_id where pc.channel_id = $1 and pc.is_enabled",
|
||||
[channel],
|
||||
);
|
||||
return rows[0] ? { jobId: String(rows[0].jt_job_id), jobName: (rows[0].name as string | null) ?? null } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сообщение проектного канала. Принимаются люди и huddle (заметки и расшифровка от Slackbot: файлы canvas и huddle_transcript).
|
||||
* Ключ памяти и сессии - ответственный менеджер проекта (assistant_project), иначе отправитель.
|
||||
*/
|
||||
private async handleProjectEvent(ev: Record<string, unknown>, project: { jobId: string; jobName: string | null }): Promise<void> {
|
||||
const channel = String(ev.channel);
|
||||
const ts = String(ev.ts);
|
||||
const user = String(ev.user ?? "");
|
||||
const rawFiles = (ev.files as { id?: string; name?: string; mimetype?: string; filetype?: string }[] | undefined) ?? [];
|
||||
const huddleFiles = rawFiles.filter((f) => /huddle|vnd\.slack-docs/i.test(`${f.name ?? ""} ${f.mimetype ?? ""} ${f.filetype ?? ""}`));
|
||||
const isHuddle = ev.subtype === "huddle_thread" || huddleFiles.length > 0;
|
||||
if (ev.bot_id && !isHuddle) return; // собственные ответы и прочие боты
|
||||
if (!isHuddle && !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
|
||||
if (isHuddle && !rawFiles.length) return; // "A huddle started" без материалов
|
||||
const sender = user ? (await this.pool.query("select id, display_name from person where slack_user_id = $1 and is_active", [user])).rows[0] : undefined;
|
||||
const owner =
|
||||
(
|
||||
await this.pool.query(
|
||||
"select ap.manager_person_id as id, p.display_name from assistant_project ap join person p on p.id = ap.manager_person_id where ap.jt_job_id = $1 and ap.manager_person_id is not null limit 1",
|
||||
[project.jobId],
|
||||
)
|
||||
).rows[0] ?? sender;
|
||||
if (!owner) {
|
||||
this.deps.ctx.log.warn({ channel, user }, "проектный канал: нет ответственного менеджера и известного отправителя - сообщение пропущено");
|
||||
return;
|
||||
}
|
||||
const manager = (await this.findManagerByPerson(String(owner.id))) ?? { personId: String(owner.id), name: String(owner.display_name), slackUserId: null, slackChannelId: channel };
|
||||
const ctx: ProjectContext = { jobId: project.jobId, jobName: project.jobName, channel, senderName: (sender?.display_name as string | undefined) ?? null, isHuddle };
|
||||
const text = (isHuddle ? "[Slack huddle: заметки и расшифровка во вложениях] " : "") + String(ev.text ?? "");
|
||||
await this.accept({ ...manager, slackChannelId: channel }, { channel, ts, text, fileIds: rawFiles.map((f) => String(f.id)).filter(Boolean), senderUserId: user || undefined, project: ctx });
|
||||
}
|
||||
|
||||
async findManagerByPerson(personId: string): Promise<ManagerInfo | null> {
|
||||
const { rows } = await this.pool.query(
|
||||
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice
|
||||
from construction_manager cm join person p on p.id = cm.person_id where cm.person_id = $1 limit 1`,
|
||||
[personId],
|
||||
);
|
||||
return rows[0] ? rowToManager(rows[0]) : null;
|
||||
}
|
||||
|
||||
/** Менеджер чата (по slack_channel_id или единственный активный менеджер для каналов из настроек). */
|
||||
async findManagerByChannel(channel: string): Promise<ManagerInfo | null> {
|
||||
const { rows } = await this.pool.query(
|
||||
|
||||
Reference in New Issue
Block a user