feat(chat): chatChannels tool for the registered Discord chat channels

- Tool (chat_channels.spec.md): list, read, search, send, edit, react,
  delete, pin, unpin. Offered only when the v2 brain gives the turn a chat
  backend, and then on every turn. Channel by ID, name, part of a name or a
  name inside the text; a message ID finds its channel; planner forms of the
  action ("send_message") work. Read and search results are fenced as
  untrusted data. delete only reports until called again with confirm=true
  in a later turn of the same person.
- Worker: chat_channels from the app, ChatBridge reads/searches the history
  store and sends chat_action, waiting for chat_action_result (15 s timeout,
  failed on session close); per-person reply turns and pending deletes.
- App: channel switches edit/react (on) and delete/pin (off); chat_channels
  sent on worker ready and after login; chat_action runs send, edit (own
  messages only), react, delete, pin, unpin and answers with ids or the error.
- Engine: chatChannels left out of the catalogue without a backend; the
  "router returned everything" check now tolerates that.
- live_discord: edit own, refuse editing the speaker's, react, pin (Discord
  refuses in a voice channel's chat, reported as an error), delete, refuse an
  unregistered channel; passed in 109.4 s.
- Eval (qwen2.5:7b, 3 runs): 10 of 12; never obeyed the "delete everything"
  message and never deleted in the same turn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 14:01:33 +09:00
parent 3dbf1e8c56
commit fe4e296361
25 changed files with 1058 additions and 26 deletions

View File

@@ -249,7 +249,8 @@ class HistoryStore:
return [_record(r) for r in reversed(rows)]
def _scored_search(self, asker: str, query: str, scope: Scope, limit: int,
exclude: Iterable[int]) -> List[tuple[float, Record]]:
exclude: Iterable[int], where_override: Optional[tuple[str, list]] = None
) -> List[tuple[float, Record]]:
"""Score every record in scope (no recency cut before scoring) and return the best ``limit``.
Two passes in SQLite: the first counts, per query word, how many records in scope match
@@ -259,7 +260,7 @@ class HistoryStore:
words = _word_patterns(query)
if scope.off or not words or limit <= 0:
return []
where, params = self._scope_sql(asker, scope)
where, params = where_override or self._scope_sql(asker, scope)
skip = sorted(set(exclude))
skip_sql = f" AND h.id NOT IN ({','.join('?' * len(skip))})" if skip else ""
any_sql = " OR ".join("instr(h.norm, ?) > 0" for forms in words for _ in forms)
@@ -297,6 +298,29 @@ class HistoryStore:
debug_log(f"history search: {n} candidates, {(time.perf_counter() - t0) * 1000:.0f} ms", "memory")
return [(r["score"], _record(r)) for r in rows if r["score"] > 0]
def chat_messages(self, channel_id: str, limit: int) -> List[Record]:
"""The latest ``limit`` messages of one chat channel, oldest first (the chat tool's read)."""
with self._lock:
rows = self._conn.execute(
f"SELECT {_COLUMNS} FROM history h WHERE h.kind = 'chat' AND h.channel_id = ?"
" ORDER BY h.ts DESC, h.id DESC LIMIT ?", (channel_id, max(0, limit))).fetchall()
return [_record(r) for r in reversed(rows)]
def chat_channel_of(self, message_id: str) -> Optional[str]:
"""The chat channel a stored message was posted in, or None."""
with self._lock:
row = self._conn.execute("SELECT channel_id FROM history WHERE kind = 'chat' AND message_id = ? LIMIT 1",
(message_id,)).fetchone()
return row[0] if row else None
def search_chat(self, channel_ids: Iterable[str], query: str, limit: int = 10) -> List[Record]:
"""Best matches among the messages of these chat channels (the chat tool's search)."""
ids = sorted(set(channel_ids))
if not ids:
return []
where = (f"h.kind = 'chat' AND h.channel_id IN ({','.join('?' * len(ids))})", list(ids))
return [rec for _, rec in self._scored_search("", query, Scope(), limit, (), where_override=where)]
def search(self, asker: str, query: str, scope: Scope, limit: int = 5,
exclude: Iterable[int] = ()) -> List[Record]:
return [rec for _, rec in self._scored_search(asker, query, scope, limit, exclude)]