Compare commits
3 Commits
codex/issu
...
codex/issu
| Author | SHA1 | Date | |
|---|---|---|---|
| a7f3f36d2b | |||
| c0fb9d1e66 | |||
| 59b496aee1 |
@@ -404,11 +404,11 @@ This requires `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID`, and a configured LLM in
|
||||
|
||||
#### Intelligence Terminal Tool Agent
|
||||
|
||||
When `TELEGRAM_AGENT_ENABLED=true`, the chat can perform up to `TELEGRAM_AGENT_MAX_STEPS` structured tool calls before answering. The allowlist includes system status, the approved Security Manager profile, latest brief, sweep delta, markets, source health, evidence search, memory, predictions, scenarios, and generated ideas. The agent has no generic shell, filesystem, network, environment, or secret-access tool.
|
||||
When `TELEGRAM_AGENT_ENABLED=true`, the chat can perform up to `TELEGRAM_AGENT_MAX_STEPS` structured tool calls before answering. The allowlist includes system status, the approved Security Manager profile, latest brief, sweep delta, markets, source health, local evidence search, bounded public web/news search through GDELT, memory, predictions, scenarios, and generated ideas. The agent has no generic shell, filesystem, environment, secret-access, or arbitrary network tool.
|
||||
|
||||
Read-only tools run automatically. `trigger_sweep`, `mute_alerts`, and `unmute_alerts` return an expiring confirmation request with Telegram **Confirm** and **Cancel** buttons. Confirmation is bound to the configured chat and cannot be reused. `/trace` exposes only tool names, duration, status, and a short operational rationale; private chain-of-thought is neither requested nor stored.
|
||||
|
||||
With `TELEGRAM_AGENT_PROACTIVE_ENABLED=true`, material sweep changes trigger a separate bounded analysis. The Security Manager can cross-check the approved profile, evidence, source health, scenarios, memory, and predictions before deciding whether to notify. A cooldown limits repeat notifications. Without a completed profile, fixed alert rules remain the fallback; with a profile, successful agent decisions respect its alert level and quiet hours. FLASH alerts can override quiet hours.
|
||||
With `TELEGRAM_AGENT_PROACTIVE_ENABLED=true`, material sweep changes trigger a separate bounded analysis. The Security Manager can cross-check the approved profile, evidence, source health, scenarios, memory, predictions, and bounded GDELT web/news results before deciding whether to notify. A cooldown limits repeat notifications. Without a completed profile, fixed alert rules remain the fallback; with a profile, successful agent decisions respect its alert level and quiet hours. FLASH alerts can override quiet hours.
|
||||
|
||||
#### Security Manager First Start
|
||||
|
||||
@@ -420,11 +420,13 @@ The Security Manager uses the profile to rank proximity, severity, time horizon,
|
||||
|
||||
The Security Manager's conversational identity is **DAVE**, a synthetic security-management construct. DAVE adapts language, formality, directness, answer length, formatting, and technical depth to the operator's current message and bounded chat history. Explicit style requests take priority. The adaptation does not copy spelling mistakes, hostility, panic, or unsupported certainty, and urgent safety instructions remain concise and unambiguous. DAVE does not claim human emotions, consciousness, a body, or access beyond the terminal's allowlisted tools.
|
||||
|
||||
DAVE Telegram answers are sent as plain-text chat messages. Long AI or proactive answers are split into smaller conversational messages so Telegram does not show giant report blocks or visible Markdown markers such as `**bold**`. The first proactive message should carry the immediate assessment; evidence and tool traces are sent as separate short follow-ups when present.
|
||||
|
||||
The language selected during Security Manager onboarding is enforced across direct chat, multi-tool answers, tool-loop finalization, dynamic presence, and proactive sweep alerts. This does not depend on the model deciding to read the profile first. Server-generated labels such as priority, evidence, and tool traces are localized as well.
|
||||
|
||||
#### Dynamic DAVE Presence
|
||||
|
||||
`DAVE_PRESENCE_ENABLED=true` lets DAVE initiate Telegram conversations without fixed daily times. Evaluations occur at randomized intervals and can be pulled forward by material sweep changes. DAVE considers current data freshness, source integrity, recent changes, evidence, the encrypted Security Manager profile, time since your last interaction, and whether another message would add value. It may send a relevant warning, situation update, evidence-grounded all-clear, practical suggestion, or one natural context question. It stays silent when a message would only add noise.
|
||||
`DAVE_PRESENCE_ENABLED=true` lets DAVE initiate Telegram conversations without fixed daily times. Evaluations occur at randomized intervals and can be pulled forward by material sweep changes. DAVE considers current data freshness, source integrity, recent changes, evidence, bounded web/news corroboration when useful, the encrypted Security Manager profile, time since your last interaction, and whether another message would add value. It may send a relevant warning, situation update, evidence-grounded all-clear, practical suggestion, or one natural context question. It stays silent when a message would only add noise.
|
||||
|
||||
Dynamic presence respects profile quiet hours, a daily message cap, a minimum gap between messages, and an idle period after your own chat activity. Evaluation timing and counters persist in `runs/dave-presence-state.json`, preventing restart spam. Scheduled presence cannot execute mutating tools or bypass confirmation. This feature is opt-in because it consumes LLM requests and sends unsolicited Telegram messages.
|
||||
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
# Agent Handoff
|
||||
|
||||
Last updated: 2026-07-05
|
||||
Last updated: 2026-07-07
|
||||
|
||||
## DAVE Conversational Telegram Delivery And Web Search
|
||||
|
||||
- Issue #82 tracks operator feedback from 2026-07-07: proactive DAVE messages were too report-like, used visible Markdown markers, arrived as large text blocks, and needed a way to start web searches from chat.
|
||||
- Implementation branch in progress: `codex/issue-dave-conversation-web-search`.
|
||||
- DAVE persona now explicitly prefers live chat style, short natural paragraphs, no visible Markdown syntax, and compact first proactive/presence messages.
|
||||
- Telegram transport has `sendConversation(...)`, which strips visible Markdown syntax for plain-text AI chat and splits large AI/proactive responses into smaller Telegram messages. Handler responses can set `conversation: true`.
|
||||
- Proactive sweep alerts and dynamic presence now use the conversation transport. The DAVE answer, evidence, and tool trace are sent as separate short messages where possible.
|
||||
- The terminal agent has a new read-only `web_search` tool backed by GDELT DOC search. It is bounded by query length, result limit, and time window; it does not provide arbitrary shell/filesystem/secret/network access.
|
||||
- Tests added/updated: Telegram conversation splitting/Markdown cleanup and bounded `web_search` registry behavior.
|
||||
|
||||
## Dynamic DAVE Presence
|
||||
|
||||
@@ -19,6 +29,11 @@ Last updated: 2026-07-05
|
||||
|
||||
## Latest Completed Work
|
||||
|
||||
- Issue #79 / PR #80 fixed proactive DAVE alerts ignoring the onboarding profile language. The screenshot showed German dynamic presence followed by an English `[AGENT PRIORITY]` alert. Merge commit: `59b496aee19b446a7cdeae74d119778cfbd92d8f`.
|
||||
- The validated profile language is now an explicit required runtime parameter for direct provider chat, multi-tool reasoning, final-only synthesis, dynamic presence, and proactive sweep analysis. This no longer depends on the model choosing to call `get_security_profile`.
|
||||
- Server-generated wrappers are localized (`DAVE // PRIORITÄT`, `Belege`, `Werkzeuge`, `AKTIV`). Provider, tool-finalization, and presence language tests were added. PR runs 959-960 and production runs 961-963 passed.
|
||||
- The registry image was redeployed to Dockge. Live verification read only the encrypted profile language code and confirmed `de`; the container was `running/healthy`, profile persisted, agent and presence enabled, and no sweep error was present.
|
||||
|
||||
- Issue #76 / PR #77 fixed a second local-model protocol leak: ChatML-style output such as `<|tool_call>call:get_evidence{query:"...",limit:5}<tool_call|>` was previously treated as user-facing text. Merge commit: `7f140021f037cbc351c9a3b39a5eb3610bfc4939`.
|
||||
- The controlled agent now parses bounded tagged calls into the normal allowlisted tool path without `eval`, recognizes tagged JSON envelopes, and treats malformed protocol-like output as a repairable protocol error. Tool tags are never accepted as final Telegram text.
|
||||
- The exact observed Russia-query format and a malformed-tag variant are regression fixtures. PR runs 935-936 and production runs 937-939 passed.
|
||||
|
||||
@@ -108,7 +108,7 @@ export class DavePresence {
|
||||
this._save();
|
||||
try {
|
||||
const runtime = this.getRuntime();
|
||||
const prompt = `Decide whether DAVE should initiate a natural, useful conversation with the operator now. This is a dynamic presence evaluation, not a fixed scheduled briefing. Inspect the security profile and current terminal intelligence using only read-only tools. Consider freshness, source integrity, recent sweep changes, evidence, scenarios, personal relevance, time since interaction, and whether there is something genuinely useful to say. You may provide a concise relevant warning, situational update, evidence-grounded all-clear, practical suggestion, or one natural question that improves protection or context. Set notify=false when speaking would add noise. Never call mutating tools. Never imply consciousness, feelings, continuous observation, or activity outside this evaluation. Local time: ${clock.time}; timezone: ${timezone}; sent today: ${this.state.sentCount}/${this.maxPerDay}; last operator interaction: ${this.state.lastUserInteractionAt || 'unknown'}; last DAVE message: ${this.state.lastSentAt || 'none'}.`;
|
||||
const prompt = `Decide whether DAVE should initiate a natural, useful conversation with the operator now. This is a dynamic presence evaluation, not a fixed scheduled briefing. Inspect the security profile and current terminal intelligence using only read-only tools, including web_search only when current external corroboration is necessary. Consider freshness, source integrity, recent sweep changes, evidence, scenarios, personal relevance, time since interaction, and whether there is something genuinely useful to say. You may provide a concise relevant warning, situational update, evidence-grounded all-clear, practical suggestion, or one natural question that improves protection or context. Set notify=false when speaking would add noise. Never call mutating tools. Never imply consciousness, feelings, continuous observation, or activity outside this evaluation. If notifying, write one short chat-style message without visible Markdown, headings, tables, or report sections. Local time: ${clock.time}; timezone: ${timezone}; sent today: ${this.state.sentCount}/${this.maxPerDay}; last operator interaction: ${this.state.lastUserInteractionAt || 'unknown'}; last DAVE message: ${this.state.lastSentAt || 'none'}.`;
|
||||
const result = await this.agent.run(prompt, {
|
||||
chatId: 'dave-presence',
|
||||
context: String(await this.getContext()).slice(0, 12000),
|
||||
@@ -123,9 +123,12 @@ export class DavePresence {
|
||||
|
||||
const german = profile.language === 'de';
|
||||
const evidence = result.evidence?.length
|
||||
? `\n\n${german ? 'Belege' : 'Evidence'}:\n${result.evidence.slice(0, 4).map(item => `- ${item}`).join('\n')}`
|
||||
? `${german ? 'Belege' : 'Evidence'}:\n${result.evidence.slice(0, 4).map(item => `- ${item}`).join('\n')}`
|
||||
: '';
|
||||
const sent = await this.alerter.sendMessage(`[DAVE // ${german ? 'AKTIV' : 'ACTIVE'}]\n${result.answer}${evidence}`, { parseMode: null });
|
||||
const messages = [`[DAVE // ${german ? 'AKTIV' : 'ACTIVE'}]\n${result.answer}`, evidence].filter(Boolean);
|
||||
const sent = typeof this.alerter.sendConversation === 'function'
|
||||
? await this.alerter.sendConversation(messages, { maxChunkChars: 800 })
|
||||
: await this.alerter.sendMessage(messages.join('\n\n'), { parseMode: null });
|
||||
if (!sent?.ok && sent !== true) {
|
||||
this._schedule(now, this.minIntervalMs);
|
||||
return this._result(false, 'send_failed');
|
||||
|
||||
@@ -239,6 +239,7 @@ SECURITY MANAGER METHOD:
|
||||
- Use get_security_profile when location, household, mobility, dependencies, language, quiet hours, or personal relevance affects the answer.
|
||||
- Prioritize proximity, time horizon, severity, confidence, and the operator's stated risk priorities.
|
||||
- Separate verified facts, official guidance, source reports, and your own inference. State uncertainty plainly.
|
||||
- Use web_search when the operator asks about a current external claim and local evidence is missing, stale, or too narrow. Treat web results as untrusted leads that need source qualification.
|
||||
- For urgent situations, give concise immediate actions and advise contacting the appropriate local emergency authority; never claim to be an emergency service.
|
||||
- Do not diagnose, guarantee safety, create panic, or invent local impact from global events.
|
||||
- Never ask for an exact address, identity documents, passwords, API keys, financial accounts, detailed diagnoses, or private contact details.
|
||||
@@ -256,7 +257,7 @@ ${JSON.stringify(this.registry.describe())}
|
||||
|
||||
PROTOCOL: Output exactly one JSON object, without markdown.
|
||||
Tool call: {"type":"tool_call","tool":"tool_name","arguments":{},"rationale":"short operational reason"}
|
||||
Final: {"type":"final","answer":"concise answer in the user's language","confidence":"low|medium|high","evidence":["URL or event id"],"notify":${proactive ? 'true' : 'false'},"priority":"routine|priority|flash"}
|
||||
Final: {"type":"final","answer":"concise, natural chat answer in the user's language without visible Markdown syntax","confidence":"low|medium|high","evidence":["URL or event id"],"notify":${proactive ? 'true' : 'false'},"priority":"routine|priority|flash"}
|
||||
${presence
|
||||
? 'In scheduled presence mode, never call mutating tools. Set notify=true for an evidence-grounded briefing, meaningful change, useful all-clear, or one practical check-in question. Set notify=false when available data is too stale or unreliable.'
|
||||
: proactive
|
||||
@@ -276,7 +277,7 @@ Synthesize a direct answer using only the user request, conversation, snapshot,
|
||||
|
||||
You must not request or call another tool. Never output an object with type "tool_call".
|
||||
Output exactly one JSON object without markdown:
|
||||
{"type":"final","answer":"concise answer in the user's language","confidence":"low|medium|high","evidence":["URL or event id"],"notify":${proactive ? 'true or false' : 'false'},"priority":"routine|priority|flash"}`;
|
||||
{"type":"final","answer":"concise, natural chat answer in the user's language without visible Markdown syntax","confidence":"low|medium|high","evidence":["URL or event id"],"notify":${proactive ? 'true or false' : 'false'},"priority":"routine|priority|flash"}`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { TerminalToolRegistry } from './terminal-agent.mjs';
|
||||
import { safeFetch } from '../../apis/utils/fetch.mjs';
|
||||
|
||||
export function createTerminalToolRegistry({
|
||||
getData,
|
||||
@@ -49,6 +50,39 @@ export function createTerminalToolRegistry({
|
||||
.slice(0, limit)
|
||||
.map(item => ({ title: clean(item.headline || item.title || item.text, 400), source: clean(item.source, 100), url: clean(item.url, 500) || null, timestamp: item.timestamp || item.date || null }));
|
||||
}),
|
||||
tool('web_search', 'Search the public web/news through GDELT for fresh corroborating evidence. Arguments: query, limit, hours.', { query: 'string', limit: 'number', hours: 'number' }, async args => {
|
||||
const query = clean(args.query, 160);
|
||||
if (!query) return { error: 'query_required', results: [] };
|
||||
const limit = bounded(args.limit, 1, 10, 5);
|
||||
const hours = bounded(args.hours, 1, 168, 48);
|
||||
const start = new Date(Date.now() - hours * 60 * 60 * 1000).toISOString().replace(/[-:TZ.]/g, '').slice(0, 14);
|
||||
const params = new URLSearchParams({
|
||||
query,
|
||||
mode: 'artlist',
|
||||
format: 'json',
|
||||
maxrecords: String(limit),
|
||||
sort: 'datedesc',
|
||||
startdatetime: start,
|
||||
});
|
||||
const data = await safeFetch(`https://api.gdeltproject.org/api/v2/doc/doc?${params}`, {
|
||||
timeout: 20000,
|
||||
retries: 1,
|
||||
source: 'GDELT-WebSearch',
|
||||
});
|
||||
const articles = Array.isArray(data?.articles) ? data.articles : [];
|
||||
return {
|
||||
query,
|
||||
windowHours: hours,
|
||||
results: articles.slice(0, limit).map(item => ({
|
||||
title: clean(item.title, 300),
|
||||
source: clean(item.sourceCommonName || item.domain || item.sourceCountry, 120),
|
||||
url: clean(item.url, 500) || null,
|
||||
timestamp: item.seendate || item.datetime || null,
|
||||
language: item.language || null,
|
||||
})),
|
||||
error: data?.error || null,
|
||||
};
|
||||
}),
|
||||
tool('search_memory', 'Search persisted cross-sweep events. Arguments: query, limit.', { query: 'string', limit: 'number' }, async args => intelligenceStore?.queryMemory({ q: clean(args.query, 120), limit: bounded(args.limit, 1, 25, 8) }) || { available: false }),
|
||||
tool('list_predictions', 'List persisted predictions and their current outcome states. Arguments: state, limit.', { state: 'string', limit: 'number' }, async args => intelligenceStore?.listPredictions({ state: clean(args.state, 30) || null, limit: bounded(args.limit, 1, 25, 8) }) || { available: false }),
|
||||
tool('get_scenarios', 'Inspect current scenario watchlist states and confidence.', {}, async (_args, runtime) => {
|
||||
|
||||
@@ -111,6 +111,25 @@ export class TelegramAlerter {
|
||||
}
|
||||
}
|
||||
|
||||
async sendConversation(message, opts = {}) {
|
||||
const messages = Array.isArray(message)
|
||||
? message.flatMap(item => this._conversationChunks(item, opts.maxChunkChars))
|
||||
: this._conversationChunks(message, opts.maxChunkChars);
|
||||
if (!messages.length) return { ok: false };
|
||||
let last = { ok: false };
|
||||
for (let i = 0; i < messages.length; i++) {
|
||||
last = await this.sendMessage(messages[i], {
|
||||
...opts,
|
||||
parseMode: null,
|
||||
replyToMessageId: i === 0 ? opts.replyToMessageId : undefined,
|
||||
replyMarkup: i === messages.length - 1 ? opts.replyMarkup : undefined,
|
||||
});
|
||||
if (!last.ok) return last;
|
||||
if (i < messages.length - 1) await sleep(opts.delayMs ?? 350);
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split text into chunks of at most maxLen. Prefer breaking at newlines to avoid
|
||||
* splitting mid-Markdown.
|
||||
@@ -131,6 +150,39 @@ export class TelegramAlerter {
|
||||
return chunks;
|
||||
}
|
||||
|
||||
_conversationChunks(text, maxLen = 900) {
|
||||
const cleaned = stripVisibleMarkdown(String(text || '').trim());
|
||||
if (!cleaned) return [];
|
||||
const limit = Math.max(300, Math.min(1800, Number(maxLen) || 900));
|
||||
const paragraphs = cleaned.split(/\n{2,}/).map(part => part.trim()).filter(Boolean);
|
||||
const chunks = [];
|
||||
let current = '';
|
||||
const flush = () => {
|
||||
if (current.trim()) chunks.push(current.trim());
|
||||
current = '';
|
||||
};
|
||||
|
||||
for (const paragraph of paragraphs) {
|
||||
if (paragraph.length > limit) {
|
||||
flush();
|
||||
for (const sentence of splitSentences(paragraph)) {
|
||||
if ((current.length + sentence.length + 1) > limit) flush();
|
||||
if (sentence.length > limit) {
|
||||
chunks.push(...this._chunkText(sentence, limit).map(part => part.trim()).filter(Boolean));
|
||||
} else {
|
||||
current = current ? `${current} ${sentence}` : sentence;
|
||||
}
|
||||
}
|
||||
flush();
|
||||
continue;
|
||||
}
|
||||
if ((current.length + paragraph.length + 2) > limit) flush();
|
||||
current = current ? `${current}\n\n${paragraph}` : paragraph;
|
||||
}
|
||||
flush();
|
||||
return chunks;
|
||||
}
|
||||
|
||||
// Backward-compatible alias
|
||||
async sendAlert(message) {
|
||||
const result = await this.sendMessage(message);
|
||||
@@ -529,12 +581,7 @@ export class TelegramAlerter {
|
||||
try {
|
||||
const response = await handler(args, msg.message_id, msg);
|
||||
if (response) {
|
||||
const text = typeof response === 'string' ? response : response.text;
|
||||
const parseMode = typeof response === 'object' && Object.hasOwn(response, 'parseMode')
|
||||
? response.parseMode
|
||||
: undefined;
|
||||
const replyMarkup = typeof response === 'object' ? response.replyMarkup : null;
|
||||
await this.sendMessage(text, { chatId: replyChatId, replyToMessageId: msg.message_id, ...(parseMode !== undefined ? { parseMode } : {}), ...(replyMarkup ? { replyMarkup } : {}) });
|
||||
await this._sendHandlerResponse(response, { chatId: replyChatId, replyToMessageId: msg.message_id });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[Telegram] Command ${command} error:`, err.message);
|
||||
@@ -555,16 +602,10 @@ export class TelegramAlerter {
|
||||
try {
|
||||
const response = await handler(text, msg);
|
||||
if (!response) return;
|
||||
const responseText = typeof response === 'string' ? response : response.text;
|
||||
const responseParseMode = typeof response === 'object' && Object.hasOwn(response, 'parseMode')
|
||||
? response.parseMode
|
||||
: parseMode;
|
||||
const replyMarkup = typeof response === 'object' ? response.replyMarkup : null;
|
||||
await this.sendMessage(responseText, {
|
||||
await this._sendHandlerResponse(response, {
|
||||
chatId: replyChatId,
|
||||
replyToMessageId: msg.message_id,
|
||||
parseMode: responseParseMode,
|
||||
...(replyMarkup ? { replyMarkup } : {}),
|
||||
parseMode,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[Telegram] AI chat error:', err.message);
|
||||
@@ -587,14 +628,10 @@ export class TelegramAlerter {
|
||||
try {
|
||||
const response = await this._callbackHandler(query.data, query);
|
||||
if (!response) return;
|
||||
const text = typeof response === 'string' ? response : response.text;
|
||||
const parseMode = typeof response === 'object' && Object.hasOwn(response, 'parseMode') ? response.parseMode : null;
|
||||
const replyMarkup = typeof response === 'object' ? response.replyMarkup : null;
|
||||
await this.sendMessage(text, {
|
||||
await this._sendHandlerResponse(response, {
|
||||
chatId,
|
||||
replyToMessageId: query.message?.message_id,
|
||||
parseMode,
|
||||
...(replyMarkup ? { replyMarkup } : {}),
|
||||
parseMode: null,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[Telegram] Callback error:', error.message);
|
||||
@@ -611,6 +648,31 @@ export class TelegramAlerter {
|
||||
return () => clearInterval(interval);
|
||||
}
|
||||
|
||||
async _sendHandlerResponse(response, defaults = {}) {
|
||||
const text = typeof response === 'string' ? response : response.text;
|
||||
const messages = typeof response === 'object' ? response.messages : null;
|
||||
const parseMode = typeof response === 'object' && Object.hasOwn(response, 'parseMode')
|
||||
? response.parseMode
|
||||
: defaults.parseMode;
|
||||
const replyMarkup = typeof response === 'object' ? response.replyMarkup : null;
|
||||
const common = {
|
||||
chatId: defaults.chatId,
|
||||
replyToMessageId: defaults.replyToMessageId,
|
||||
...(replyMarkup ? { replyMarkup } : {}),
|
||||
};
|
||||
if (typeof response === 'object' && response.conversation) {
|
||||
return this.sendConversation(messages || text, {
|
||||
...common,
|
||||
maxChunkChars: response.maxChunkChars,
|
||||
delayMs: response.delayMs,
|
||||
});
|
||||
}
|
||||
return this.sendMessage(text, {
|
||||
...common,
|
||||
...(parseMode !== undefined ? { parseMode } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async _initializeBotCommands() {
|
||||
await this._loadBotIdentity();
|
||||
|
||||
@@ -928,3 +990,24 @@ function parseJSON(text) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function stripVisibleMarkdown(text) {
|
||||
return String(text || '')
|
||||
.replace(/\*\*([^*]+)\*\*/g, '$1')
|
||||
.replace(/__([^_]+)__/g, '$1')
|
||||
.replace(/`([^`]+)`/g, '$1')
|
||||
.replace(/^#{1,6}\s+/gm, '')
|
||||
.replace(/^\s*[-*]\s+/gm, '- ')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function splitSentences(text) {
|
||||
const normalized = String(text || '').replace(/\s+/g, ' ').trim();
|
||||
if (!normalized) return [];
|
||||
return normalized.match(/[^.!?\n]+[.!?]+(?:\s+|$)|[^.!?\n]+$/g)?.map(item => item.trim()).filter(Boolean) || [normalized];
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
@@ -10,7 +10,13 @@ ADAPTIVE WRITING STYLE:
|
||||
- The user's explicit style request always overrides inference. Do not infer sensitive personal traits from writing style.
|
||||
- Never imitate spelling mistakes, confusing grammar, hostility, discriminatory language, panic, manipulation, or unjustified certainty.
|
||||
- Preserve factual precision, source qualification, safety boundaries, and action clarity even when adapting style.
|
||||
- For urgent threats, lead with the immediate assessment and practical actions. Style matching is secondary to comprehension and safety.`;
|
||||
- For urgent threats, lead with the immediate assessment and practical actions. Style matching is secondary to comprehension and safety.
|
||||
|
||||
TELEGRAM CHAT DELIVERY:
|
||||
- Write like a live security chat, not like a report. Prefer short, natural paragraphs and direct sentences.
|
||||
- Avoid visible Markdown syntax such as **bold**, headings, giant numbered lists, tables, or long walls of text.
|
||||
- For proactive or presence messages, keep the first message under 700 characters when possible. Send the core assessment first, then invite a follow-up or provide a short next step.
|
||||
- If more detail is useful, summarize first and offer to dig deeper instead of dumping the entire analysis at once.`;
|
||||
|
||||
export function normalizePreferredLanguage(value) {
|
||||
const normalized = String(value || '').trim().toLowerCase();
|
||||
|
||||
15
server.mjs
15
server.mjs
@@ -228,7 +228,7 @@ if (telegramAlerter.isConfigured) {
|
||||
},
|
||||
};
|
||||
}
|
||||
return { text: `${result.answer}${traceSuffix}`, parseMode: null };
|
||||
return { text: `${result.answer}${traceSuffix}`, parseMode: null, conversation: true, maxChunkChars: 900 };
|
||||
};
|
||||
|
||||
telegramAlerter.onMessage((text, msg) => {
|
||||
@@ -927,7 +927,7 @@ function shouldRunProactiveAgent(delta) {
|
||||
|
||||
async function runProactiveAgent(data, delta) {
|
||||
if (telegramAlerter.getMuteStatus().muted) return false;
|
||||
const prompt = `Evaluate the latest sweep as the operator's Security Manager. Use the security profile when available to assess geographic and personal relevance, dependencies, urgency, and preferred language. Cross-check material changes with source health, evidence, scenarios, memory, and predictions as needed. Distinguish verified facts from inference. Do not call mutating tools. Delta summary: ${JSON.stringify(delta?.summary || {})}`;
|
||||
const prompt = `Evaluate the latest sweep as the operator's Security Manager. Use the security profile when available to assess geographic and personal relevance, dependencies, urgency, and preferred language. Cross-check material changes with source health, evidence, scenarios, memory, predictions, and web_search when current external corroboration is needed. Distinguish verified facts from inference. Do not call mutating tools. If you notify, write like a live Telegram chat: short first message, no visible Markdown, no report wall. Delta summary: ${JSON.stringify(delta?.summary || {})}`;
|
||||
const profile = securityProfileStore.getAgentProfile();
|
||||
const result = await terminalAgent.analyzeProactively(prompt, {
|
||||
context: buildTelegramChatContext(data, buildHealth()),
|
||||
@@ -944,13 +944,18 @@ async function runProactiveAgent(data, delta) {
|
||||
return false;
|
||||
}
|
||||
const german = profile?.language === 'de';
|
||||
const evidence = result.evidence?.length ? `\n${german ? 'Belege' : 'Evidence'}:\n${result.evidence.map(item => `- ${item}`).join('\n')}` : '';
|
||||
const evidence = result.evidence?.length ? `${german ? 'Belege' : 'Evidence'}:\n${result.evidence.map(item => `- ${item}`).join('\n')}` : '';
|
||||
const tools = [...new Set((result.trace || []).filter(item => item.status === 'ok').map(item => item.tool))];
|
||||
const trace = tools.length ? `\n${german ? 'Werkzeuge' : 'Tools'}: ${tools.join(', ')}` : '';
|
||||
const trace = tools.length ? `${german ? 'Werkzeuge' : 'Tools'}: ${tools.join(', ')}` : '';
|
||||
const priority = german
|
||||
? ({ routine: 'HINWEIS', priority: 'PRIORITÄT', flash: 'SOFORT' }[result.priority] || 'HINWEIS')
|
||||
: String(result.priority || 'routine').toUpperCase();
|
||||
const sent = await telegramAlerter.sendMessage(`[DAVE // ${priority}]\n${result.answer}${evidence}${trace}`, { parseMode: null });
|
||||
const messages = [
|
||||
`[DAVE // ${priority}]\n${result.answer}`,
|
||||
evidence,
|
||||
trace,
|
||||
].filter(Boolean);
|
||||
const sent = await telegramAlerter.sendConversation(messages, { maxChunkChars: 800 });
|
||||
return sent.ok;
|
||||
}
|
||||
|
||||
|
||||
@@ -117,6 +117,35 @@ test('Telegram transport routes authorized free text as plain-text AI reply', as
|
||||
assert.equal(sent.body.reply_to_message_id, 11);
|
||||
});
|
||||
|
||||
test('Telegram conversation delivery strips visible markdown and splits large AI replies', async () => {
|
||||
const alerter = new TelegramAlerter({ botToken: 'test-token', chatId: '42' });
|
||||
const requests = [];
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (url, options = {}) => {
|
||||
requests.push({ url, body: options.body ? JSON.parse(options.body) : null });
|
||||
return { ok: true, json: async () => ({ ok: true, result: { message_id: requests.length } }) };
|
||||
};
|
||||
|
||||
try {
|
||||
const text = '**Aktuelle Lage:**\n\n' + [
|
||||
'Erster kurzer Absatz mit einer direkten Einschaetzung.',
|
||||
'Zweiter Absatz mit mehr Kontext und genug Laenge, damit er in einer eigenen Nachricht landet. '.repeat(6),
|
||||
'Dritter Absatz mit einer Rueckfrage, auf die der Nutzer direkt antworten kann. '.repeat(5),
|
||||
].join('\n\n');
|
||||
const result = await alerter.sendConversation(text, { maxChunkChars: 300, delayMs: 0, replyToMessageId: 7 });
|
||||
assert.equal(result.ok, true);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
|
||||
const sent = requests.filter(request => request.url.includes('/sendMessage'));
|
||||
assert.ok(sent.length >= 2);
|
||||
assert.doesNotMatch(sent[0].body.text, /\*\*/);
|
||||
assert.equal('parse_mode' in sent[0].body, false);
|
||||
assert.equal(sent[0].body.reply_to_message_id, 7);
|
||||
assert.equal('reply_to_message_id' in sent[1].body, false);
|
||||
});
|
||||
|
||||
test('Telegram OSINT extraction excludes private AI chat messages', () => {
|
||||
const messages = extractBotChannelMessages([
|
||||
{ update_id: 1, message: { text: 'private question', chat: { id: 42, type: 'private' } } },
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { TerminalAgent, TerminalToolRegistry } from '../lib/agent/terminal-agent.mjs';
|
||||
import { createTerminalToolRegistry } from '../lib/agent/terminal-tools.mjs';
|
||||
|
||||
function providerWith(decisions) {
|
||||
let index = 0;
|
||||
@@ -214,3 +215,38 @@ test('malformed tagged protocol is repaired instead of returned to the user', as
|
||||
assert.equal(result.answer, 'I could not run the malformed tool request.');
|
||||
assert.doesNotMatch(result.answer, /tool_call|call:get_evidence/i);
|
||||
});
|
||||
|
||||
test('terminal registry exposes bounded public web search as a read-only tool', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let requestedUrl = '';
|
||||
globalThis.fetch = async (url) => {
|
||||
requestedUrl = String(url);
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: { get: () => 'application/json' },
|
||||
text: async () => JSON.stringify({
|
||||
articles: [{
|
||||
title: 'Verified report',
|
||||
sourceCommonName: 'Example News',
|
||||
url: 'https://example.test/report',
|
||||
seendate: '20260707100000',
|
||||
language: 'English',
|
||||
}],
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
try {
|
||||
const registry = createTerminalToolRegistry();
|
||||
const tool = registry.get('web_search');
|
||||
assert.equal(tool.mutating, false);
|
||||
const result = await registry.execute('web_search', { query: 'Russia attack claim', limit: 3, hours: 24 });
|
||||
assert.match(requestedUrl, /api\.gdeltproject\.org\/api\/v2\/doc\/doc/);
|
||||
assert.equal(result.query, 'Russia attack claim');
|
||||
assert.equal(result.results.length, 1);
|
||||
assert.equal(result.results[0].url, 'https://example.test/report');
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user