* feat(i18n): layered catalogs — plugin packs and user overlay over bundled locales
* feat(tui): i18n layer — en catalog, nanostore runtime, RPC pack loader, _keys.tui.json emitter
ui-tui/src/i18n/: en.ts (facade over topical siblings under en/), types.ts
(Translations + dotted TranslationKey derived from en), runtime.ts ($locale/
$catalog atoms, translateFrom active→en→key, pack merge with string→fn
wrapping for {0}/{1} placeholders), loader.ts (display.language →
i18n.catalog {lang, surface:'tui'}, English when the method is missing),
useT()/useLocale() hooks, t() for non-React code. useConfigSync feeds the
loader from the existing config.get full hydration. `npm run i18n:keys`
writes locales/_keys.tui.json (sorted flat key list) and runs before build.
* feat(plugins): provides_locales manifest field, ctx.register_locale/register_locale_dir, manifest-only language packs
* chore(tui): split en catalog siblings by lane (slash sibling)
* feat(plugins): validate language packs — parse, text-only, key-subset WARN against en / _keys exports
* feat(tui_gateway): i18n.languages / i18n.catalog RPC + regenerated contracts
* feat(config): display.language accepts any supported_languages() id, refuses unknown ids with the list
* docs(i18n): language packs user guide, pluggable display.language, plugin developer section, AGENTS notes
* feat(plugins): report language-pack layers in the mid-run activation summary
* feat(tui): wire status bar, composer placeholders, hotkey help and approval/clarify/confirm prompts through i18n
StatusRule maps compared state values (ready/running…/summoning) to catalog
text at render via displayStatus(); hotkeys()/placeholder() resolve lazily so
a pack that arrives after boot applies. Catalog grows to 81 keys.
* feat(desktop): pluggable app locales — registry, host.i18n.registerAppLocale, backend packs, keys emitter
- Locale widens to string (BundledLocale keeps the union); TRANSLATIONS stays
the bundled record and every consumer resolves through the registry.
- src/i18n/registry.ts: registerAppLocale(id, {endonym, rtl, translations})
layers partial packs (nested or flat dotted) over bundled/en via
mergeTranslations; a string over a function-valued en entry becomes a
positional {0}/{1} formatter; $appLocaleVersion bumps so translators
re-render; per-source disposers + replaceAppLocaleSource for atomic swaps.
- Backend packs: i18n.languages + i18n.catalog {surface:'desktop'} feed the
registry as source 'backend' (method-not-found is silent); re-synced on
socket open, display.language change and profile switch. A saved pack-only
language is promoted once its pack registers.
- SDK: host.i18n.registerAppLocale / languageOptions; ctx.i18n.registerAppLocale
tracked for unload. Docs in the desktop plugin SDK guide + skill reference.
- Language switcher lists bundled ∪ registered ∪ backend, endonym-only; RTL
from the registry (applyDocumentLocale takes rtl).
- npm run i18n:keys emits locales/_keys.desktop.json (wired into build).
* i18n(cli): route /topup + /subscription copy through t() (cli.billing.*, cli.subscription.*)
Module-level copy tables and modal choice tuples in cli_billing_mixin.py froze
English at import, before display.language was known. They are now key tables /
builder functions evaluated at call time; every user-facing line in the /usage
balance block, /subscription and the five /topup screens reads the catalog.
Choice VALUES stay English identifiers. Fragment-assembled status lines
(Plan: … → cancels · $x left · renews …) become full templates.
* i18n(gateway): exec-approval card contract + base/run/run_busy/run_inbound replies through t()
- base_exec_approval: EA_* English constants stay; add ea_header_text()/ea_reason_label_text()/
ea_smart_deny_line_text()/ea_default_reason_text()/ea_action_labels()/approval_timed_out_notice()
accessors; deadline + timed-out notice resolve via gateway.exec_approval.*
- BasePlatformAdapter._EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/_EA_ACTION_LABELS become
properties (adapters still shadow them with markup class attrs)
- run.py: provider error replies table holds catalog keys; _CONTEXT_OVERFLOW_REPLY -> _context_overflow_reply()
- run_busy/run_inbound: typed approval + slash-confirm matchers accept English ∪ approval.inputs.* (t())
- locales/en.yaml: gateway.exec_approval/busy/errors/... namespaces
* i18n(cli): wire modal, loops, agent-setup mixins through t() (cli.* keys)
* i18n(platforms): route Slack, Matrix and Feishu user-facing text through t()
Exec-approval markup overrides (_EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/
_EA_ACTION_LABELS) become per-call properties over the shared
gateway.exec_approval.* contract keys, so Slack's 3000-char section budget
measures the resolved template. Slack _APPROVAL_DECISIONS/_CONFIRM_DECISIONS,
Feishu _APPROVAL_LABEL_MAP and Matrix _EA_LEGEND/_EA_TYPED_HINT turn into
key tables resolved at click time; the Matrix typed hints become whole
sentences per offered tier instead of spliced fragments. Slack button labels
are cut to 75 chars and select placeholders to 150 after translation; the
model-facing clarify fallback answer ('choice N') stays English while the
card copy localizes.
locales/en.yaml gains the gateway.exec_approval.* contract keys plus the
platform.shared.* / platform.slack.* / platform.matrix.* / platform.feishu.*
namespaces (and the keys for the other adapters wired in follow-up commits).
* i18n(gateway): run_turn / run_turn_runner / approval-settle copy through t()
- status hints, proxy errors, background task notices, progress heartbeats, session info lines
- tool progress chrome (tool_head/tool_pending/tool_preview/tool_verbose) shared by base.format_tool_event
- run_turn_runner:1406 Chinese clarify placeholder -> gateway.clarify.native_stream_placeholder (zh text kept in zh.yaml)
- _UNEXPECTED_SILENCE_REPLY/_CLARIFY_EXPIRED_NOTICE -> accessor functions
* i18n(platforms): route Google Chat and Teams user-facing text through t()
Google Chat clarify card, typing placeholder, orphan-card labels and the whole
/setup-files reply set (module constants become platform.google_chat.setup_files.*
keys resolved at reply time). The attachment-fallback notice that shipped
hardcoded in Spanish is keyed with an English en value; es.yaml carries the
original Spanish text for those four keys.
Teams approval card header/reason use the gateway.exec_approval.* contract,
_APPROVAL_LABELS becomes a key table resolved at click time, and the meeting
summary writer resolves its section headings/fallbacks per render.
* i18n(platforms): route LINE, WeCom, email, DingTalk, IRC and Home Assistant text through t()
LINE default copy constants become catalog keys resolved in __init__ (the
LINE_*_TEXT / extra.* operator overrides still win); the busy-ack bypass
matcher keys on the leading emoji marker only, so it keeps firing once the
gateway busy heads are localized. WeCom media size/format notices that shipped
hardcoded in Chinese are keyed with English en values and zh.yaml carries the
original Chinese text. DingTalk emotion bubbles resolve per send.
* i18n(cli): route /model switch output and -q status lines through t() (cli.model.*, cli.single_query.*)
Switch-summary labels shared with the gateway reuse gateway.model.* keys
(provider/context/max-output/capabilities/prompt-caching); CLI-only variants
(glyph or no-backtick forms) live under cli.model.*. The hand-padded /model usage
block becomes a (form, description-key) table padded at render time so the
command syntax stays fixed while descriptions translate. -q 'Error:' reuses
gateway.model.error_prefix.
* i18n(cli): route TUI panel/hint/placeholder copy through t() (cli.tui.*)
_APPROVAL_CHOICE_LABELS and _TUI_MODAL_HINTS become key tables resolved at
render time; vault/sudo panel bodies are one catalog value per panel split on
newline; inline plurals use <key>_one/<key>_other. Adds the cli.* namespace
(shared/tui/voice/render/subagents/dock) to locales/en.yaml.
* i18n(cli): voice/wake-word CLI copy through t() (cli.voice.*)
RuntimeError texts raised in _voice_start_recording are human copy (callers
print {e}) and are keyed; the Termux requirement-check match stays English.
Wake state ids stay internal, only their labels localize.
* i18n(cli): live-work dock, subagent monitor and render copy through t()
cli.subagents.* / cli.dock.* / cli.render.*; count fragments pluralize via
_one/_other keys, verdict table holds keys resolved at paint time so width
clipping measures the translated text.
* i18n(gateway): unauthorized/pairing, voice, topics, shutdown, startup, notifications, kanban pings through t()
* i18n(cli): move tips + composer placeholders into the catalog (tips.tNNN / tips.placeholder.pNN)
get_random_tip()/get_random_composer_placeholder() pick a key from the English catalog
(the parity baseline, probed once per process) and resolve it through t() for the active
language, so language packs translate tips like any other string. Also lands the cli.*
en.yaml namespace consumed by the CLI info/help/error-copy wiring in the next commit.
* i18n(cli): wire chat-turn + session mixins through t(); kanban log trimmer matches t() output
* test(cli): assert TUI/dock/voice copy via t(key); prove labels resolve at render time
Pinned-English assertions in the approval-UI, live-work dock and voice tests now
go through the catalog. New test swaps the catalog after import and checks the
approval panel + hint row follow it (the reason _APPROVAL_CHOICE_LABELS and
_TUI_MODAL_HINTS became key tables).
* i18n(cli): route CLI info/help/error copy through t() (cli.* namespace)
cli_info_mixin: /help consumes CommandDef.describe() (added to commands.py: slash.<name>.description
with fallback to .description), section titles/skill/quick-command headers, /tools, /toolsets,
/usage labels, /context, /whoami, /insights, /gateway status, tool-progress labels, bang-shell
denials, MCP config-watch + /reload-mcp confirm/reload lines, /reload-skills, and the session-store
warning all read the catalog at call time (module-level label tables became functions so the
active language is honoured after startup). cli.py: worktree cleanup, tirith warning, show_config
(labels re-padded at print time), quick/plugin/skill slash-command errors, ambiguous-command hint,
stdin error, gateway start, profile warning. cli_chat_error_copy / cli_unknown_command /
cli_output / cli_init_mixin: chat error panel copy, did-you-mean lines, n-more / yes-no prompt
(localized affirmative initial alongside 'y'), unknown-toolsets warning.
* i18n(w1a): wire agent display/explainers/approval + slash registry/help through t()
- hermes_cli/commands.py: CommandDef.describe() resolves slash.<name>.description
at call time; category labels via slash.category.*; help/alias/usage suffixes
via slash.shared.*; gateway_help_lines and commands_platforms/slash_exec use them.
- agent/display.py: display.verb.* resolved at call time via get_tool_verb();
bridge/spinner/thinking-verb/cute-row/failure/preview/diff text via display.*.
- agent/turn_explainers.py: exit-reason / persistence-cause tables become call-time
lookups (explainer.exit.*, explainer.persistence.*, explainer.file_mutation.*).
- agent/background_review.py, session_activity.py, context_breakdown.py,
status_output.py: review summaries, iteration progress, context notices.
- tools/approval.py, approval_context.py: approval.summary.*, approval.noun.*,
approval.window.* pluralized keys.
- gateway/slash_commands*.py: remaining raw strings (busy, whoami, platform,
bundles, memory, skills, approvals, set_home, diff, update, debug, profile,
heartbeat, refine, review, subgoal, loop, retry, compress codex path, save,
sessions, model guard/errors, agents rows, topup, login). HISTORY_UNREADABLE
keeps its English constant; callers use history_unreadable() ->
gateway.shared.history_unreadable.
- locales/en.yaml: new approval/display/explainer/slash blocks + gateway leftovers.
* i18n(telegram): route adapter chat copy through t()
Approval card (header/reason/smart-deny as HTML-escaped properties), inline
button labels, callback toasts (cut at Telegram's 200-char cap), model/choice
pickers, clarify/update/slash-confirm prompts, gmail-triage labels and the
inbound-media failure notice now come from the catalog. _UNAUTHORIZED is a
lazy _unauthorized() so the import no longer binds a language. The command
menu carries a language+payload fingerprint (forum scopes re-register on
change) and BotCommand descriptions are cut at 256.
Adds gateway.exec_approval.* (WAVE2 contract), platform.telegram.*,
platform.discord.* and the slash.*.description keys the Discord table shares
with the CLI registry to locales/en.yaml.
* i18n(gateway/platforms): whatsapp_cloud, yuanbao, weixin, signal, api_server copy through t()
- whatsapp_cloud: clarify list/buttons, approve/deny + slash-confirm labels via platform.whatsapp.* (t()-then-truncate at 20/24/72 caps); _EA_HEADER becomes a property wrapping ea_header_text()
- yuanbao: SLOW_RESPONSE_MESSAGE -> slow_response_message() (platform.yuanbao.slow_response_notice; zh keeps the original text); cron-wrapper markers centralized as module constants for strip_cron_wrapper
- api_server: PROVIDER_AUTH_FAILED_LABEL/PROVIDER_RATE_LIMITED_LABEL stay English for run.py matchers; user_text() renders via t()
- signal/_format_wait, weixin voice caption, openai_routes transformed notice
- run_turn: second _UNEXPECTED_SILENCE_REPLY consumer -> accessor
* i18n(discord): route adapter chat copy through t()
Native slash-command table becomes _NATIVE_SLASH_COMMAND_SPECS holding catalog
keys; _native_slash_commands() resolves descriptions, parameter descriptions
and Choice names for the active language, each cut at Discord's 100-char cap,
and the app-command sync fingerprint now includes get_language() so a
display.language change re-syncs. Exec-approval card (gateway.exec_approval.*
contract), slash-confirm / clarify / update views, model+choice pickers,
thread creation, forum titles, voice acks, the response-truncation notice,
the unauthorized-slash security alert and the media upload-size notices all
read from platform.discord.*. Decorator-declared button labels are relabelled
in __init__ (80-char cap); embed titles cut at 256, select placeholders at
150, option label/description at 100. _UNAUTHORIZED is a lazy _unauthorized().
* i18n(cli): wire status-bar, stream, terminal mixins + terminal_input through t(); rename kwargs that shadow t(key)
* i18n: wire hermes_cli/cli_commands_mixin.py slash-command copy through t()
- 431 new leaves under cli.commands.<cmd>.* in locales/en.yaml; 12 rows reuse
existing gateway.* keys (rollback, diff, resume, branch, btw, model, reasoning)
via a _gt() helper so CLI and gateway replies stay identical.
- Module-level English tables (_BUSY_MODE_*, _REASONING_TOGGLES, _HATCH_PROGRESS,
_DIFF_LABELS, _LOCAL_ENGINE_LINES) become call-time catalog lookups keyed by id.
- Verb tables (Enabling/Disabling, Paused/Resumed/Triggered, planned/done,
Updating/Generating) are one full template per variant; plurals use
<key>_one/<key>_other via _tn(); hand-padded column labels (/snapshot list)
translate the value and re-pad at the call site.
- Multi-line usage blocks are single catalog values split with _lines().
- Model-facing system notes and DB-stored reasons stay English (EXCLUDED).
* tests: assert /handoff, /worktree, /login CLI copy via t(key) instead of pinned English
* test(i18n): pin Telegram/Discord adapter catalog wiring
Lazy unauthorized notice, exec-approval contract keys, HTML escaping before
Telegram <b> wrapping, 200-char toast / 256-char BotCommand caps, Discord
100-char app-command text and 80-char button caps, and language-bearing
command-menu fingerprints on both platforms.
* i18n: reconcile cli.shared on/off vs enabled/disabled after lane merge
* i18n: describe() in TUI-gateway slash listings; localize TUI exit resume hint
* i18n(tr): translate bundled catalog + tui pack
* i18n(ja): translate bundled catalog + tui pack
* i18n(ko): translate bundled catalog + tui pack
* i18n(zh): translate bundled catalog + tui pack
* i18n(fr): translate bundled catalog + tui pack
* i18n(af): translate bundled catalog + tui pack
* i18n(uk): translate bundled catalog + tui pack
* i18n(ar): translate bundled catalog + tui pack
* i18n(pt): translate bundled catalog + tui pack
* i18n(it): translate bundled catalog + tui pack
* i18n(es): translate bundled catalog + tui pack
* i18n(zh-hant): translate bundled catalog + tui pack
* i18n(ru): translate bundled catalog + tui pack
* i18n(hu): translate bundled catalog + tui pack
* i18n(hu): translate pre-existing English-valued leftovers (kanban wake, /context, /status, fast labels)
* i18n(de): translate bundled catalog + tui pack
* i18n(ga): translate bundled catalog + tui pack
* test(i18n): fixture matches _normalize_lang(lang, home) signature
* i18n(tui): scaffold userMessages/slashCmd en siblings
* i18n(tui): wire secure prompts + content tables
* feat(tui): i18n — wire billing, subscription, connection-setup and journey overlays
Adds en siblings billing.ts / subscription.ts / connection.ts (namespaces
billing, subscription, connection, journey) and routes every user-facing
literal in billingOverlay, subscriptionOverlay, connectionSetupOverlay and
journey through useT()/messages(). Module-level label tables became lazy
(scopeStillDeniedResult(), verbOf(T, action)); auto-reload rows dispatch on
stable ids instead of label text. Regenerates locales/_keys.tui.json.
* i18n(tui): wire slash ops/wake replies
* i18n(tui): wire pickers (modelPicker, activeSessionSwitcher, petPicker)
* i18n(tui): wire slash core/debug/setup replies
* i18n(tui): wire hubs (agents overlay/panel/controls, skills, plugins)
* i18n(tui): wire slash session/topup/subscription replies
* i18n(tui): wire chat bits (branding, thinking, messageLine, loaders, todo, queued, banner, entry)
* i18n(tui): register t3 siblings (pickers, hubs, secure, content, chatBits) and regenerate keys
* i18n(tui): wire userMessages copy through the userMessages namespace
* i18n(tui): lazy-copy test for userMessages, regenerate _keys.tui.json
* i18n(tui): wire session/gateway/lib text through the TUI catalog (lane t2)
Adds en siblings session.ts, gatewayMsg.ts, libText.ts (namespaces session,
gatewayMsg, libText) and routes user-facing literals in app/{useMainApp,
useSessionLifecycle,useInputHandlers,turnController,createServerRequestHandler,
setupHandoff,createGatewayEventHandler}.ts, gatewayClient displayed reasons,
lib/*, domain/*, hooks/* through t()/messages(). Status-bar state values that
code compares against, backend-matched strings, log lines, model-bound text,
and machine 'error:' prefixes stay literal. Regenerates locales/_keys.tui.json
(232 keys).
* i18n: serve bundled locales/<lang>.tui.yaml under overlay/packs; TUI pack parity test; regen _keys.tui.json (1250)
* i18n: translate pre-existing English stubs in bundled locales (424 leaves, 14 locales)
* tui: i18n-export-en script (English templates for pack translators)
* docs(i18n): bundled TUI packs are the bottom layer of the tui surface
* i18n(ru): translate TUI pack
* i18n(ar): translate TUI pack
* i18n(es): translate TUI pack
* i18n(pt): translate TUI pack
* i18n(ko): translate TUI pack
* i18n(de): translate TUI pack
* i18n(ja): translate TUI pack
* i18n(fr): translate TUI pack
* i18n(tr): translate TUI pack
* i18n(it): translate TUI pack
* i18n(zh): translate TUI pack
* i18n(zh-hant): translate TUI pack
* i18n(hu): translate TUI pack
* i18n(uk): translate TUI pack
1,169 missing keys translated; 81 pre-existing kept byte-identical. Parity OK missing=0 extra=0 placeholder_mismatch=0 empty=0.
Deliberately identical to en: chatBits.branding.mcpSummary ({0} MCP), chatBits.thinking.agentsHint ((/agents)), session.main.voiceStt (◉ STT), session.main.voiceTtsSuffix ( [tts]), slashCmd.core.help.tuiSection (TUI), slashCmd.core.history.hermesTag (Hermes #{0}), slashCmd.debug.heapdump.heapPath (heapdump: {0}), slashCmd.debug.mem.rss (rss), subscription.stepUp.title (Remote Spending — product feature name, as in core catalog), content.faces.* (glyph-only kaomoji).
* i18n(ga): translate TUI pack
* i18n(af): translate TUI pack
* plugin_guard: locale catalogs in language packs step down the agent-config family
A translated status line such as "Updating AGENTS.md" in locales/<lang>.yaml is UI text the loader
reads as a string leaf; it cannot edit a file. The bundled en.yaml itself tripped agent_config_mod
at critical, making any faithful language pack uninstallable. Injection shapes keep full severity.
* plugin_validate_locales: read key exports with utf-8-sig (Windows footgun lint)
* i18n(relay): route relay adapter prompt copy through t(); drop dead import-bound approval header
Adds platform.relay.* (5 keys) to en and all 16 bundled locales, reusing the sibling platform
translations for the confirm buttons and the Other option.
* ci: fix TUI import order, MDX table pipe, main's overflow-warning wording in all locales; fresh-install fixture carries the i18n kernel
- ui-tui/src/i18n/en.ts: perfectionist/sort-imports (slash before slashCmd)
- docs plugins/index.md: escape the | inside the provides_locales table cell (MDX parsed <id> as JSX)
- display.notice.uncompressed_context_overflow: adopt main's wording (names compression.enabled: false
and /compact) in en + 16 locales; the guardrail test pins that phrase
- tests/scripts/test_fresh_source_install.py: the installer tail now resolves CLI text through
agent.i18n, so the fixture tree carries the i18n kernel + en.yaml (not the agent runtime)
* docs(desktop-plugin-sdk): double-backtick the template-literal example (MDX evaluated ${n})
* test(e2e): display.language is validated against the live language set; exclude it from the arbitrary-string set property
* commands: keep the localized COMMANDS/COMMANDS_BY_CATEGORY module __getattr__ after the compat block removal
* build: never write locales/_keys.*.json from the desktop/TUI builds; regenerate the committed desktop key export
The desktop build regenerated locales/_keys.desktop.json in the checkout, so a
hermes update that rebuilt the app left the tree dirty (Desktop update E2E:
'M locales/_keys.desktop.json'). The key exports are committed artifacts pinned
to en.ts by apps/desktop/scripts/i18n-keys.test.mjs and ui-tui i18n:keys:check;
builds read them, never write them. Regenerated after main's new desktop strings.
* test: unbreak two main-red timing tests the PR merge-ref inherits
- test_local_runtime racing fake publishes the modern state record (legacy pid-only
records are rejected since 65ff3ad353; main has been red on this test since)
- test_run_progress_topics ManyProgressLinesAgent waits for the first bubble instead of
a fixed 0.35s, which a loaded CI runner does not always meet
* chore(i18n): regenerate desktop key catalog for main's new strings (model pricing, copy changelog)
* test(e2e): torture-chamber fd monitor confirms a deleted sidecar is still held before calling it a leak
SQLite's WAL last-close unlinks -shm before closing its descriptor (unixShmUnmap, then
unixShmPurge), so a healthy close shows a (deleted) -shm for microseconds; the 20ms poll
occasionally caught that window on the short-lived opener and failed the episode.
* chore(i18n): regenerate desktop key catalog for main's telemetry/consent strings
* chore(i18n): regenerate desktop key catalog after main sync
---------
Co-authored-by: Teknium <teknium@nousresearch.com>
1248 lines
54 KiB
Python
1248 lines
54 KiB
Python
"""CLI presentation -- spinner, kawaii faces, tool preview formatting.
|
||
|
||
Pure display functions with no AIAgent dependency; used for CLI feedback.
|
||
"""
|
||
|
||
import logging
|
||
import os
|
||
import re
|
||
import sys
|
||
import threading
|
||
import time
|
||
from dataclasses import dataclass, field, replace
|
||
from difflib import unified_diff
|
||
from pathlib import Path
|
||
from typing import Any, Iterator
|
||
from urllib.parse import urlsplit
|
||
|
||
from utils import safe_json_loads
|
||
from agent.i18n import t
|
||
from agent.redact import redact_sensitive_text
|
||
from agent.tool_result_classification import file_mutation_result_landed, is_guardrail_refusal
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
_ANSI_RESET = "\033[0m"
|
||
_MAX_INLINE_DIFF_FILES = 6
|
||
_MAX_INLINE_DIFF_LINES = 80
|
||
|
||
|
||
def _display_url(value: Any) -> str:
|
||
"""Extract a display-only URL without assuming model argument types."""
|
||
value = (value.get("url") or value.get("href")) if isinstance(value, dict) else value
|
||
return value.strip() if isinstance(value, str) else ""
|
||
|
||
|
||
def _http_url(candidate: str) -> str | None:
|
||
"""``candidate`` when it parses as an absolute http(s) URL, else None."""
|
||
try:
|
||
parsed = urlsplit(candidate)
|
||
except ValueError:
|
||
return None
|
||
return candidate if parsed.scheme.lower() in {"http", "https"} and parsed.netloc else None
|
||
|
||
|
||
def _hex_rgb(h: str) -> tuple[int, int, int]:
|
||
return int(h[1:3], 16), int(h[3:5], 16), int(h[5:7], 16)
|
||
|
||
|
||
def _get_skin():
|
||
"""Active skin config, or None when unavailable (lazy import avoids cycles)."""
|
||
try:
|
||
from hermes_cli.skin_engine import get_active_skin
|
||
return get_active_skin()
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
# Diff colors resolve lazily from the skin engine (light/dark aware) and are
|
||
# cached after the first resolution.
|
||
_diff_colors_cached: dict[str, str] | None = None
|
||
|
||
|
||
# Foreground diff colors: key -> (skin color key, dark-terminal fallback RGB).
|
||
_DIFF_FG = {
|
||
"dim": ("banner_dim", (150, 150, 150)), "file": ("session_label", (180, 160, 255)),
|
||
"hunk": ("session_border", (120, 120, 140)),
|
||
}
|
||
# Background diff colors (white text on a dark tint of the skin's ui_error/ui_ok):
|
||
# key -> (skin key, default hex, dominant channel index, dark-terminal fallback).
|
||
_DIFF_BG = {
|
||
"minus": ("ui_error", "#ef5350", 0, "\033[38;2;255;255;255;48;2;120;20;20m"),
|
||
"plus": ("ui_ok", "#4caf50", 1, "\033[38;2;255;255;255;48;2;20;90;20m"),
|
||
}
|
||
|
||
|
||
def _fg(r: int, g: int, b: int) -> str:
|
||
return f"\033[38;2;{r};{g};{b}m"
|
||
|
||
|
||
def _tinted_bg(rgb: tuple[int, int, int], dominant: int) -> str:
|
||
r, g, b = (max(v // 2, 20) if i == dominant else max(v // 4, 10) for i, v in enumerate(rgb))
|
||
return f"\033[38;2;255;255;255;48;2;{r};{g};{b}m"
|
||
|
||
|
||
def _diff_ansi() -> dict[str, str]:
|
||
"""Return ANSI escapes for diff display, resolved from the active skin."""
|
||
global _diff_colors_cached
|
||
if _diff_colors_cached is not None:
|
||
return _diff_colors_cached
|
||
colors = {k: _fg(*rgb) for k, (_, rgb) in _DIFF_FG.items()} | {k: v[3] for k, v in _DIFF_BG.items()}
|
||
try:
|
||
skin = _get_skin()
|
||
for key, (skin_key, fallback) in _DIFF_FG.items():
|
||
h = skin.get_color(skin_key, "")
|
||
colors[key] = _fg(*(_hex_rgb(h) if h and len(h) == 7 and h[0] == "#" else fallback))
|
||
bg_hex = {key: skin.get_color(skin_key, default) for key, (skin_key, default, _, _) in _DIFF_BG.items()}
|
||
for key, (_, _, dominant, _) in _DIFF_BG.items():
|
||
h = bg_hex[key]
|
||
if h and len(h) == 7:
|
||
colors[key] = _tinted_bg(_hex_rgb(h), dominant)
|
||
except Exception:
|
||
pass
|
||
_diff_colors_cached = colors
|
||
return colors
|
||
|
||
|
||
@dataclass
|
||
class LocalEditSnapshot:
|
||
"""Pre-tool filesystem snapshot used to render diffs locally after writes."""
|
||
paths: list[Path] = field(default_factory=list)
|
||
before: dict[str, str | None] = field(default_factory=dict)
|
||
|
||
|
||
# Configurable tool preview length; set once at startup from display.tool_preview_length.
|
||
_tool_preview_max_len: int = 0 # 0 = unlimited
|
||
_friendly_tool_labels: bool = True
|
||
|
||
|
||
def set_tool_preview_max_len(n: int) -> None:
|
||
"""Set the global max length for tool call previews. 0 = no limit."""
|
||
global _tool_preview_max_len
|
||
_tool_preview_max_len = max(int(n), 0) if n else 0
|
||
|
||
|
||
def get_tool_preview_max_len() -> int:
|
||
"""Return the configured max preview length (0 = unlimited)."""
|
||
return _tool_preview_max_len
|
||
|
||
|
||
def set_friendly_tool_labels(enabled: bool) -> None:
|
||
"""Toggle friendly human-phrased tool labels (display.friendly_tool_labels)."""
|
||
global _friendly_tool_labels
|
||
_friendly_tool_labels = bool(enabled)
|
||
|
||
|
||
def get_skin_tool_prefix() -> str:
|
||
"""Get tool output prefix character from active skin."""
|
||
skin = _get_skin()
|
||
return skin.tool_prefix if skin else "┊"
|
||
|
||
|
||
def get_tool_emoji(tool_name: str, default: str = "⚡") -> str:
|
||
"""Display emoji for a tool: skin ``tool_emojis`` override, then registry, then *default*."""
|
||
skin = _get_skin()
|
||
override = skin.tool_emojis.get(tool_name) if skin and skin.tool_emojis else None
|
||
if override:
|
||
return override
|
||
try:
|
||
from tools.registry import registry
|
||
return registry.get_emoji(tool_name, default="") or default
|
||
except Exception:
|
||
return default
|
||
|
||
|
||
# ── Tool preview (one-line summary of a tool call's primary argument) ─────
|
||
|
||
def _oneline(text: str) -> str:
|
||
"""Collapse whitespace (including newlines) to single spaces."""
|
||
return " ".join(text.split())
|
||
|
||
|
||
def _tail_trunc(text: str, limit: int | None) -> str:
|
||
"""Tail-truncate to ``limit`` chars with ``...`` (0/None = unlimited). The result never
|
||
exceeds ``limit``: for 1-3 the ellipsis itself is clipped (``text[:limit - 3]`` would go
|
||
negative and hand back almost the whole string, #9439)."""
|
||
if not limit or limit <= 0 or len(text) <= limit:
|
||
return text
|
||
return "." * limit if limit <= 3 else text[:limit - 3] + "..."
|
||
|
||
|
||
def _clip(text: str, n: int) -> str:
|
||
"""``text[:n]`` plus ``...`` when longer (used inside quoted previews)."""
|
||
return f"{text[:n]}{'...' if len(text) > n else ''}"
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class ToolPreview:
|
||
"""A compact tool preview plus presentation facts lost to truncation."""
|
||
|
||
text: str
|
||
truncated: bool = False
|
||
url: str | None = None
|
||
|
||
|
||
# ── Shell command summarisation ──────────────────────────────────────────
|
||
|
||
_SHELL_SILENT_HEADS = {"cd", "pushd", "popd", "export", "set", "unset", "source", ".", "true", "false", ":"}
|
||
_SHELL_PIPE_TAIL_HEADS = {"head", "tail", "wc", "sort", "uniq"}
|
||
|
||
|
||
def _shell_basename(head: str) -> str:
|
||
return head.rsplit("/", 1)[-1] if head else ""
|
||
|
||
|
||
def _scan_quoted(text: str) -> Iterator[tuple[int, str, bool]]:
|
||
"""Yield ``(index, char, inside_quotes)``; a quote closes unless backslash-escaped."""
|
||
quote: str | None = None
|
||
for i, ch in enumerate(text):
|
||
if quote:
|
||
yield i, ch, True
|
||
if ch == quote and (i == 0 or text[i - 1] != "\\"):
|
||
quote = None
|
||
elif ch in {"'", '"'}:
|
||
quote = ch
|
||
yield i, ch, True
|
||
else:
|
||
yield i, ch, False
|
||
|
||
|
||
def _split_shell_words(segment: str) -> list[str]:
|
||
parts: list[list[str]] = [[]]
|
||
for _, ch, quoted in _scan_quoted(segment):
|
||
if not quoted and ch.isspace():
|
||
parts.append([])
|
||
else:
|
||
parts[-1].append(ch)
|
||
return ["".join(p) for p in parts if p]
|
||
|
||
|
||
def _strip_shell_pipe_tail(segment: str) -> str:
|
||
"""Drop a trailing ``| head/tail/wc/sort/uniq ...`` pipeline stage."""
|
||
words = _split_shell_words(segment)
|
||
for i, word in enumerate(words):
|
||
if word == "|" and _shell_basename(words[i + 1] if i + 1 < len(words) else "") in _SHELL_PIPE_TAIL_HEADS:
|
||
words = words[:i]
|
||
break
|
||
return " ".join(words).strip()
|
||
|
||
|
||
def _split_shell_compound(command: str) -> list[str]:
|
||
"""Split on unquoted ``&&`` / ``||`` / ``;`` / newline, dropping pipe tails per segment."""
|
||
raw: list[list[str]] = [[]]
|
||
skip = False
|
||
for i, ch, quoted in _scan_quoted(command):
|
||
if skip:
|
||
skip = False
|
||
elif not quoted and (command.startswith("&&", i) or command.startswith("||", i)):
|
||
raw.append([])
|
||
skip = True
|
||
elif not quoted and ch in {";", "\n"}:
|
||
raw.append([])
|
||
else:
|
||
raw[-1].append(ch)
|
||
segments = (_strip_shell_pipe_tail("".join(buf).strip()) for buf in raw)
|
||
return [s for s in segments if s]
|
||
|
||
|
||
def _shell_head_word(segment: str) -> str:
|
||
"""Command name of a segment, skipping leading ``VAR=value`` assignments."""
|
||
words = _split_shell_words(segment)
|
||
while words and re.match(r"^[A-Za-z_]\w*=", words[0]):
|
||
words.pop(0)
|
||
return _shell_basename(words[0] if words else "")
|
||
|
||
|
||
def _clean_shell_segment(segment: str) -> str:
|
||
"""Drop redirections (``> file``, ``2>&1``) from a segment."""
|
||
words = _split_shell_words(segment)
|
||
out: list[str] = []
|
||
i = 0
|
||
while i < len(words):
|
||
word = words[i]
|
||
if re.match(r"^\d*(?:>>?|<)$", word):
|
||
i += 2 # operator + target
|
||
elif re.match(r"^\d*(?:>&|<&)\d+$", word):
|
||
i += 1
|
||
else:
|
||
out.append(word)
|
||
i += 1
|
||
return " ".join(out).strip()
|
||
|
||
|
||
def _is_shell_boundary_echo(segment: str) -> bool:
|
||
words = _split_shell_words(segment)
|
||
if _shell_basename(words[0] if words else "") != "echo":
|
||
return False
|
||
return bool(re.search(r"-{2,}|_exit=|(?:^|\s|=)\$[?{]|PIPESTATUS", " ".join(words[1:])))
|
||
|
||
|
||
def summarize_shell_command(command: str) -> str:
|
||
"""Compact shell wrapper/plumbing for display while preserving raw command elsewhere."""
|
||
original = _oneline(command)
|
||
if not original:
|
||
return ""
|
||
segments = _split_shell_compound(original)
|
||
if len(segments) <= 1:
|
||
return _clean_shell_segment(segments[0] if segments else original) or original
|
||
core: list[str] = []
|
||
for segment in segments:
|
||
cleaned = _clean_shell_segment(segment)
|
||
if cleaned and _shell_head_word(cleaned) not in _SHELL_SILENT_HEADS and not _is_shell_boundary_echo(cleaned):
|
||
core.append(cleaned)
|
||
if not core:
|
||
return original
|
||
count = len(core) - 1
|
||
if not count:
|
||
return core[0]
|
||
return t("display.preview.shell_plus_one" if count == 1 else "display.preview.shell_plus_many", first=core[0], count=count)
|
||
|
||
|
||
def _read_file_line_label(args: dict) -> str:
|
||
offset, limit = args.get("offset"), args.get("limit")
|
||
if not isinstance(offset, int) or offset <= 0:
|
||
return ""
|
||
return f"L{offset}-{offset + limit - 1}" if isinstance(limit, int) and limit > 1 else f"L{offset}"
|
||
|
||
|
||
def redact_browser_typed_text_for_display(value: Any, typed_text: Any) -> Any:
|
||
"""Replace every occurrence of a secret-looking browser_type value with its redacted form.
|
||
|
||
Backends echo the attempted input in error strings/metadata, so it is swapped before
|
||
reaching logs, callbacks, the model, or chat history. Forced regardless of
|
||
``security.redact_secrets``: a leaked typed credential is a security boundary.
|
||
"""
|
||
needle = "" if typed_text is None else str(typed_text)
|
||
redacted = redact_sensitive_text(needle, force=True) if needle else needle
|
||
if redacted == needle:
|
||
return value
|
||
if isinstance(value, str):
|
||
return value.replace(needle, redacted)
|
||
if isinstance(value, dict):
|
||
return {key: redact_browser_typed_text_for_display(item, typed_text) for key, item in value.items()}
|
||
if isinstance(value, list):
|
||
return [redact_browser_typed_text_for_display(item, typed_text) for item in value]
|
||
if isinstance(value, tuple):
|
||
return tuple(redact_browser_typed_text_for_display(item, typed_text) for item in value)
|
||
return value
|
||
|
||
|
||
def redact_tool_args_for_display(tool_name: str, args: dict | None) -> dict | None:
|
||
"""Return a copy of tool args safe for logs/progress UI (masks ``browser_type`` secrets)."""
|
||
if not isinstance(args, dict):
|
||
return args
|
||
if tool_name == "browser_type" and isinstance(args.get("text"), str):
|
||
return {**args, "text": redact_sensitive_text(args["text"], force=True)}
|
||
return args
|
||
|
||
|
||
def _delegate_task_goals(tasks: Any, *, per_goal_len: int) -> list[str]:
|
||
"""One truncated goal string per dict task (``?`` when missing)."""
|
||
if not isinstance(tasks, list):
|
||
return []
|
||
raw_goals = (task.get("goal") for task in tasks if isinstance(task, dict))
|
||
return [_tail_trunc(("?" if g is None else _oneline(str(g))) or "?", per_goal_len) for g in raw_goals]
|
||
|
||
|
||
def _browser_exec_step_label(args: dict, max_chars: int = 80) -> str | None:
|
||
"""User-friendly step label from browser_exec code's leading comment."""
|
||
first = str(args.get("code", "") or "").strip().split("\n", 1)[0].strip()
|
||
label = first.lstrip("#").strip() if first.startswith("#") else ""
|
||
if not label:
|
||
return None
|
||
return label[: max_chars - 1] + "…" if len(label) > max_chars else label
|
||
|
||
|
||
_PRIMARY_ARGS = {
|
||
"terminal": "command", "web_search": "query", "web_extract": "urls", "read_file": "path",
|
||
"write_file": "path", "patch": "path", "search_files": "pattern", "browser_navigate": "url",
|
||
"browser_click": "ref", "browser_type": "text", "image_generate": "prompt", "text_to_speech": "text",
|
||
"vision_analyze": "question", "skill_view": "name", "skills_list": "category", "cronjob_manage": "action",
|
||
"execute_code": "code", "browser_exec": "code", "delegate_task": "goal", "clarify": "question",
|
||
"skill_manage": "name",
|
||
}
|
||
_FALLBACK_PREVIEW_KEYS = ("query", "text", "command", "path", "name", "prompt", "code", "goal")
|
||
|
||
|
||
def _delegate_action_preview(args: dict) -> str | None:
|
||
"""Shared ``list/steer/stop <id>`` preview for delegate_task, or None for spawn calls."""
|
||
action = str(args.get("action") or "").strip().lower()
|
||
if action in ("list", "steer", "stop"):
|
||
return f"{action} {str(args.get('subagent_id') or '').strip()}".strip()
|
||
return None
|
||
|
||
|
||
def _preview_browser_exec(args: dict, max_len: int) -> str | None:
|
||
label = _browser_exec_step_label(args)
|
||
if label is not None:
|
||
return _tail_trunc(label, max_len)
|
||
return _tail_trunc(_oneline(str(args.get("code", "") or "")), max_len) or None
|
||
|
||
|
||
def _preview_delegate_task(args: dict, max_len: int) -> str | None:
|
||
action_preview = _delegate_action_preview(args)
|
||
tasks = args.get("tasks")
|
||
if action_preview is not None:
|
||
return _tail_trunc(action_preview, max_len)
|
||
if tasks and isinstance(tasks, list):
|
||
goals = _delegate_task_goals(tasks, per_goal_len=40)
|
||
preview = (t("display.preview.delegate_tasks", count=len(goals), goals=" | ".join(goals)) if goals
|
||
else t("display.preview.delegate_parallel_tasks", count=len(tasks)))
|
||
return _tail_trunc(preview, max_len)
|
||
goal = args.get("goal", "")
|
||
return None if goal is None else _tail_trunc(_oneline(str(goal)), max_len) or None
|
||
|
||
|
||
def _preview_process_manage(args: dict, _max_len: int) -> str | None:
|
||
action, sid, data, timeout_val = (args.get(k) for k in ("action", "session_id", "data", "timeout"))
|
||
parts = [str(action) if action else "", str(sid)[:16] if sid else "",
|
||
f'"{_oneline(str(data)[:20])}"' if data else "", f"{timeout_val}s" if timeout_val and action == "wait" else ""]
|
||
return " ".join(p for p in parts if p) or None
|
||
|
||
|
||
def _preview_todo_list(args: dict, _max_len: int) -> str:
|
||
todos_arg = args.get("todos")
|
||
verb = t("display.preview.todo_verb_updating" if args.get("merge", False) else "display.preview.todo_verb_planning")
|
||
return t("display.preview.todo_reading") if todos_arg is None else t("display.preview.todo_tasks", verb=verb, count=len(todos_arg))
|
||
|
||
|
||
def _preview_shell(key: str):
|
||
def _build(args: dict, max_len: int) -> str | None:
|
||
command = args.get(key)
|
||
return None if command is None else _tail_trunc(summarize_shell_command(str(command)), max_len) or None
|
||
return _build
|
||
|
||
|
||
def _preview_read_file(args: dict, max_len: int) -> str | None:
|
||
path = args.get("path") or args.get("file") or args.get("filepath")
|
||
label = (Path(str(path).replace("\\", "/")).name or str(path)) if path is not None else None
|
||
return None if label is None else _tail_trunc(f"{label} {_read_file_line_label(args)}".strip(), max_len) or None
|
||
|
||
|
||
def _preview_memory(args: dict, _max_len: int) -> str:
|
||
action, target = args.get("action", ""), args.get("target", "")
|
||
if action == "add":
|
||
return f"+{target}: \"{_clip(_oneline(args.get('content', '')), 25)}\""
|
||
if action in ("replace", "remove"):
|
||
old = _oneline(args.get("old_text") or "") or t("display.preview.missing_old_text")
|
||
return f"{'~' if action == 'replace' else '-'}{target}: \"{old[:20]}\""
|
||
return action
|
||
|
||
|
||
def _preview_send_message(args: dict, _max_len: int) -> str:
|
||
return t("display.preview.send_message_to", target=args.get("target", "?"),
|
||
message=_tail_trunc(_oneline(args.get("message", "")), 20))
|
||
|
||
|
||
def _preview_skill_view(args: dict, max_len: int) -> str | None:
|
||
name = _oneline(str(args.get("name") or ""))
|
||
file_path = args.get("file_path")
|
||
label = (f"{name} → {_oneline(str(file_path))}" if name else _oneline(str(file_path))) if file_path else name
|
||
return _tail_trunc(label, max_len) or None
|
||
|
||
|
||
def _preview_bridge_call(tool_name: str):
|
||
def _build(args: dict, max_len: int) -> str | None:
|
||
labels = bridge_tool_labels(tool_name, args)
|
||
if not labels:
|
||
return _primary_arg_preview(tool_name, args, max_len)
|
||
extra = f" +{len(labels) - 1}" if len(labels) > 1 else ""
|
||
return _tail_trunc(f"{labels[0].text}{extra}", max_len) or None
|
||
return _build
|
||
|
||
|
||
# Tool-specific preview builders: f(args, max_len) -> preview. Tools not listed
|
||
# fall through to the primary-argument lookup in build_tool_preview.
|
||
_PREVIEW_BUILDERS = {
|
||
"browser_exec": _preview_browser_exec, "delegate_task": _preview_delegate_task,
|
||
"process_manage": _preview_process_manage, "todo_list": _preview_todo_list,
|
||
"terminal": _preview_shell("command"), "execute_code": _preview_shell("code"),
|
||
"read_file": _preview_read_file, "memory": _preview_memory, "send_message": _preview_send_message,
|
||
"skill_view": _preview_skill_view,
|
||
"session_search": lambda args, _m: t("display.preview.session_search_recall", query=_clip(_oneline(args.get("query", "")), 25)),
|
||
"tool_call": _preview_bridge_call("tool_call"),
|
||
"tool_search": _preview_bridge_call("tool_search"),
|
||
"tool_describe": _preview_bridge_call("tool_describe"),
|
||
}
|
||
|
||
|
||
def build_tool_preview(tool_name: str, args: dict, max_len: int | None = None) -> str | None:
|
||
"""Build a short preview of a tool call's primary argument for display.
|
||
|
||
*max_len* ``None`` defers to the global ``_tool_preview_max_len``; ``0`` means unlimited.
|
||
"""
|
||
if max_len is None:
|
||
max_len = _tool_preview_max_len
|
||
if not args:
|
||
return None
|
||
args = redact_tool_args_for_display(tool_name, args) or args
|
||
builder = _PREVIEW_BUILDERS.get(tool_name)
|
||
if builder is not None:
|
||
return builder(args, max_len)
|
||
return _primary_arg_preview(tool_name, args, max_len)
|
||
|
||
|
||
def _primary_arg_preview(tool_name: str, args: dict, max_len: int) -> str | None:
|
||
key = _PRIMARY_ARGS.get(tool_name) or next((k for k in _FALLBACK_PREVIEW_KEYS if k in args), None)
|
||
if not key or key not in args:
|
||
return None
|
||
value = args[key]
|
||
preview = _oneline(str((value[0] if value else "") if isinstance(value, list) else value))
|
||
return _tail_trunc(preview, max_len) if preview else None
|
||
|
||
|
||
def prepare_tool_preview(tool_name: str, args: dict | None, *, fallback: str, max_len: int) -> ToolPreview:
|
||
"""Compact preview plus explicit truncation/URL facts (the uncapped preview is
|
||
rebuilt from the arguments so an upstream display cap cannot drop its link target)."""
|
||
full_text = build_tool_preview(tool_name, args, max_len=0) or fallback
|
||
text = _tail_trunc(full_text, max_len)
|
||
truncated = text != full_text
|
||
url = _http_url(_display_url(full_text)) if truncated else None
|
||
return ToolPreview(text=text, truncated=truncated, url=url)
|
||
|
||
|
||
# ── Friendly tool labels: "web_search <q>" -> "Searching the web for <q>" ──
|
||
# Curated built-ins only — we know each core tool's semantics so the verb is fixed,
|
||
# not computed; custom/plugin/MCP tools have no entry and fall back to the raw preview.
|
||
|
||
# Tools with a curated verb; the text itself lives in the catalog (``display.verb.<tool>``) and is
|
||
# resolved at call time by ``get_tool_verb`` so a ``display.language`` change applies immediately.
|
||
_TOOL_VERB_TOOLS: frozenset[str] = frozenset({
|
||
"web_search", "web_extract", "browser_navigate", "browser_click", "browser_type",
|
||
"read_file", "write_file", "patch", "search_files", "terminal", "execute_code",
|
||
"image_generate", "video_generate", "text_to_speech", "vision_analyze", "session_search",
|
||
"skill_view", "skills_list", "skill_manage", "delegate_task", "cronjob_manage", "clarify",
|
||
"memory", "todo_list",
|
||
})
|
||
|
||
|
||
def _tool_verb(tool_name: str) -> str | None:
|
||
return t(f"display.verb.{tool_name}") if tool_name in _TOOL_VERB_TOOLS else None
|
||
|
||
|
||
# Verbs that read better without the argument preview appended.
|
||
_TOOL_VERBS_NO_PREVIEW: frozenset[str] = frozenset({"skills_list", "session_search"})
|
||
# Verbs joined to the preview with " for " (search-style phrasing).
|
||
_TOOL_VERBS_FOR_CONNECTOR: frozenset[str] = frozenset({"web_search", "search_files"})
|
||
|
||
_BRIDGE_GENERATING_TOOLS: frozenset[str] = frozenset({"tool_call", "tool_search", "tool_describe"})
|
||
|
||
|
||
def bridge_generating_phrase(tool_name: str) -> str | None:
|
||
if not _friendly_tool_labels or tool_name not in _BRIDGE_GENERATING_TOOLS:
|
||
return None
|
||
return t(f"display.bridge_generating.{tool_name}")
|
||
|
||
|
||
def tool_labels_for_call(tool_name: str, args: dict | None) -> list:
|
||
try:
|
||
from tools.tool_labels import labels_for_call
|
||
labels = labels_for_call(tool_name, args or {})
|
||
except Exception as exc: # noqa: BLE001 — display must never abort a turn
|
||
logger.debug("bridge labels failed for %s: %s", tool_name, exc)
|
||
return []
|
||
skin = _get_skin()
|
||
overrides = (skin.tool_emojis if skin and skin.tool_emojis else None) or {}
|
||
return [replace(label, emoji=overrides[label.name]) if label.name in overrides else label
|
||
for label in labels]
|
||
|
||
|
||
def bridge_tool_labels(tool_name: str, args: dict | None) -> list:
|
||
return tool_labels_for_call(tool_name, args) if _friendly_tool_labels else []
|
||
|
||
|
||
def tool_row_emoji(tool_name: str, args: dict | None = None, default: str = "⚡") -> str:
|
||
labels = bridge_tool_labels(tool_name, args) if args else []
|
||
return labels[0].emoji if labels else get_tool_emoji(tool_name, default)
|
||
|
||
|
||
def get_tool_verb(tool_name: str) -> str | None:
|
||
"""Friendly verb for a built-in tool, or None (labels disabled / no curated verb);
|
||
callers compose ``f"{verb}{tool_verb_connector(tool)}{preview}"`` themselves."""
|
||
return _tool_verb(tool_name) if _friendly_tool_labels else None
|
||
|
||
|
||
def tool_verb_connector(tool_name: str) -> str:
|
||
"""Return the connector between a verb and its preview (" for " or " ")."""
|
||
return t("display.verb_connector.search" if tool_name in _TOOL_VERBS_FOR_CONNECTOR else "display.verb_connector.default")
|
||
|
||
|
||
def verb_drops_preview(tool_name: str) -> bool:
|
||
"""Whether the verb should render alone, without the argument preview."""
|
||
return tool_name in _TOOL_VERBS_NO_PREVIEW
|
||
|
||
|
||
def build_status_phrase(tool_name: str, args: dict | None, max_len: int = 49) -> str | None:
|
||
"""Lowercase "is <verb> <preview>…" phrase following the bot's display name (Slack setStatus).
|
||
|
||
``args=None`` gives a verb-only phrase (``display.live_status: verb`` keeps previews out
|
||
of shared channels). None for ``_thinking`` or disabled labels so callers use their
|
||
static default. Default ``max_len`` stays under Slack's ~50-char status truncation.
|
||
"""
|
||
if not tool_name or tool_name == "_thinking" or not _friendly_tool_labels:
|
||
return None
|
||
verb = _tool_verb(tool_name)
|
||
phrase = (t("display.status_phrase.verb", verb=f"{verb[0].lower()}{verb[1:]}") if verb
|
||
else t("display.status_phrase.using_tool", tool=tool_name))
|
||
with_preview = args and verb and tool_name not in _TOOL_VERBS_NO_PREVIEW
|
||
preview = build_tool_preview(tool_name, args, max_len=None) if with_preview else None
|
||
if preview: # previews can contain newlines (terminal commands); keep the first line
|
||
phrase = f"{phrase}{tool_verb_connector(tool_name)}{preview.splitlines()[0].strip()}"
|
||
return phrase[: max_len - 2].rstrip() + "…" if len(phrase) > max_len - 1 else phrase + "…"
|
||
|
||
|
||
def build_tool_label(tool_name: str, args: dict, max_len: int | None = None) -> str | None:
|
||
labels = bridge_tool_labels(tool_name, args)
|
||
if labels:
|
||
label = labels[0]
|
||
preview = _tail_trunc(label.preview, max_len if max_len is not None else _tool_preview_max_len)
|
||
extra = f" +{len(labels) - 1}" if len(labels) > 1 else ""
|
||
return f"{label.text}{f' {preview}' if preview else ''}{extra}"
|
||
verb = get_tool_verb(tool_name)
|
||
if verb and tool_name in _TOOL_VERBS_NO_PREVIEW:
|
||
return verb
|
||
preview = build_tool_preview(tool_name, args, max_len=max_len)
|
||
if not verb:
|
||
return preview
|
||
return f"{verb}{tool_verb_connector(tool_name)}{preview}" if preview else verb
|
||
|
||
|
||
# ── Inline diff previews for write actions ────────────────────────────────
|
||
|
||
def _resolved_path(path: str) -> Path:
|
||
"""Resolve a possibly-relative filesystem path against the current cwd."""
|
||
return Path.cwd() / Path(os.path.expanduser(path)) # a `/` with an absolute rhs keeps the rhs
|
||
|
||
|
||
def _snapshot_text(path: Path) -> str | None:
|
||
"""Return UTF-8 file content, or None for missing/unreadable files."""
|
||
try:
|
||
return path.read_text(encoding="utf-8-sig")
|
||
except (FileNotFoundError, IsADirectoryError, UnicodeDecodeError, OSError):
|
||
return None
|
||
|
||
|
||
def _display_diff_path(path: Path) -> str:
|
||
"""Prefer cwd-relative paths in diffs when available."""
|
||
try:
|
||
return str(path.resolve().relative_to(Path.cwd().resolve()))
|
||
except Exception:
|
||
return str(path)
|
||
|
||
|
||
def _resolve_skill_manage_paths(args: dict) -> list[Path]:
|
||
"""Resolve skill_manage write targets to filesystem paths."""
|
||
action = args.get("action")
|
||
name = args.get("name")
|
||
if not action or not name:
|
||
return []
|
||
from tools.skill_manager_tool import _find_skill, _resolve_skill_dir
|
||
|
||
if action == "create":
|
||
return [_resolve_skill_dir(name, args.get("category")) / "SKILL.md"]
|
||
existing = _find_skill(name)
|
||
if not existing:
|
||
return []
|
||
skill_dir = Path(existing["path"])
|
||
file_path = args.get("file_path")
|
||
if action == "delete":
|
||
return [path for path in sorted(skill_dir.rglob("*")) if path.is_file()]
|
||
if file_path and action in {"edit", "patch", "write_file", "remove_file"}:
|
||
return [skill_dir / file_path]
|
||
return [skill_dir / "SKILL.md"] if action in {"edit", "patch"} else []
|
||
|
||
|
||
def _resolve_local_edit_paths(tool_name: str, function_args: dict | None, task_id: str | None = None) -> list[Path]:
|
||
"""Resolve local filesystem targets for write-capable tools."""
|
||
if not isinstance(function_args, dict):
|
||
return []
|
||
if tool_name == "skill_manage":
|
||
return _resolve_skill_manage_paths(function_args)
|
||
path = function_args.get("path") if tool_name in {"write_file", "patch"} else None
|
||
if path and task_id is not None:
|
||
from tools.file_tools_paths import _resolve_path_for_task, _terminal_env_type_for_task
|
||
|
||
# A remote target may happen to exist on this host too. Never persist a
|
||
# preview of that unrelated file; patch can still supply its own diff.
|
||
if _terminal_env_type_for_task(task_id) != "local":
|
||
return []
|
||
return [Path(_resolve_path_for_task(path, task_id))]
|
||
return [_resolved_path(path)] if path else []
|
||
|
||
|
||
def capture_local_edit_snapshot(
|
||
tool_name: str, function_args: dict | None, *, task_id: str | None = None,
|
||
) -> LocalEditSnapshot | None:
|
||
"""Capture before-state for local write previews."""
|
||
paths = _resolve_local_edit_paths(tool_name, function_args, task_id)
|
||
if not paths:
|
||
return None
|
||
return LocalEditSnapshot(paths=paths, before={str(path): _snapshot_text(path) for path in paths})
|
||
|
||
|
||
def _result_succeeded(result: str | None) -> bool:
|
||
"""Conservatively detect whether a tool result represents success."""
|
||
data = safe_json_loads(result) if result else None
|
||
if not isinstance(data, dict) or data.get("error"):
|
||
return False
|
||
return bool(data.get("success")) if "success" in data else True
|
||
|
||
|
||
def _diff_from_snapshot(snapshot: LocalEditSnapshot | None) -> str | None:
|
||
"""Generate unified diff text from a stored before-state and current files."""
|
||
if not snapshot:
|
||
return None
|
||
chunks: list[str] = []
|
||
for path in snapshot.paths:
|
||
before, after = snapshot.before.get(str(path)), _snapshot_text(path)
|
||
if before == after:
|
||
continue
|
||
display_path = _display_diff_path(path)
|
||
diff = "".join(unified_diff(
|
||
(before or "").splitlines(keepends=True), (after or "").splitlines(keepends=True),
|
||
fromfile=f"a/{display_path}", tofile=f"b/{display_path}",
|
||
))
|
||
if diff:
|
||
chunks.append(diff if diff.endswith("\n") else diff + "\n")
|
||
return "".join(chunks) or None
|
||
|
||
|
||
def extract_edit_diff(
|
||
tool_name: str, result: str | None, *,
|
||
function_args: dict | None = None, snapshot: LocalEditSnapshot | None = None,
|
||
) -> str | None:
|
||
"""Extract a unified diff from a file-edit tool result."""
|
||
if tool_name == "patch" and result:
|
||
data = safe_json_loads(result)
|
||
diff = data.get("diff") if isinstance(data, dict) else None
|
||
if isinstance(diff, str) and diff.strip():
|
||
return diff
|
||
if tool_name not in {"write_file", "patch", "skill_manage"} or not _result_succeeded(result):
|
||
return None
|
||
return _diff_from_snapshot(snapshot)
|
||
|
||
|
||
def _emit_inline_diff(diff_text: str, print_fn) -> bool:
|
||
"""Emit rendered diff text through the CLI's prompt_toolkit-safe printer."""
|
||
if print_fn is None or not diff_text:
|
||
return False
|
||
try:
|
||
for line in [t("display.diff.review_header"), *diff_text.rstrip("\n").splitlines()]:
|
||
print_fn(line)
|
||
return True
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
# Unified-diff line prefix -> diff color key (checked in order; "--- "/"+++ " handled first).
|
||
_DIFF_LINE_COLORS = (("@@", "hunk"), ("-", "minus"), ("+", "plus"), (" ", "dim"))
|
||
|
||
|
||
def _render_inline_unified_diff(diff: str) -> list[str]:
|
||
"""Render unified diff lines in Hermes' inline transcript style."""
|
||
rendered: list[str] = []
|
||
from_file = to_file = None
|
||
for raw_line in diff.splitlines():
|
||
if raw_line.startswith("--- "):
|
||
from_file = raw_line[4:].strip()
|
||
continue
|
||
if raw_line.startswith("+++ "):
|
||
to_file = raw_line[4:].strip()
|
||
if from_file or to_file:
|
||
rendered.append(f"{_diff_ansi()['file']}{from_file or 'a/?'} → {to_file or 'b/?'}{_ANSI_RESET}")
|
||
continue
|
||
color = next((c for prefix, c in _DIFF_LINE_COLORS if raw_line.startswith(prefix)), None)
|
||
if color:
|
||
rendered.append(f"{_diff_ansi()[color]}{raw_line}{_ANSI_RESET}")
|
||
elif raw_line:
|
||
rendered.append(raw_line)
|
||
return rendered
|
||
|
||
|
||
def _split_unified_diff_sections(diff: str) -> list[str]:
|
||
"""Split a unified diff into per-file sections."""
|
||
sections: list[list[str]] = [[]]
|
||
for line in diff.splitlines():
|
||
if line.startswith("--- ") and sections[-1]:
|
||
sections.append([])
|
||
sections[-1].append(line)
|
||
return ["\n".join(section) for section in sections if section]
|
||
|
||
|
||
def _summarize_rendered_diff_sections(
|
||
diff: str, *, max_files: int = _MAX_INLINE_DIFF_FILES, max_lines: int = _MAX_INLINE_DIFF_LINES,
|
||
) -> list[str]:
|
||
"""Render diff sections while capping file count and total line count."""
|
||
sections = _split_unified_diff_sections(diff)
|
||
rendered: list[str] = []
|
||
omitted_files = omitted_lines = 0
|
||
for idx, section in enumerate(sections):
|
||
section_lines = _render_inline_unified_diff(section)
|
||
remaining_budget = max_lines - len(rendered)
|
||
if idx >= max_files or remaining_budget <= 0:
|
||
omitted_files += 1
|
||
omitted_lines += len(section_lines)
|
||
continue
|
||
if len(section_lines) <= remaining_budget:
|
||
rendered.extend(section_lines)
|
||
continue
|
||
rendered.extend(section_lines[:remaining_budget])
|
||
omitted_lines += len(section_lines) - remaining_budget
|
||
omitted_files += 1 + max(0, len(sections) - idx - 1)
|
||
for leftover in sections[idx + 1:]:
|
||
omitted_lines += len(_render_inline_unified_diff(leftover))
|
||
break
|
||
if omitted_files or omitted_lines:
|
||
summary = t("display.diff.omitted_lines", count=omitted_lines)
|
||
if omitted_files:
|
||
summary += t("display.diff.omitted_files", count=omitted_files)
|
||
rendered.append(f"{_diff_ansi()['hunk']}{summary}{_ANSI_RESET}")
|
||
return rendered
|
||
|
||
|
||
def render_edit_diff_with_delta(
|
||
tool_name: str, result: str | None, *,
|
||
function_args: dict | None = None, snapshot: LocalEditSnapshot | None = None, print_fn=None,
|
||
) -> bool:
|
||
"""Render an edit diff inline without taking over the terminal UI."""
|
||
diff = extract_edit_diff(tool_name, result, function_args=function_args, snapshot=snapshot)
|
||
if not diff:
|
||
return False
|
||
try:
|
||
rendered_lines = _summarize_rendered_diff_sections(diff)
|
||
except Exception as exc:
|
||
logger.debug("Could not render inline diff: %s", exc)
|
||
return False
|
||
return _emit_inline_diff("\n".join(rendered_lines), print_fn)
|
||
|
||
|
||
# ── KawaiiSpinner ─────────────────────────────────────────────────────────
|
||
|
||
class KawaiiSpinner:
|
||
"""Animated spinner with kawaii faces for CLI feedback during tool execution."""
|
||
|
||
SPINNERS = {
|
||
'dots': list('⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'), 'bounce': list('⠁⠂⠄⡀⢀⠠⠐⠈'), 'grow': list('▁▂▃▄▅▆▇█▇▆▅▄▃▂'),
|
||
'arrows': list('←↖↑↗→↘↓↙'), 'star': list('✶✷✸✹✺✹✸✷'), 'moon': list('🌑🌒🌓🌔🌕🌖🌗🌘'),
|
||
'pulse': list('◜◠◝◞◡◟'), 'brain': list('🧠💭💡✨💫🌟💡💭'), 'sparkle': list('⁺˚*✧✦✧*˚'),
|
||
}
|
||
KAWAII_WAITING = [
|
||
"(。◕‿◕。)", "(◕‿◕✿)", "٩(◕‿◕。)۶", "(✿◠‿◠)", "( ˘▽˘)っ", "♪(´ε` )", "(◕ᴗ◕✿)", "ヾ(^∇^)", "(≧◡≦)", "(★ω★)",
|
||
]
|
||
KAWAII_THINKING = [
|
||
"(。•́︿•̀。)", "(◔_◔)", "(¬‿¬)", "( •_•)>⌐■-■", "(⌐■_■)", "(´・_・`)", "◉_◉", "(°ロ°)", "( ˘⌣˘)♡", "ヽ(>∀<☆)☆",
|
||
"٩(๑❛ᴗ❛๑)۶", "(⊙_⊙)", "(¬_¬)", "( ͡° ͜ʖ ͡°)", "ಠ_ಠ",
|
||
]
|
||
# English fallback; ``get_thinking_verbs`` prefers the skin list, then the catalog
|
||
# (``display.thinking_verbs``, comma-separated) for the active language.
|
||
THINKING_VERBS = [
|
||
"pondering", "contemplating", "musing", "cogitating", "ruminating", "deliberating", "mulling",
|
||
"reflecting", "processing", "reasoning", "analyzing", "computing", "synthesizing", "formulating",
|
||
"brainstorming",
|
||
]
|
||
|
||
@staticmethod
|
||
def _skin_spinner_list(key: str, fallback: list) -> list:
|
||
"""Return the active skin's ``spinner[key]`` list, or *fallback* when absent/empty."""
|
||
try:
|
||
skin = _get_skin()
|
||
return (skin.spinner.get(key, []) if skin else None) or fallback
|
||
except Exception:
|
||
return fallback
|
||
|
||
get_waiting_faces = classmethod(lambda cls: cls._skin_spinner_list("waiting_faces", cls.KAWAII_WAITING))
|
||
get_thinking_faces = classmethod(lambda cls: cls._skin_spinner_list("thinking_faces", cls.KAWAII_THINKING))
|
||
@classmethod
|
||
def _catalog_thinking_verbs(cls) -> list[str]:
|
||
verbs = [v.strip() for v in t("display.thinking_verbs").split(",") if v.strip()]
|
||
return verbs if verbs and verbs != ["display.thinking_verbs"] else cls.THINKING_VERBS
|
||
|
||
get_thinking_verbs = classmethod(lambda cls: cls._skin_spinner_list("thinking_verbs", cls._catalog_thinking_verbs()))
|
||
|
||
def __init__(self, message: str = "", spinner_type: str = 'dots', print_fn=None):
|
||
self.message = message
|
||
self.spinner_frames = self.SPINNERS.get(spinner_type, self.SPINNERS['dots'])
|
||
self.running = False
|
||
self.thread = self.start_time = None
|
||
self.frame_idx = self.last_line_len = 0
|
||
self._print_fn = print_fn # when set, bypasses self._out so silenced agents stay silent
|
||
self._out = sys.stdout # captured NOW, before any child redirect_stdout(devnull) replaces it
|
||
|
||
def _write(self, text: str, end: str = '\n', flush: bool = False):
|
||
"""Write via print_fn when supplied, else to the stdout captured at creation."""
|
||
if self._print_fn is not None:
|
||
try:
|
||
self._print_fn(text)
|
||
except Exception:
|
||
pass
|
||
return
|
||
try:
|
||
self._out.write(text + end)
|
||
if flush:
|
||
self._out.flush()
|
||
except (ValueError, OSError):
|
||
pass
|
||
|
||
@property
|
||
def _is_tty(self) -> bool:
|
||
"""Check if output is a real terminal, safe against closed streams."""
|
||
try:
|
||
return hasattr(self._out, 'isatty') and self._out.isatty()
|
||
except (ValueError, OSError):
|
||
return False
|
||
|
||
def _is_patch_stdout_proxy(self) -> bool:
|
||
"""True for prompt_toolkit's StdoutProxy: it injects newlines around each flush so the
|
||
\\r overwrite never lands, and the CLI drives its own TUI spinner widget in that mode."""
|
||
try:
|
||
from prompt_toolkit.patch_stdout import StdoutProxy
|
||
return isinstance(self._out, StdoutProxy)
|
||
except ImportError:
|
||
return False
|
||
|
||
def _animate(self):
|
||
tty = self._is_tty
|
||
# Non-TTY (Docker, systemd, pipe): log once instead of spamming frames.
|
||
if not tty:
|
||
self._write(t("display.spinner.tool_line", message=self.message), flush=True)
|
||
# Under patch_stdout the \r animation would overdraw the TUI status bar.
|
||
if not tty or self._is_patch_stdout_proxy():
|
||
while self.running:
|
||
time.sleep(0.5 if not tty else 0.1)
|
||
return
|
||
skin = _get_skin()
|
||
wings = skin.get_spinner_wings() if skin else []
|
||
while self.running:
|
||
if os.getenv("HERMES_SPINNER_PAUSE"):
|
||
time.sleep(0.1)
|
||
continue
|
||
frame = self.spinner_frames[self.frame_idx % len(self.spinner_frames)]
|
||
elapsed = f"({time.time() - self.start_time:.1f}s)"
|
||
left, right = wings[self.frame_idx % len(wings)] if wings else ("", "")
|
||
line = f" {left} {frame} {self.message} {right} {elapsed}" if wings else f" {frame} {self.message} {elapsed}"
|
||
self._write(f"\r{line}{' ' * max(self.last_line_len - len(line), 0)}", end='', flush=True)
|
||
self.last_line_len = len(line)
|
||
self.frame_idx += 1
|
||
time.sleep(0.12)
|
||
|
||
def start(self):
|
||
if self.running:
|
||
return
|
||
self.running, self.start_time = True, time.time()
|
||
self.thread = threading.Thread(target=self._animate, daemon=True)
|
||
self.thread.start()
|
||
|
||
def update_text(self, new_message: str):
|
||
self.message = new_message
|
||
|
||
def _clear_line_blanks(self) -> str:
|
||
return ' ' * max(self.last_line_len + 5, 40) # spaces, not \033[K: garbles under patch_stdout
|
||
|
||
def print_above(self, text: str):
|
||
"""Print a line above the spinner (next tick redraws it below). Works inside
|
||
redirect_stdout(devnull) because _write targets the stdout captured at creation."""
|
||
self._write(f"\r{self._clear_line_blanks()}\r {text}" if self.running else f" {text}", flush=True)
|
||
|
||
def stop(self, final_message: str = None):
|
||
self.running = False
|
||
if self.thread:
|
||
self.thread.join(timeout=0.5)
|
||
is_tty = self._is_tty
|
||
if is_tty:
|
||
self._write(f"\r{self._clear_line_blanks()}\r", end='', flush=True)
|
||
if final_message:
|
||
elapsed = f" ({time.time() - self.start_time:.1f}s)" if self.start_time else ""
|
||
self._write(f" {final_message}" if is_tty else t("display.spinner.done_line", message=final_message, elapsed=elapsed), flush=True)
|
||
|
||
def __enter__(self):
|
||
self.start()
|
||
return self
|
||
|
||
def __exit__(self, *exc):
|
||
self.stop()
|
||
return False
|
||
|
||
|
||
# ── Cute tool message (completion line that replaces the spinner) ─────────
|
||
|
||
_ERROR_SUFFIX_MAX_LEN = 48
|
||
# A degraded backend (Docker down, SSH host unreachable) needs the whole reason plus the fix hint.
|
||
_DEGRADED_SUFFIX_MAX_LEN = 200
|
||
|
||
|
||
def _trim_error(msg: str) -> str:
|
||
"""Shrink an error message for inline display (long 'File not found' paths -> filename)."""
|
||
msg = msg.strip()
|
||
if "File not found:" in msg:
|
||
tail = msg.partition("File not found:")[2].strip()
|
||
if "/" in tail:
|
||
msg = t("display.failure.file_not_found", name=tail.rsplit("/", 1)[-1])
|
||
return _tail_trunc(msg, _ERROR_SUFFIX_MAX_LEN)
|
||
|
||
|
||
def _degraded_suffix(data: dict) -> str:
|
||
"""`` [<reason> — <retry_hint>]`` for a ``status: degraded`` terminal result (hint omitted when empty)."""
|
||
reason = str(data.get("reason") or data.get("error") or t("display.failure.terminal_backend_unavailable")).strip()
|
||
hint = str(data.get("retry_hint") or "").strip()
|
||
text = f"{reason} — {hint}" if hint else reason
|
||
return f" [{_tail_trunc(text, _DEGRADED_SUFFIX_MAX_LEN)}]"
|
||
|
||
|
||
def _detect_tool_failure(tool_name: str, result: Any) -> tuple[bool, str]:
|
||
"""Return ``(is_failure, suffix)`` for a tool result, e.g. ``(True, " [exit 1]")``."""
|
||
if result is None or file_mutation_result_landed(tool_name, result):
|
||
return False, ""
|
||
data = result if isinstance(result, dict) else safe_json_loads(result)
|
||
# A harness REFUSAL of a redundant call (repeated identical read/search) is not a
|
||
# failed call. This is the ``failed`` the executor hands the loop guardrail, so
|
||
# counting it would escalate refusals into ``repeated_exact_failure_block``.
|
||
if is_guardrail_refusal(data):
|
||
return False, ""
|
||
|
||
# A denied/timed-out approval carries one human sentence; show it instead of the model-facing
|
||
# "BLOCKED: ... Do NOT retry" text (which stays in the JSON for the model).
|
||
if isinstance(data, dict) and data.get("user_summary"):
|
||
return True, f" [{_tail_trunc(str(data['user_summary']), _DEGRADED_SUFFIX_MAX_LEN)}]"
|
||
|
||
# Terminal: non-zero exit code is the canonical failure signal.
|
||
if tool_name == "terminal":
|
||
exit_code = data.get("exit_code") if isinstance(data, dict) else None
|
||
if exit_code is None or exit_code == 0:
|
||
return False, ""
|
||
if data.get("status") == "degraded":
|
||
return True, _degraded_suffix(data)
|
||
err_msg = data.get("error")
|
||
return True, f" [{_trim_error(str(err_msg))}]" if err_msg else t("display.failure.exit_code", code=exit_code)
|
||
|
||
if isinstance(data, dict):
|
||
failed = data.get("success") is False
|
||
# Memory: distinguish "store full" from real errors.
|
||
if tool_name == "memory" and failed and "exceed the limit" in data.get("error", ""):
|
||
return True, t("display.failure.memory_full")
|
||
err = data.get("error") or data.get("message")
|
||
if err and (failed or "error" in data):
|
||
return True, f" [{_trim_error(str(err))}]"
|
||
# Multimodal results (dicts) are successes; failures arrive as JSON-encoded strings.
|
||
if isinstance(result, str) and (
|
||
'"error"' in result[:500].lower() or '"failed"' in result[:500].lower() or result.startswith("Error")
|
||
):
|
||
return True, t("display.failure.generic")
|
||
return False, ""
|
||
|
||
|
||
def _domain(url: str) -> str:
|
||
return url.replace("https://", "").replace("http://", "").split("/")[0]
|
||
|
||
|
||
def _cute_trunc(s) -> str:
|
||
"""Tail-truncate to the configured preview cap (0 = unlimited)."""
|
||
return _tail_trunc(str(s), _tool_preview_max_len)
|
||
|
||
|
||
def _cute_path(p) -> str:
|
||
"""Head-truncate a path to the configured preview cap, keeping the filename end."""
|
||
p = str(p)
|
||
limit = _tool_preview_max_len
|
||
if not limit or len(p) <= limit:
|
||
return p
|
||
return "." * limit if limit <= 3 else "..." + p[-(limit - 3):]
|
||
|
||
|
||
def _cute_row(emoji: str, verb: str, detail: str = "") -> str:
|
||
"""``┊ {emoji} {verb:9} {detail}`` -- verb column from ``display.cute.verb.<verb>`` (9 cells wide)."""
|
||
return f"┊ {emoji} {t(f'display.cute.verb.{verb}'):9} {detail}"
|
||
|
||
|
||
def _cute_web_extract(a: dict, _r) -> str:
|
||
urls = a.get("urls", [])
|
||
url = _display_url(urls[0] if isinstance(urls, list) else urls) if urls else ""
|
||
if not url:
|
||
return _cute_row("📄", "fetch", t("display.cute.fetch_pages"))
|
||
extra = f" +{len(urls)-1}" if isinstance(urls, list) and len(urls) > 1 else ""
|
||
return _cute_row("📄", "fetch", f"{_cute_trunc(_domain(url))}{extra}")
|
||
|
||
|
||
def _cute_todo_list(a: dict, result) -> str:
|
||
todos_arg = a.get("todos")
|
||
total = done = 0
|
||
try:
|
||
summary = (safe_json_loads(result) or {}).get("summary", {}) if result else {}
|
||
total, done = summary.get("total", 0), summary.get("completed", 0)
|
||
except Exception:
|
||
pass
|
||
progress = t("display.cute.todo_progress", done=done, total=total)
|
||
if todos_arg is None:
|
||
detail = progress if total > 0 else t("display.cute.todo_reading")
|
||
elif a.get("merge", False):
|
||
detail = (t("display.cute.todo_update_progress", done=done, total=total) if total > 0 and done > 0
|
||
else t("display.cute.todo_update_count", count=len(todos_arg)))
|
||
else:
|
||
detail = progress if total > 0 and done > 0 else t("display.cute.todo_count", count=len(todos_arg))
|
||
return _cute_row("📋", "plan", detail)
|
||
|
||
|
||
def _cute_memory(a: dict, _r) -> str:
|
||
action, target = a.get("action", "?"), a.get("target", "")
|
||
if action == "add":
|
||
return _cute_row("🧠", "memory", f"+{target}: \"{_cute_trunc(a.get('content', ''))}\"")
|
||
if action in ("replace", "remove"):
|
||
old = a.get("old_text") or t("display.preview.missing_old_text")
|
||
return _cute_row("🧠", "memory", f"{'~' if action == 'replace' else '-'}{target}: \"{_cute_trunc(old)}\"")
|
||
return _cute_row("🧠", "memory", str(action))
|
||
|
||
|
||
def _cute_skill_view(a: dict, _r) -> str:
|
||
label, file_path = a.get("name", ""), a.get("file_path")
|
||
label = (f"{label} → {file_path}" if label else str(file_path)) if file_path else label
|
||
return _cute_row("📚", "skill", _cute_trunc(label))
|
||
|
||
|
||
def _cute_cronjob(a: dict, _r) -> str:
|
||
action = a.get("action", "?")
|
||
if action == "create":
|
||
skills = a.get("skills") or ([a.get("skill")] if a.get("skill") else [])
|
||
label = a.get("name") or (skills[0] if skills else None) or a.get("prompt", t("display.cute.cron_task_fallback"))
|
||
return _cute_row("⏰", "cron", t("display.cute.cron_create", label=_cute_trunc(label)))
|
||
if action == "list":
|
||
return _cute_row("⏰", "cron", t("display.cute.cron_listing"))
|
||
return _cute_row("⏰", "cron", f"{action} {a.get('job_id', '')}")
|
||
|
||
|
||
def _cute_execute_code(a: dict, _r) -> str:
|
||
code = a.get("code", "").strip()
|
||
return _cute_row("🐍", "exec", _cute_trunc(code.split(chr(10))[0] if code else ""))
|
||
|
||
|
||
def _cute_browser_exec(a: dict, _r) -> str:
|
||
# Leading `# …` comment becomes the step label; code stays collapsed behind the preview cap.
|
||
label = _browser_exec_step_label(a)
|
||
return _cute_row("🌐", "browser", _cute_trunc(_oneline(str(a.get("code", "") or ""))) if label is None else label)
|
||
|
||
|
||
def _cute_delegate(a: dict, _r) -> str:
|
||
action_preview = _delegate_action_preview(a)
|
||
tasks = a.get("tasks")
|
||
if action_preview is not None:
|
||
return _cute_row("🔀", "delegate", _cute_trunc(action_preview))
|
||
if tasks and isinstance(tasks, list):
|
||
goals = _delegate_task_goals(tasks, per_goal_len=30)
|
||
joined = _cute_trunc(" | ".join(goals) if goals else t("display.cute.delegate_parallel"))
|
||
return _cute_row("🔀", "delegate", f"{len(goals) or len(tasks)}x: {joined}")
|
||
return _cute_row("🔀", "delegate", _cute_trunc(a.get("goal", "")))
|
||
|
||
|
||
def _cute_process_manage(a: dict, _r) -> str:
|
||
action, sid = a.get("action", "?"), a.get("session_id", "")[:12]
|
||
return _cute_row("⚙️ ", "proc", t("display.cute.process_list") if action == "list" else f"{action} {sid}")
|
||
|
||
|
||
_SCROLL_ARROWS = {"down": "↓", "up": "↑", "right": "→", "left": "←"}
|
||
|
||
|
||
def _cute_scroll(a: dict, _r) -> str:
|
||
direction = a.get("direction", "down")
|
||
label = t(f"display.cute.scroll.{direction}") if direction in _SCROLL_ARROWS else str(direction)
|
||
return _cute_row(f"{_SCROLL_ARROWS.get(direction, '↓')} ", "scroll", label)
|
||
|
||
|
||
# Completion-line renderers: tool -> f(args, result) -> "┊ {emoji} {verb:9} {detail}" (duration appended by caller).
|
||
_CUTE_LINES = {
|
||
"web_search": lambda a, r: _cute_row("🔍", "search", _cute_trunc(a.get("query", ""))),
|
||
"web_extract": _cute_web_extract,
|
||
"terminal": lambda a, r: _cute_row("💻", "terminal", _cute_trunc(build_tool_preview("terminal", a) or a.get("command", ""))),
|
||
"process_manage": _cute_process_manage,
|
||
"read_file": lambda a, r: _cute_row("📖", "read", _cute_trunc(build_tool_preview("read_file", a) or a.get("path", ""))),
|
||
"write_file": lambda a, r: _cute_row("✍️ ", "write", _cute_path(a.get("path", ""))),
|
||
"patch": lambda a, r: _cute_row("🔧", "patch", _cute_path(a.get("path", ""))),
|
||
"search_files": lambda a, r: _cute_row("🔎", "find" if a.get("target", "content") == "files" else "grep", _cute_trunc(a.get("pattern", ""))),
|
||
"browser_navigate": lambda a, r: _cute_row("🌐", "navigate", _cute_trunc(_domain(a.get("url", "")))),
|
||
"browser_snapshot": lambda a, r: _cute_row("📸", "snapshot", t("display.cute.snapshot_full" if a.get("full") else "display.cute.snapshot_compact")),
|
||
"browser_click": lambda a, r: _cute_row("👆", "click", str(a.get("ref", "?"))),
|
||
"browser_type": lambda a, r: _cute_row("⌨️ ", "type", f"\"{_cute_trunc(a.get('text', ''))}\""),
|
||
"browser_scroll": _cute_scroll,
|
||
"browser_back": lambda a, r: _cute_row("◀️ ", "back"),
|
||
"browser_press": lambda a, r: _cute_row("⌨️ ", "press", str(a.get("key", "?"))),
|
||
"browser_get_images": lambda a, r: _cute_row("🖼️ ", "images", t("display.cute.images_extracting")),
|
||
"browser_vision": lambda a, r: _cute_row("👁️ ", "vision", t("display.cute.vision_analyzing_page")),
|
||
"todo_list": _cute_todo_list,
|
||
"session_search": lambda a, r: _cute_row("🔍", "recall", f"\"{_cute_trunc(a.get('query', ''))}\""),
|
||
"memory": _cute_memory,
|
||
"skills_list": lambda a, r: _cute_row("📚", "skills", t("display.cute.skills_list", category=a.get("category") or t("display.cute.skills_all"))),
|
||
"skill_view": _cute_skill_view,
|
||
"image_generate": lambda a, r: _cute_row("🎨", "create", _cute_trunc(a.get("prompt", ""))),
|
||
"text_to_speech": lambda a, r: _cute_row("🔊", "speak", _cute_trunc(a.get("text", ""))),
|
||
"vision_analyze": lambda a, r: _cute_row("👁️ ", "vision", _cute_trunc(a.get("question", ""))),
|
||
"send_message": lambda a, r: _cute_row("📨", "send", f"{a.get('target', '?')}: \"{_cute_trunc(a.get('message', ''))}\""),
|
||
"cronjob_manage": _cute_cronjob,
|
||
"execute_code": _cute_execute_code,
|
||
"browser_exec": _cute_browser_exec,
|
||
"delegate_task": _cute_delegate,
|
||
}
|
||
|
||
|
||
def _cute_bridge_rows(tool_name: str, args: dict) -> list[str] | None:
|
||
labels = bridge_tool_labels(tool_name, args)
|
||
if not labels:
|
||
return None
|
||
return [f"┊ {label.emoji} {_cute_trunc(label.text)}"
|
||
f"{f' {_cute_trunc(label.preview)}' if label.preview else ''}" for label in labels]
|
||
|
||
|
||
_BRIDGE_CALL_INDEX_RE = re.compile(r"calls\[(\d+)\]")
|
||
|
||
|
||
def _entry_failure_suffix(entry: Any) -> str:
|
||
if not isinstance(entry, dict):
|
||
return ""
|
||
error = entry.get("error")
|
||
if isinstance(error, dict):
|
||
return f" [{_trim_error(str(error.get('message') or error.get('code') or t('display.failure.generic_word')))}]"
|
||
if not (error or entry.get("success") is False):
|
||
return ""
|
||
return _detect_tool_failure(str(entry.get("name") or ""), entry)[1]
|
||
|
||
|
||
def _bridge_row_suffixes(rows: int, result: Any, call_suffix: str) -> list[str]:
|
||
suffixes = [""] * rows
|
||
data = result if isinstance(result, dict) else safe_json_loads(result)
|
||
entries = data.get("results") if isinstance(data, dict) else None
|
||
if isinstance(entries, list):
|
||
for position, entry in enumerate(entries[:rows]):
|
||
suffix = _entry_failure_suffix(entry)
|
||
if not suffix:
|
||
continue
|
||
index = entry.get("index")
|
||
suffixes[index if isinstance(index, int) and 0 <= index < rows else position] = suffix
|
||
if call_suffix and not any(suffixes):
|
||
match = _BRIDGE_CALL_INDEX_RE.search(call_suffix)
|
||
named = int(match.group(1)) if match else rows - 1
|
||
suffixes[named if 0 <= named < rows else rows - 1] = call_suffix
|
||
return suffixes
|
||
|
||
|
||
def _get_cute_tool_message(tool_name: str, args: dict, duration: float, result: str | None = None) -> str:
|
||
args = redact_tool_args_for_display(tool_name, args) or args
|
||
is_failure, failure_suffix = _detect_tool_failure(tool_name, result)
|
||
render = _CUTE_LINES.get(tool_name)
|
||
rows = _cute_bridge_rows(tool_name, args)
|
||
if rows is None:
|
||
body = render(args, result) if render else f"┊ ⚡ {tool_name[:9]:9} {_cute_trunc(build_tool_preview(tool_name, args) or '')}"
|
||
rows, suffixes = [body], [failure_suffix if is_failure else ""]
|
||
else:
|
||
suffixes = _bridge_row_suffixes(len(rows), result, failure_suffix if is_failure else "")
|
||
rows = [*rows[:-1], f"{rows[-1]} {duration:.1f}s"]
|
||
prefix = get_skin_tool_prefix()
|
||
return "\n ".join(f"{row}{suffix}".replace("┊", prefix, 1) for row, suffix in zip(rows, suffixes))
|
||
|
||
|
||
def get_cute_tool_message(tool_name: str, args: dict, duration: float, result: str | None = None) -> str:
|
||
"""Render a completion label without letting cosmetic failures escape."""
|
||
try:
|
||
return _get_cute_tool_message(tool_name, args, duration, result=result)
|
||
except Exception as exc: # noqa: BLE001 — display must never abort a turn
|
||
logger.debug("Tool completion label failed for %s: %s", tool_name, exc)
|
||
safe_name = tool_name[:9] if isinstance(tool_name, str) and tool_name else t("display.cute.fallback_tool_name")
|
||
safe_duration = f"{duration:.1f}s" if isinstance(duration, (int, float)) else t("display.cute.fallback_done")
|
||
return t("display.cute.completed", tool=f"{safe_name:9}", duration=safe_duration)
|
||
|