Политика размеров: MCP read_full_text для обрезанных данных, аудит без скрытого ограничения
- fulltext.ts: хранилище полных текстов, clipForAgent (пометка ОБРЕЗАНО + ref), MCP-сервер khb_fulltext (POST /mcp/fulltext, read_full_text с offset/length) - cli-runner: набор инструментов fulltext (--mcp-config, --strict-mcp-config, allowedTools только read_full_text) - audit.ts: фрагмент 1500 символов, полный текст сообщения читается по ref; промт получает раздел «Доступ к полному тексту» - убраны скрытые обрезки: reminder_history (текст, ответ), API истории агента, обращение в ИТ в Slack - khb-sql: подсказка при лимите строк объясняет чтение по частям - known-issues.md: политика размеров Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -15,3 +15,13 @@
|
|||||||
| P7 | Запуск агента в 09:00 пропущен 03.12 (первый запуск дня в 12:00). | Не выяснена. | открыта |
|
| P7 | Запуск агента в 09:00 пропущен 03.12 (первый запуск дня в 12:00). | Не выяснена. | открыта |
|
||||||
| P8 | Доступ сервисного аккаунта к папкам Drive потерян после переноса папок в «30. IT» (приём файлов, бэкапы, записи встреч). | Права наследуются от нового родителя. | закрыта 04.12: `khb-drive-agent` выданы права на «Meeting recordings», «Tech data and logs», «Backups», «IT security» |
|
| P8 | Доступ сервисного аккаунта к папкам Drive потерян после переноса папок в «30. IT» (приём файлов, бэкапы, записи встреч). | Права наследуются от нового родителя. | закрыта 04.12: `khb-drive-agent` выданы права на «Meeting recordings», «Tech data and logs», «Backups», «IT security» |
|
||||||
| P9 | Канал алертов `#it-support-for-agents` засорён обработанными обращениями и служебными сообщениями монитора. | Все алерты (монитор, обращения агентов, аудит) идут в один канал, а старые не чистятся. | в работе: чистка обработанных сообщений ассистентов |
|
| P9 | Канал алертов `#it-support-for-agents` засорён обработанными обращениями и служебными сообщениями монитора. | Все алерты (монитор, обращения агентов, аудит) идут в один канал, а старые не чистятся. | в работе: чистка обработанных сообщений ассистентов |
|
||||||
|
|
||||||
|
## Политика размеров (решение Юрия, 04.12.2026)
|
||||||
|
|
||||||
|
Любое ограничение размера текста, который видит агент, должно (1) явно помечаться в тексте («ОБРЕЗАНО: показано N из M символов, ref=…») и (2) оставлять агенту способ прочитать полный текст любой длины; в промте об этом упоминается.
|
||||||
|
|
||||||
|
Реализация (`src/fulltext.ts`): MCP-сервер `khb_fulltext` с инструментом `read_full_text(ref, offset, length)` в HTTP сервиса (`POST /mcp/fulltext`, токен сервиса), подключается агенту через `--mcp-config` (набор инструментов `fulltext`). Хелпер `clipForAgent(text, max, {ref})` режет с пометкой и кладёт полный текст в хранилище (48 часов). Первое применение: ночной аудит сообщений (фрагмент 1500 символов + полный текст по `slack:<канал>:<ts>`), промт аудита получает раздел «Доступ к полному тексту».
|
||||||
|
|
||||||
|
Прочие места проверены: убраны скрытые обрезки текста напоминаний и ответов (`reminder_history`, API истории), обращения агента в ИТ уходят в Slack целиком; подсказка `khb-sql` при лимите 200 строк теперь указывает, как прочитать остальное (`order by` + `limit/offset`). Остаются внешние пределы, не зависящие от нас: Slack `chat.postMessage` (35000 символов), подсказка whisper (900 символов), TTS (4000 байт на запрос, текст делится на части без потерь).
|
||||||
|
|
||||||
|
Открыто: подключить `fulltext` к агентам шага 4 (общение) и шага 2, если там появятся обрезки (сейчас их нет); проверить, что новые места с `.slice`/`left()` в промтах агентов проходят через `clipForAgent`.
|
||||||
|
|||||||
@@ -175,7 +175,7 @@ export function registerAgentRoutes(app: FastifyInstance, pool: Pool): void {
|
|||||||
q("select created_at, step, severity, body from agent_problem_log where manager_person_id = $1 order by created_at desc limit $2"),
|
q("select created_at, step, severity, body from agent_problem_log where manager_person_id = $1 order by created_at desc limit $2"),
|
||||||
q("select received_at, channel_id, message_ts, status, has_files, sender_slack_user_id from slack_message_log where manager_person_id = $1 order by received_at desc limit $2"),
|
q("select received_at, channel_id, message_ts, status, has_files, sender_slack_user_id from slack_message_log where manager_person_id = $1 order by received_at desc limit $2"),
|
||||||
q(
|
q(
|
||||||
`select r.reminded_at, left(r.reminder_text, 500) as reminder_text, r.reply_at, left(r.reply_summary, 300) as reply_summary
|
`select r.reminded_at, r.reminder_text, r.reply_at, r.reply_summary
|
||||||
from reminder_history r join assistant_project ap on ap.id = r.assistant_project_id where ap.manager_person_id = $1 order by r.reminded_at desc limit $2`,
|
from reminder_history r join assistant_project ap on ap.id = r.assistant_project_id where ap.manager_person_id = $1 order by r.reminded_at desc limit $2`,
|
||||||
),
|
),
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { spawn } from "node:child_process";
|
import { spawn } from "node:child_process";
|
||||||
|
import { FULLTEXT_TOOL } from "../fulltext.js";
|
||||||
import { mkdirSync } from "node:fs";
|
import { mkdirSync } from "node:fs";
|
||||||
import { parseUsage, type TokenUsage } from "../usage.js";
|
import { parseUsage, type TokenUsage } from "../usage.js";
|
||||||
|
|
||||||
export type ToolSet = "none" | "chat";
|
/** none - без инструментов; chat - инструменты шага 4; fulltext - без инструментов, кроме MCP read_full_text (чтение полного текста обрезанных данных, fulltext.ts). */
|
||||||
|
export type ToolSet = "none" | "chat" | "fulltext";
|
||||||
|
|
||||||
export interface ClaudeCall {
|
export interface ClaudeCall {
|
||||||
prompt: string;
|
prompt: string;
|
||||||
@@ -56,6 +58,8 @@ export interface CliRunnerOptions {
|
|||||||
bin: string;
|
bin: string;
|
||||||
timeoutMs: number;
|
timeoutMs: number;
|
||||||
model?: string;
|
model?: string;
|
||||||
|
/** Адрес и токен сервиса для MCP «полный текст» (ToolSet "fulltext"). */
|
||||||
|
fulltext?: { url: string; token: string };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Инструменты шага 4: Bash (ffmpeg, whisper, exiftool, khb-sql, khb-drive), ToolSearch и запросы JobTread через коннектор claude.ai. */
|
/** Инструменты шага 4: Bash (ffmpeg, whisper, exiftool, khb-sql, khb-drive), ToolSearch и запросы JobTread через коннектор claude.ai. */
|
||||||
@@ -68,7 +72,11 @@ export function createCliRunner(opts: CliRunnerOptions): ClaudeRunner {
|
|||||||
mkdirSync(call.cwd, { recursive: true });
|
mkdirSync(call.cwd, { recursive: true });
|
||||||
const args = ["-p", "--output-format", "json", call.resume ? "--resume" : "--session-id", call.sessionId];
|
const args = ["-p", "--output-format", "json", call.resume ? "--resume" : "--session-id", call.sessionId];
|
||||||
if (opts.model) args.push("--model", opts.model);
|
if (opts.model) args.push("--model", opts.model);
|
||||||
args.push(...(call.tools === "chat" ? CHAT_TOOLS : ["--tools", ""]));
|
if (call.tools === "fulltext") {
|
||||||
|
if (!opts.fulltext) return reject(new ClaudeError("ToolSet fulltext: не задан адрес сервиса для MCP", "failed"));
|
||||||
|
const mcp = { mcpServers: { khb_fulltext: { type: "http", url: `${opts.fulltext.url}/mcp/fulltext`, headers: { Authorization: `Bearer ${opts.fulltext.token}` } } } };
|
||||||
|
args.push("--tools", "", "--strict-mcp-config", "--mcp-config", JSON.stringify(mcp), "--allowedTools", FULLTEXT_TOOL);
|
||||||
|
} else args.push(...(call.tools === "chat" ? CHAT_TOOLS : ["--tools", ""]));
|
||||||
const child = spawn(opts.bin, args, { cwd: call.cwd, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ANTHROPIC_API_KEY: "", ...call.env } });
|
const child = spawn(opts.bin, args, { cwd: call.cwd, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ANTHROPIC_API_KEY: "", ...call.env } });
|
||||||
const tStart = Date.now();
|
const tStart = Date.now();
|
||||||
let out = "";
|
let out = "";
|
||||||
|
|||||||
@@ -131,7 +131,7 @@ export async function saveProblems(ctx: AgentContext, managerId: string, step: "
|
|||||||
const same = (a: string, b: string) => a.replace(/\s+/g, " ").trim() === b.replace(/\s+/g, " ").trim();
|
const same = (a: string, b: string) => a.replace(/\s+/g, " ").trim() === b.replace(/\s+/g, " ").trim();
|
||||||
if (!prev || !same(prev, itReq)) {
|
if (!prev || !same(prev, itReq)) {
|
||||||
await ctx.pool.query("insert into agent_problem_log (manager_person_id, step, severity, body) values ($1,$2,'it_request',$3)", [managerId, step, itReq]);
|
await ctx.pool.query("insert into agent_problem_log (manager_person_id, step, severity, body) values ($1,$2,'it_request',$3)", [managerId, step, itReq]);
|
||||||
await ctx.notifyIt(`${prev ? ":arrows_counterclockwise: ОБНОВЛЕНИЕ обращения агента в ИТ (заменяет предыдущее" : ":sos: Обращение агента в ИТ ("}${prev ? ", " : ""}${step}, менеджер ${managerId}): ${itReq.slice(0, 1500)}`);
|
await ctx.notifyIt(`${prev ? ":arrows_counterclockwise: ОБНОВЛЕНИЕ обращения агента в ИТ (заменяет предыдущее" : ":sos: Обращение агента в ИТ ("}${prev ? ", " : ""}${step}, менеджер ${managerId}): ${itReq}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (log && !/^(нет|-|\(пусто\))\.?$/i.test(log))
|
if (log && !/^(нет|-|\(пусто\))\.?$/i.test(log))
|
||||||
|
|||||||
34
packages/khbuild_assistant_prep/src/fulltext.test.ts
Normal file
34
packages/khbuild_assistant_prep/src/fulltext.test.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { chunkOf, clipForAgent, FullTextStore, handleMcp } from "./fulltext.js";
|
||||||
|
|
||||||
|
describe("полный текст для агента", () => {
|
||||||
|
it("короткий текст не меняется, длинный режется с пометкой и ref", () => {
|
||||||
|
const store = new FullTextStore();
|
||||||
|
expect(clipForAgent("abc", 10, { store })).toBe("abc");
|
||||||
|
const long = "x".repeat(50);
|
||||||
|
const out = clipForAgent(long, 10, { store, ref: "slack:C1:1.1" });
|
||||||
|
expect(out).toContain("ОБРЕЗАНО: показано 10 из 50");
|
||||||
|
expect(out).toContain("ref=slack:C1:1.1");
|
||||||
|
expect(store.get("slack:C1:1.1")).toBe(long);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("MCP: tools/list и чтение частями любой длины", () => {
|
||||||
|
const store = new FullTextStore();
|
||||||
|
const ref = store.put("0123456789".repeat(5000), "r1"); // 50 000 символов
|
||||||
|
expect(handleMcp({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } }, store)).toMatchObject({ result: { protocolVersion: "2025-06-18" } });
|
||||||
|
const list = handleMcp({ jsonrpc: "2.0", id: 2, method: "tools/list" }, store) as { result: { tools: { name: string }[] } };
|
||||||
|
expect(list.result.tools[0]!.name).toBe("read_full_text");
|
||||||
|
const first = handleMcp({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "read_full_text", arguments: { ref } } }, store) as { result: { content: { text: string }[] } };
|
||||||
|
expect(first.result.content[0]!.text).toContain("символы 0..20000 из 50000; следующий offset: 20000");
|
||||||
|
const last = handleMcp({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "read_full_text", arguments: { ref, offset: 40000, length: 100000 } } }, store) as { result: { content: { text: string }[] } };
|
||||||
|
expect(last.result.content[0]!.text).toContain("конец текста");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("MCP: неизвестный ref - ошибка инструмента, уведомления без ответа", () => {
|
||||||
|
const store = new FullTextStore();
|
||||||
|
const r = handleMcp({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "read_full_text", arguments: { ref: "нет" } } }, store) as { result: { isError: boolean } };
|
||||||
|
expect(r.result.isError).toBe(true);
|
||||||
|
expect(handleMcp({ jsonrpc: "2.0", method: "notifications/initialized" }, store)).toBeNull();
|
||||||
|
expect(chunkOf("abc", 10, 5)).toContain("за концом");
|
||||||
|
});
|
||||||
|
});
|
||||||
152
packages/khbuild_assistant_prep/src/fulltext.ts
Normal file
152
packages/khbuild_assistant_prep/src/fulltext.ts
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Политика размеров (04.12.2026): любое сокращение текста, который видит агент, обязано (1) явно помечаться в самом тексте
|
||||||
|
* («ОБРЕЗАНО … ref=…») и (2) оставлять агенту способ прочитать полный текст любой длины - MCP-инструмент `read_full_text`
|
||||||
|
* (эндпоинт POST /mcp/fulltext этого сервиса, подключается к агенту через --mcp-config, см. cli-runner.ts, ToolSet "fulltext").
|
||||||
|
* В промте агента, которому доступен инструмент, это упоминается (FULLTEXT_PROMPT_NOTE).
|
||||||
|
*/
|
||||||
|
export const FULLTEXT_TOOL = "mcp__khb_fulltext__read_full_text";
|
||||||
|
|
||||||
|
export const FULLTEXT_PROMPT_NOTE =
|
||||||
|
"Тебе доступен MCP-инструмент `read_full_text` (сервер khb_fulltext): параметры `ref`, необязательные `offset` и `length`. " +
|
||||||
|
"Если в тексте стоит пометка «ОБРЕЗАНО … ref=…», показан только фрагмент: прочитай полный текст этим инструментом по ref " +
|
||||||
|
"(текст любой длины читается частями: следующий `offset` указан в ответе) и только потом делай вывод. Не делай выводов по обрезанному фрагменту.";
|
||||||
|
|
||||||
|
const TTL_MS = 48 * 3600_000;
|
||||||
|
const MAX_ENTRIES = 5000;
|
||||||
|
const DEFAULT_CHUNK = 20_000;
|
||||||
|
const MAX_CHUNK = 100_000;
|
||||||
|
|
||||||
|
interface Entry {
|
||||||
|
text: string;
|
||||||
|
at: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Хранилище полных текстов в памяти сервиса (ref -> текст), живёт TTL; читается MCP-инструментом. */
|
||||||
|
export class FullTextStore {
|
||||||
|
private map = new Map<string, Entry>();
|
||||||
|
|
||||||
|
/** Сохраняет полный текст; ref - явный (например `slack:C0123:1700000000.000100`) или хэш текста. */
|
||||||
|
put(text: string, ref?: string): string {
|
||||||
|
const key = ref ?? `t:${createHash("sha256").update(text).digest("hex").slice(0, 16)}`;
|
||||||
|
this.map.set(key, { text, at: Date.now() });
|
||||||
|
if (this.map.size > MAX_ENTRIES) this.sweep();
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
get(ref: string): string | undefined {
|
||||||
|
const e = this.map.get(ref);
|
||||||
|
if (!e) return undefined;
|
||||||
|
if (Date.now() - e.at > TTL_MS) {
|
||||||
|
this.map.delete(ref);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return e.text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sweep(): void {
|
||||||
|
const now = Date.now();
|
||||||
|
for (const [k, e] of this.map) if (now - e.at > TTL_MS) this.map.delete(k);
|
||||||
|
// всё ещё много: убираем самые старые
|
||||||
|
if (this.map.size > MAX_ENTRIES) for (const k of [...this.map.keys()].slice(0, this.map.size - MAX_ENTRIES)) this.map.delete(k);
|
||||||
|
}
|
||||||
|
|
||||||
|
get size(): number {
|
||||||
|
return this.map.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Общее хранилище сервиса. */
|
||||||
|
export const fullTextStore = new FullTextStore();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сокращает текст для агента до max символов, если он длиннее; полный текст кладёт в хранилище, в конец сокращённого добавляет пометку с ref.
|
||||||
|
* Текст короче max возвращается как есть.
|
||||||
|
*/
|
||||||
|
export function clipForAgent(text: string, max: number, opts: { ref?: string; store?: FullTextStore } = {}): string {
|
||||||
|
if (text.length <= max) return text;
|
||||||
|
const ref = (opts.store ?? fullTextStore).put(text, opts.ref);
|
||||||
|
return `${text.slice(0, max)} …[ОБРЕЗАНО: показано ${max} из ${text.length} символов, полный текст: read_full_text ref=${ref}]`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Часть текста по offset/length с пометкой положения и следующим offset. */
|
||||||
|
export function chunkOf(text: string, offset: number, length: number): string {
|
||||||
|
const off = Math.max(0, Math.floor(offset));
|
||||||
|
const len = Math.min(MAX_CHUNK, Math.max(1, Math.floor(length)));
|
||||||
|
if (off >= text.length) return `[offset ${off} за концом текста: всего ${text.length} символов]`;
|
||||||
|
const part = text.slice(off, off + len);
|
||||||
|
const end = off + part.length;
|
||||||
|
const tail = end < text.length ? `следующий offset: ${end}` : "конец текста";
|
||||||
|
return `[символы ${off}..${end} из ${text.length}; ${tail}]\n${part}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RpcReq {
|
||||||
|
jsonrpc?: string;
|
||||||
|
id?: number | string | null;
|
||||||
|
method?: string;
|
||||||
|
params?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TOOL_DEF = {
|
||||||
|
name: "read_full_text",
|
||||||
|
description:
|
||||||
|
"Читает полный текст (любой длины) по ссылке ref из пометки «ОБРЕЗАНО … ref=…». Длинный текст читается частями: offset и length (символы), в ответе указан следующий offset.",
|
||||||
|
inputSchema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
ref: { type: "string", description: "Ссылка из пометки ОБРЕЗАНО" },
|
||||||
|
offset: { type: "integer", minimum: 0, description: "С какого символа читать (по умолчанию 0)" },
|
||||||
|
length: { type: "integer", minimum: 1, maximum: MAX_CHUNK, description: `Сколько символов (по умолчанию ${DEFAULT_CHUNK}, максимум ${MAX_CHUNK})` },
|
||||||
|
},
|
||||||
|
required: ["ref"],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Обработчик одного запроса MCP (JSON-RPC 2.0, Streamable HTTP, ответ application/json); null - уведомление без ответа. */
|
||||||
|
export function handleMcp(req: RpcReq, store: FullTextStore = fullTextStore): Record<string, unknown> | null {
|
||||||
|
const id = req.id ?? null;
|
||||||
|
const ok = (result: unknown) => ({ jsonrpc: "2.0", id, result });
|
||||||
|
const err = (code: number, message: string) => ({ jsonrpc: "2.0", id, error: { code, message } });
|
||||||
|
switch (req.method) {
|
||||||
|
case "initialize":
|
||||||
|
return ok({
|
||||||
|
protocolVersion: typeof req.params?.protocolVersion === "string" ? req.params.protocolVersion : "2025-03-26",
|
||||||
|
capabilities: { tools: {} },
|
||||||
|
serverInfo: { name: "khb_fulltext", version: "1.0.0" },
|
||||||
|
});
|
||||||
|
case "ping":
|
||||||
|
return ok({});
|
||||||
|
case "tools/list":
|
||||||
|
return ok({ tools: [TOOL_DEF] });
|
||||||
|
case "tools/call": {
|
||||||
|
const p = req.params ?? {};
|
||||||
|
if (p.name !== "read_full_text") return err(-32602, `неизвестный инструмент: ${String(p.name)}`);
|
||||||
|
const a = (p.arguments ?? {}) as { ref?: unknown; offset?: unknown; length?: unknown };
|
||||||
|
if (typeof a.ref !== "string" || !a.ref) return ok({ isError: true, content: [{ type: "text", text: "не указан ref" }] });
|
||||||
|
const text = store.get(a.ref);
|
||||||
|
if (text === undefined) return ok({ isError: true, content: [{ type: "text", text: `ref ${a.ref} не найден или устарел (хранится 48 часов); полный текст недоступен` }] });
|
||||||
|
const out = chunkOf(text, Number(a.offset ?? 0) || 0, Number(a.length ?? DEFAULT_CHUNK) || DEFAULT_CHUNK);
|
||||||
|
return ok({ content: [{ type: "text", text: out }] });
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if (req.method?.startsWith("notifications/")) return null;
|
||||||
|
return err(-32601, `метод не поддерживается: ${String(req.method)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST /mcp/fulltext: MCP-сервер «полный текст» (авторизация - общий токен сервиса, хук onRequest в http-api). */
|
||||||
|
export function registerFullTextMcp(app: FastifyInstance, store: FullTextStore = fullTextStore): void {
|
||||||
|
app.post("/mcp/fulltext", async (req, reply) => {
|
||||||
|
const body = req.body as RpcReq | RpcReq[] | undefined;
|
||||||
|
if (!body) return reply.code(400).send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "пустое тело" } });
|
||||||
|
if (Array.isArray(body)) {
|
||||||
|
const out = body.map((b) => handleMcp(b, store)).filter((x): x is Record<string, unknown> => x !== null);
|
||||||
|
return out.length ? out : reply.code(202).send();
|
||||||
|
}
|
||||||
|
const res = handleMcp(body, store);
|
||||||
|
return res ?? reply.code(202).send();
|
||||||
|
});
|
||||||
|
app.get("/mcp/fulltext", async (_req, reply) => reply.code(405).send({ error: "только POST" }));
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
|
|||||||
import Fastify, { type FastifyInstance } from "fastify";
|
import Fastify, { type FastifyInstance } from "fastify";
|
||||||
import type { Pool } from "khb_common";
|
import type { Pool } from "khb_common";
|
||||||
import { registerAgentRoutes } from "./agents-api.js";
|
import { registerAgentRoutes } from "./agents-api.js";
|
||||||
|
import { registerFullTextMcp } from "./fulltext.js";
|
||||||
import { usageSummary, type UsageLog } from "./usage.js";
|
import { usageSummary, type UsageLog } from "./usage.js";
|
||||||
import type { PrepJob, PrepResult } from "./jobs.js";
|
import type { PrepJob, PrepResult } from "./jobs.js";
|
||||||
import { checkMailAuth } from "./mail/auth.js";
|
import { checkMailAuth } from "./mail/auth.js";
|
||||||
@@ -61,6 +62,7 @@ export function buildApi(deps: PrepApiDeps): FastifyInstance {
|
|||||||
});
|
});
|
||||||
|
|
||||||
registerAgentRoutes(app, deps.pool);
|
registerAgentRoutes(app, deps.pool);
|
||||||
|
registerFullTextMcp(app);
|
||||||
|
|
||||||
if (deps.mail) {
|
if (deps.mail) {
|
||||||
const mail = deps.mail.deps;
|
const mail = deps.mail.deps;
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ export async function input7(db: Queryable, assistantProjectId: string, since: D
|
|||||||
`select jt_task_id, count(*)::int as reminders, max(reminded_at) as last_reminded_at,
|
`select jt_task_id, count(*)::int as reminders, max(reminded_at) as last_reminded_at,
|
||||||
(array_agg(reply_outcome order by reminded_at desc))[1] as last_reply_outcome,
|
(array_agg(reply_outcome order by reminded_at desc))[1] as last_reply_outcome,
|
||||||
(array_agg(reply_summary order by reminded_at desc))[1] as last_reply_summary,
|
(array_agg(reply_summary order by reminded_at desc))[1] as last_reply_summary,
|
||||||
left((array_agg(reminder_text order by reminded_at desc))[1], 300) as last_reminder_text
|
(array_agg(reminder_text order by reminded_at desc))[1] as last_reminder_text
|
||||||
from reminder_history where assistant_project_id = $1 and reminded_at >= $2
|
from reminder_history where assistant_project_id = $1 and reminded_at >= $2
|
||||||
group by jt_task_id order by max(reminded_at) desc`,
|
group by jt_task_id order by max(reminded_at) desc`,
|
||||||
[assistantProjectId, since],
|
[assistantProjectId, since],
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ const ctx: AgentContext = {
|
|||||||
log,
|
log,
|
||||||
usageLog,
|
usageLog,
|
||||||
settings: service.agent,
|
settings: service.agent,
|
||||||
runner: createCliRunner({ bin: service.agent.claudeBin, timeoutMs: service.agent.timeoutMs, model: service.agent.model }),
|
runner: createCliRunner({ bin: service.agent.claudeBin, timeoutMs: service.agent.timeoutMs, model: service.agent.model, fulltext: { url: `http://127.0.0.1:${service.http.port}`, token: service.http.token } }),
|
||||||
liveRunner: service.agent.live?.managerIds.length
|
liveRunner: service.agent.live?.managerIds.length
|
||||||
? createLiveRunner({
|
? createLiveRunner({
|
||||||
bin: service.agent.claudeBin, model: service.agent.model, timeoutMs: service.agent.timeoutMs,
|
bin: service.agent.claudeBin, model: service.agent.model, timeoutMs: service.agent.timeoutMs,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
* но за которыми не последовал ответ/обработка агента. Находки протоколируются (message_audit_run) и уходят в it-support.
|
* но за которыми не последовал ответ/обработка агента. Находки протоколируются (message_audit_run) и уходят в it-support.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { clipForAgent, FULLTEXT_PROMPT_NOTE } from "../fulltext.js";
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { mkdirSync } from "node:fs";
|
import { mkdirSync } from "node:fs";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
@@ -39,6 +40,8 @@ export const REPLY_WINDOW_SEC = 2 * 3600;
|
|||||||
/** Короткие реплики («ok», «thanks») и служебные сообщения не проверяем. */
|
/** Короткие реплики («ok», «thanks») и служебные сообщения не проверяем. */
|
||||||
export const MIN_TEXT = 20;
|
export const MIN_TEXT = 20;
|
||||||
const BATCH = 20;
|
const BATCH = 20;
|
||||||
|
/** Фрагмент сообщения в списке для классификатора; остальное агент читает MCP-инструментом read_full_text (политика размеров, fulltext.ts). */
|
||||||
|
const EXCERPT_CHARS = 1500;
|
||||||
|
|
||||||
/** Сообщения людей без ответа агента: нет сообщения бота в окне после него (и в его треде), текст не служебный. */
|
/** Сообщения людей без ответа агента: нет сообщения бота в окне после него (и в его треде), текст не служебный. */
|
||||||
export function pickUnanswered(msgs: SlackHistoryMessage[], logged: Map<string, string>): { msg: SlackHistoryMessage; logged: string | null }[] {
|
export function pickUnanswered(msgs: SlackHistoryMessage[], logged: Map<string, string>): { msg: SlackHistoryMessage; logged: string | null }[] {
|
||||||
@@ -167,7 +170,7 @@ export async function runMissedAudit(
|
|||||||
const picked = pickUnanswered(msgs, new Map(lg.rows.map((r) => [String(r.message_ts), String(r.status)])));
|
const picked = pickUnanswered(msgs, new Map(lg.rows.map((r) => [String(r.message_ts), String(r.status)])));
|
||||||
for (const p of picked) {
|
for (const p of picked) {
|
||||||
const author = (p.msg.userId && (await slack.userName?.(p.msg.userId))) || p.msg.userId || "?";
|
const author = (p.msg.userId && (await slack.userName?.(p.msg.userId))) || p.msg.userId || "?";
|
||||||
candidates.push({ n: candidates.length + 1, channel: ch, ts: p.msg.ts, author, text: p.msg.text.slice(0, 3000), logged: p.logged });
|
candidates.push({ n: candidates.length + 1, channel: ch, ts: p.msg.ts, author, text: clipForAgent(p.msg.text, EXCERPT_CHARS, { ref: `slack:${ch.id}:${p.msg.ts}` }), logged: p.logged });
|
||||||
senders.set(`${ch.id}:${p.msg.ts}`, { userId: p.msg.userId, full: p.msg.text });
|
senders.set(`${ch.id}:${p.msg.ts}`, { userId: p.msg.userId, full: p.msg.text });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -181,8 +184,8 @@ export async function runMissedAudit(
|
|||||||
const list = batch
|
const list = batch
|
||||||
.map((c) => `#${c.n} [${c.channel.label}] ${new Date(Number(c.ts) * 1000).toISOString().slice(0, 16)}Z ${c.author} (журнал: ${c.logged ?? "нет"}): ${c.text.replace(/\s+/g, " ")}`)
|
.map((c) => `#${c.n} [${c.channel.label}] ${new Date(Number(c.ts) * 1000).toISOString().slice(0, 16)}Z ${c.author} (журнал: ${c.logged ?? "нет"}): ${c.text.replace(/\s+/g, " ")}`)
|
||||||
.join("\n");
|
.join("\n");
|
||||||
const prompt = `${loadPrompt("p-missed-audit.md", {}, "proposed")}\n\n# Сообщения без ответа агента\n${list}`;
|
const prompt = `${loadPrompt("p-missed-audit.md", {}, "proposed")}\n\n# Доступ к полному тексту\n${FULLTEXT_PROMPT_NOTE}\n\n# Сообщения без ответа агента\n${list}`;
|
||||||
const res = await ctx.runner({ prompt, cwd, sessionId: randomUUID(), resume: false, tools: "none" });
|
const res = await ctx.runner({ prompt, cwd, sessionId: randomUUID(), resume: false, tools: "fulltext" });
|
||||||
const missed = parseMissed(parseSections(res.text).get("упущенные"));
|
const missed = parseMissed(parseSections(res.text).get("упущенные"));
|
||||||
for (const [n, item] of missed) {
|
for (const [n, item] of missed) {
|
||||||
const c = batch.find((x) => x.n === n);
|
const c = batch.find((x) => x.n === n);
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ export async function handleManagerMessages(
|
|||||||
// история напоминаний (вход 7): ответ менеджера закрывает последнее неотвеченное напоминание
|
// история напоминаний (вход 7): ответ менеджера закрывает последнее неотвеченное напоминание
|
||||||
if (messages.length && !opts.systemEvent) {
|
if (messages.length && !opts.systemEvent) {
|
||||||
await ctx.pool.query(
|
await ctx.pool.query(
|
||||||
`update reminder_history set reply_at = now(), reply_summary = left($2, 500), reply_outcome = 'other'
|
`update reminder_history set reply_at = now(), reply_summary = $2, reply_outcome = 'other'
|
||||||
where id = (select r.id from reminder_history r join assistant_project ap on ap.id = r.assistant_project_id
|
where id = (select r.id from reminder_history r join assistant_project ap on ap.id = r.assistant_project_id
|
||||||
where ap.manager_person_id = $1 and r.reply_at is null and r.reminded_at > now() - interval '1 day'
|
where ap.manager_person_id = $1 and r.reply_at is null and r.reminded_at > now() - interval '1 day'
|
||||||
order by r.reminded_at desc limit 1)`,
|
order by r.reminded_at desc limit 1)`,
|
||||||
@@ -431,7 +431,7 @@ ${recapBlock(st, deps.timezone)}`);
|
|||||||
// напоминание ассистента по событию - в историю напоминаний (вход 7)
|
// напоминание ассистента по событию - в историю напоминаний (вход 7)
|
||||||
await ctx.pool.query(
|
await ctx.pool.query(
|
||||||
`insert into reminder_history (assistant_project_id, reminded_at, reminder_text)
|
`insert into reminder_history (assistant_project_id, reminded_at, reminder_text)
|
||||||
select ap.id, now(), left($2, 1000) from assistant_project ap where ap.manager_person_id = $1 and ap.is_enabled order by ap.created_at limit 1`,
|
select ap.id, now(), $2 from assistant_project ap where ap.manager_person_id = $1 and ap.is_enabled order by ap.created_at limit 1`,
|
||||||
[manager.personId, reply],
|
[manager.personId, reply],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -168,6 +168,7 @@ export class MeetingWatcher {
|
|||||||
const projects = rows.map((r) => String(r.name).replace(/^\s*\d+\.\s*/, "").trim());
|
const projects = rows.map((r) => String(r.name).replace(/^\s*\d+\.\s*/, "").trim());
|
||||||
const people = [...new Set(rows.flatMap((r) => String(r.display_name).split(/\s+/)))];
|
const people = [...new Set(rows.flatMap((r) => String(r.display_name).split(/\s+/)))];
|
||||||
const text = `Weekly construction meeting. People: Arthur, ${people.join(", ")}. Projects: ${projects.join(", ")}. ${this.o.glossary.join(", ")}.`;
|
const text = `Weekly construction meeting. People: Arthur, ${people.join(", ")}. Projects: ${projects.join(", ")}. ${this.o.glossary.join(", ")}.`;
|
||||||
|
// жёсткий предел подсказки модели распознавания: whisper учитывает только последние ~224 токена initial_prompt (ограничение модели, не политики размеров)
|
||||||
return text.slice(0, 900);
|
return text.slice(0, 900);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ export async function runKhbSql(argv: string[], env: NodeJS.ProcessEnv, out: (s:
|
|||||||
const rows = res.rows.slice(0, MAX_ROWS) as Array<Record<string, unknown>>;
|
const rows = res.rows.slice(0, MAX_ROWS) as Array<Record<string, unknown>>;
|
||||||
const columns = res.fields.map((f) => f.name);
|
const columns = res.fields.map((f) => f.name);
|
||||||
out(json ? JSON.stringify(rows) : formatTable(rows, columns));
|
out(json ? JSON.stringify(rows) : formatTable(rows, columns));
|
||||||
if (res.rows.length > MAX_ROWS) out(`(показано ${MAX_ROWS} строк, есть ещё: уточните запрос - where, limit, агрегаты)`);
|
if (res.rows.length > MAX_ROWS) out(`(показано ${MAX_ROWS} строк, есть ещё: прочитайте остальное по частям - order by + limit/offset, или уточните запрос: where, агрегаты)`);
|
||||||
else out(`(${rows.length} строк)`);
|
else out(`(${rows.length} строк)`);
|
||||||
return 0;
|
return 0;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
Reference in New Issue
Block a user