answer42 0.8.0__tar.gz → 0.9.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {answer42-0.8.0 → answer42-0.9.0}/PKG-INFO +2 -2
- {answer42-0.8.0 → answer42-0.9.0}/README.md +1 -1
- {answer42-0.8.0 → answer42-0.9.0}/docs/architecture.md +12 -2
- {answer42-0.8.0 → answer42-0.9.0}/pyproject.toml +1 -1
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/assets/MCPTestClient.cf +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/assets/MCPTestManager.cf +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/html_agent.py +31 -8
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/server.py +295 -15
- {answer42-0.8.0 → answer42-0.9.0}/.gitignore +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/LICENSE +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/credentials.example.json +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/docs/agent-installation.md +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/docs/assets/answer42-logo.png +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/docs/assets/platform42-logo.svg +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/docs/installation.md +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/scripts/build_cf.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/scripts/e2e_http_smoke.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/scripts/e2e_stable.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/scripts/openclaw_mcp_autoreload.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/scripts/rag_cli.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/scripts/read_webclient_start_info.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/cf/ConfigDumpInfo.xml +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/cf/Configuration.xml +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/cf/DataProcessors/MCPTestManager/Ext/ObjectModule.bsl +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/cf/DataProcessors/MCPTestManager/Forms//320/244/320/276/321/200/320/274/320/260/Ext/Form/Module.bsl" +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/cf/DataProcessors/MCPTestManager/Forms//320/244/320/276/321/200/320/274/320/260/Ext/Form.xml" +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/cf/DataProcessors/MCPTestManager/Forms//320/244/320/276/321/200/320/274/320/260.xml" +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/cf/DataProcessors/MCPTestManager.xml +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/cf/Ext/ManagedApplicationModule.bsl +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/cf/Languages//320/240/321/203/321/201/321/201/320/272/320/270/320/271.xml" +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/client_cf/Catalogs//320/237/320/241_/320/222/320/273/320/260/320/264/320/265/320/273/320/265/321/206.xml" +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/client_cf/Catalogs//320/237/320/241_/320/241/320/277/321/200/320/260/320/262/320/276/321/207/320/275/320/270/320/2721.xml" +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/client_cf/ConfigDumpInfo.xml +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/client_cf/Configuration.xml +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/client_cf/Languages//320/240/321/203/321/201/321/201/320/272/320/270/320/271.xml" +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/client_cf/Reports//320/237/320/241_/320/241/320/277/320/270/321/201/320/276/320/272/320/255/320/273/320/265/320/274/320/265/320/275/321/202/320/276/320/262/Ext/ManagerModule.bsl" +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/client_cf/Reports//320/237/320/241_/320/241/320/277/320/270/321/201/320/276/320/272/320/255/320/273/320/265/320/274/320/265/320/275/321/202/320/276/320/262/Ext/ObjectModule.bsl" +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/client_cf/Reports//320/237/320/241_/320/241/320/277/320/270/321/201/320/276/320/272/320/255/320/273/320/265/320/274/320/265/320/275/321/202/320/276/320/262/Templates//320/236/321/201/320/275/320/276/320/262/320/275/320/260/321/217/320/241/321/205/320/265/320/274/320/260/320/232/320/276/320/274/320/277/320/276/320/275/320/276/320/262/320/272/320/270/320/224/320/260/320/275/320/275/321/213/321/205/Ext/Template.xml" +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/client_cf/Reports//320/237/320/241_/320/241/320/277/320/270/321/201/320/276/320/272/320/255/320/273/320/265/320/274/320/265/320/275/321/202/320/276/320/262/Templates//320/236/321/201/320/275/320/276/320/262/320/275/320/260/321/217/320/241/321/205/320/265/320/274/320/260/320/232/320/276/320/274/320/277/320/276/320/275/320/276/320/262/320/272/320/270/320/224/320/260/320/275/320/275/321/213/321/205.xml" +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/client_cf/Reports//320/237/320/241_/320/241/320/277/320/270/321/201/320/276/320/272/320/255/320/273/320/265/320/274/320/265/320/275/321/202/320/276/320/262.xml" +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/__init__.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/assets/__init__.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/auth.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/bridge.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/credentials.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/credentials_cli.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/os_support.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/platform.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/protocol.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/rag/__init__.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/rag/detect.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/rag/dump.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/rag/model.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/rag/parsers.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/rag/service.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/rag/store.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/rag/summary_backend.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/rag/summary_vector.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/recorder.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/release_helper.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/runtime.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/skill_installer.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/tool_groups.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/webclient_probe.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/webkit_patch.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/win_desktop.py +0 -0
- {answer42-0.8.0 → answer42-0.9.0}/src/mcp_1c/window_control.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: answer42
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.9.0
|
|
4
4
|
Summary: Answer42 — The Answer to Life, Universe, and 1C — UI Driver. MCP-powered 1C:Enterprise UI automation: click, fill, navigate, test, and introspect managed forms through the test-client API
|
|
5
5
|
Author: Marvin (AI Assistant), 42Clouds, and contributors
|
|
6
6
|
Author-email: "Kosolapov Stanislav (proDOOMman)" <prodoomman@gmail.com>
|
|
@@ -107,7 +107,7 @@ start_session(
|
|
|
107
107
|
- `fields="minimal|navigation|diagnostic|data|full"` (или свой список полей через запятую) управляет содержимым узлов без обрезки дерева.
|
|
108
108
|
- `command_panels="include|exclude|only"` явно управляет сериализацией командных панелей; `only` возвращает плоский список без повторов.
|
|
109
109
|
- `group_mode="include|flatten|flatten_layout|exclude|exclude_empty|pages_only"` определяет, сохраняются ли узлы групп, поднимаются ли их элементы на уровень выше или группы опускаются.
|
|
110
|
-
- `format="json|
|
|
110
|
+
- `format="outline|json|yaml|yml"`: по умолчанию `outline` — одна строка с отступом на узел, `Тип Имя — Заголовок [состояние] ключ=значение`. В состоянии перечисляется только отличие от обычного (`not_visible`, `not_available`, `read_only`, `current`…), остальные поля узла идут парами `ключ=значение`, так что outline несёт те же сведения, что и JSON, но обходится в разы дешевле. `json` возвращает вложенные объекты. Неверные значения профиля, группировки, командных панелей и формата отклоняются; `tree_summary` содержит число узлов и разбивку по точному типу клиента тестирования 1С (нулевые счётчики опускаются), а замеры времени и размера (`metrics`) возвращаются только с `include_timings=true`.
|
|
111
111
|
|
|
112
112
|
### Большие снимки `ui_tree` как ресурсы
|
|
113
113
|
|
|
@@ -65,7 +65,7 @@ start_session(
|
|
|
65
65
|
- `fields="minimal|navigation|diagnostic|data|full"` (или свой список полей через запятую) управляет содержимым узлов без обрезки дерева.
|
|
66
66
|
- `command_panels="include|exclude|only"` явно управляет сериализацией командных панелей; `only` возвращает плоский список без повторов.
|
|
67
67
|
- `group_mode="include|flatten|flatten_layout|exclude|exclude_empty|pages_only"` определяет, сохраняются ли узлы групп, поднимаются ли их элементы на уровень выше или группы опускаются.
|
|
68
|
-
- `format="json|
|
|
68
|
+
- `format="outline|json|yaml|yml"`: по умолчанию `outline` — одна строка с отступом на узел, `Тип Имя — Заголовок [состояние] ключ=значение`. В состоянии перечисляется только отличие от обычного (`not_visible`, `not_available`, `read_only`, `current`…), остальные поля узла идут парами `ключ=значение`, так что outline несёт те же сведения, что и JSON, но обходится в разы дешевле. `json` возвращает вложенные объекты. Неверные значения профиля, группировки, командных панелей и формата отклоняются; `tree_summary` содержит число узлов и разбивку по точному типу клиента тестирования 1С (нулевые счётчики опускаются), а замеры времени и размера (`metrics`) возвращаются только с `include_timings=true`.
|
|
69
69
|
|
|
70
70
|
### Большие снимки `ui_tree` как ресурсы
|
|
71
71
|
|
|
@@ -138,7 +138,7 @@ flowchart LR
|
|
|
138
138
|
end
|
|
139
139
|
```
|
|
140
140
|
|
|
141
|
-
**Windows.** Встроенный WebKit (старый Windows-порт WebKit1) не имеет сервера удалённой отладки, но в нём включены developer extras. `find_webviews` перечисляет окна `WebViewWindowClass` процесса тест-клиента (на скрытом рабочем столе — через `EnumDesktopWindows`). Для каждого нового WebView Answer42 отправляет Ctrl+Alt+Shift+F12. Модификаторы попадают в состояние клавиатуры потока окна (`AttachThreadInput` + `SetKeyboardState`), а сами клавиши отправляются `SendMessageTimeout`: вызов возвращается, когда окно обработало сообщение, поэтому паузы не нужны (`SendInput` на скрытый рабочий стол не доходит). 1С встраивает интерфейс инспектора в форму ещё одним WebView; всё, что появилось после горячей клавиши, запоминается как интерфейс инспектора и само не инспектируется. Признак того, что интерфейс загрузился, — заголовок скрытого окна `WebInspectorWindowClass`: WebKit меняет его на «Web Inspector — <адрес>», когда интерфейс сообщает адрес страницы (около 1,4 с после горячей клавиши).
|
|
141
|
+
**Windows.** Встроенный WebKit (старый Windows-порт WebKit1) не имеет сервера удалённой отладки, но в нём включены developer extras. `find_webviews` перечисляет окна `WebViewWindowClass` процесса тест-клиента (на скрытом рабочем столе — через `EnumDesktopWindows`). Для каждого нового WebView Answer42 отправляет Ctrl+Alt+Shift+F12. Модификаторы попадают в состояние клавиатуры потока окна (`AttachThreadInput` + `SetKeyboardState`), а сами клавиши отправляются `SendMessageTimeout`: вызов возвращается, когда окно обработало сообщение, поэтому паузы не нужны (`SendInput` на скрытый рабочий стол не доходит). 1С встраивает интерфейс инспектора в форму ещё одним WebView; всё, что появилось после горячей клавиши, запоминается как интерфейс инспектора и само не инспектируется. Если за 3 с интерфейс инспектора не появился, клавиша нажимается снова (`HOTKEY_REPEAT_SECONDS`; повторное нажатие безопасно — инспектор открывается один); если WebView поля за это время исчезло (клиент пересоздал поле), `open_inspectors` сразу делает второй проход по актуальному списку WebView. Признак того, что интерфейс загрузился, — заголовок скрытого окна `WebInspectorWindowClass`: WebKit меняет его на «Web Inspector — <адрес>», когда интерфейс сообщает адрес страницы (около 1,4 с после горячей клавиши).
|
|
142
142
|
|
|
143
143
|
Дальше `_type_into_console`: `WM_SETFOCUS` делает интерфейс инспектора активным для WebKit, не трогая фокус внутри его документа; Ctrl+Alt+C открывает вкладку Console, которая сама ставит фокус в строку ввода (инспектор запоминает вкладку). На вкладку Elements ввод попадать не должен: её дерево DOM забирает фокус, когда догружается, и набранные в нём клавиши, особенно Enter, правят DOM страницы. Esc тоже нельзя — его первой обрабатывает 1С и закрывает форму. Загрузчик `loader_js` (около 110 символов) вводится за комментарием `//`: автодополнение консоли асинхронно отвечает на набранный код и может заменить набранное после него, но внутри комментария не срабатывает. Home и два Delete снимают `//`, Enter выполняет строку. Загрузчик открывает WebSocket с одноразовым токеном в адресе, сервер в ответ присылает `PAGE_BRIDGE_JS`, который выполняет присланные выражения через `eval`. Подключение к странице занимает около 2–3 секунд; время по этапам — в `last_connect` статуса моста. Мост живёт в странице: после перезагрузки следующий вызов вводит загрузчик заново.
|
|
144
144
|
|
|
@@ -299,4 +299,14 @@ MCP-инструмент `rag_sources_add_from_directory(path, watch=true)` ищ
|
|
|
299
299
|
- `parent_name` — сериализует только поддерево элемента с указанным техническим именем.
|
|
300
300
|
- `name`, `title`, `type` — фильтры узлов; при активных фильтрах возвращается плоский список `objects`, а на актуальных версиях протокола фильтрация выполняется в менеджере 1С.
|
|
301
301
|
- `group_mode="include|flatten|flatten_layout|exclude|exclude_empty|pages_only"` — возвращать ли узлы групп как обычные узлы, поднимать их элементы или опускать группы.
|
|
302
|
-
- `format="json|
|
|
302
|
+
- `format="outline|json|yaml|yml"` — по умолчанию `outline`: одна строка на узел с теми же полями, что и в JSON (состояние — только отличия от обычного, остальное — `ключ=значение`); `json` — вложенные объекты, YAML — читаемый текст. Аргументы режимов строго проверяются; `metrics` с замерами времени и объёма возвращаются только с `include_timings=true`.
|
|
303
|
+
|
|
304
|
+
## Экономия токенов в ответах
|
|
305
|
+
|
|
306
|
+
Ответы переформатируются на границе MCP (`_shape_tool_payload`), внутренняя логика продолжает читать полный результат менеджера:
|
|
307
|
+
|
|
308
|
+
- `table_rows` отдаёт `columns` один раз и `rows` массивами ячеек; `columns=...` выбирает колонки, ячейки длиннее `max_cell_chars` (500) обрезаются с явной пометкой `…[+N chars]` и счётчиком `truncated_cells`, `max_cell_chars=0` отключает обрезку;
|
|
309
|
+
- строки в ответах `table_current_row`, `table_add_row`, `table_find_row`, `choose_current_row` приходят как `values` (заголовок → текст), без дублей;
|
|
310
|
+
- `search_stats`, `search_ms`, `press_ms` и `metrics` возвращаются только с `include_timings=true`;
|
|
311
|
+
- пары `window_title_before/after`, `form_name_before/after` остаются только там, где значение изменилось и не повторяет `client_diagnostics`;
|
|
312
|
+
- `start_session` возвращает сессию, версию, конфигурацию, расширения и окно клиента; порты, pid, дисплеи и каталоги доступны через `session_status`.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "answer42"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.9.0"
|
|
4
4
|
description = "Answer42 — The Answer to Life, Universe, and 1C — UI Driver. MCP-powered 1C:Enterprise UI automation: click, fill, navigate, test, and introspect managed forms through the test-client API"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.11"
|
|
Binary file
|
|
Binary file
|
|
@@ -54,6 +54,7 @@ LOGGER = logging.getLogger(__name__)
|
|
|
54
54
|
WEBVIEW_CLASS = "WebViewWindowClass"
|
|
55
55
|
INSPECTOR_WINDOW_CLASS = "WebInspectorWindowClass"
|
|
56
56
|
INSPECTOR_OPEN_SECONDS = 10.0 # only a limit: the first opening after a cold start can take several seconds
|
|
57
|
+
HOTKEY_REPEAT_SECONDS = 3.0 # no new front end by then: press the inspector hot key again
|
|
57
58
|
CONNECT_TIMEOUT_SECONDS = 15.0
|
|
58
59
|
# The first evaluation in a fresh console can take a second; then the loader is typed again.
|
|
59
60
|
RETYPE_SECONDS = 2.0
|
|
@@ -299,6 +300,10 @@ class HtmlAgentError(RuntimeError):
|
|
|
299
300
|
pass
|
|
300
301
|
|
|
301
302
|
|
|
303
|
+
class ViewGoneError(HtmlAgentError):
|
|
304
|
+
"""The WebKit view was destroyed (the client recreated the field) before its inspector opened."""
|
|
305
|
+
|
|
306
|
+
|
|
302
307
|
def _protocol_value(reply: dict[str, Any]) -> Any:
|
|
303
308
|
"""The JSON value of a Runtime.evaluate reply (returnByValue)."""
|
|
304
309
|
if "error" in reply:
|
|
@@ -975,6 +980,7 @@ class HtmlInspector:
|
|
|
975
980
|
self._front_ends: dict[int, int] = {}
|
|
976
981
|
self._known_front_ends: set[int] = set()
|
|
977
982
|
self._attempts: dict[int, int] = {}
|
|
983
|
+
self._view_gone = False # Windows: a view disappeared while open_inspectors was opening it
|
|
978
984
|
self._open_lock = asyncio.Lock()
|
|
979
985
|
self.last_connect: dict[str, Any] = {} # Windows: timings of the latest page connection
|
|
980
986
|
# remote: the client is started with its WebKit remote inspector server on this port.
|
|
@@ -1196,14 +1202,19 @@ class HtmlInspector:
|
|
|
1196
1202
|
async with self._open_lock:
|
|
1197
1203
|
return await self._open_linux_local()
|
|
1198
1204
|
async with self._open_lock:
|
|
1199
|
-
live = {p.hwnd for p in self.pages.values() if not p.closed}
|
|
1200
1205
|
opened: list[str] = []
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1206
|
+
# A second pass picks up the view that replaced one which disappeared while it was opened.
|
|
1207
|
+
for _ in range(2):
|
|
1208
|
+
self._view_gone = False
|
|
1209
|
+
live = {p.hwnd for p in self.pages.values() if not p.closed}
|
|
1210
|
+
for view in await self._views():
|
|
1211
|
+
if view in self._known_front_ends or view in live or self._attempts.get(view, 0) >= self.MAX_ATTEMPTS:
|
|
1212
|
+
continue
|
|
1213
|
+
page = await self._connect(view)
|
|
1214
|
+
if page is not None:
|
|
1215
|
+
opened.append(page.page_id)
|
|
1216
|
+
if not self._view_gone:
|
|
1217
|
+
break
|
|
1207
1218
|
return opened
|
|
1208
1219
|
|
|
1209
1220
|
async def _open_remote(self) -> list[str]:
|
|
@@ -1297,11 +1308,20 @@ class HtmlInspector:
|
|
|
1297
1308
|
inspectors = set(await asyncio.to_thread(find_inspector_windows, self.desktop, self.client_pid))
|
|
1298
1309
|
await asyncio.to_thread(_run_on_client_desktop, self.desktop, lambda: _press_inspector_hotkey(view))
|
|
1299
1310
|
deadline = time.monotonic() + INSPECTOR_OPEN_SECONDS
|
|
1311
|
+
repress_at = time.monotonic() + HOTKEY_REPEAT_SECONDS
|
|
1300
1312
|
new: set[int] = set()
|
|
1301
1313
|
loaded = False
|
|
1302
1314
|
while not (new and loaded) and time.monotonic() < deadline:
|
|
1303
1315
|
await asyncio.sleep(0.05)
|
|
1304
|
-
|
|
1316
|
+
current = set(await self._views())
|
|
1317
|
+
new = new or current - views
|
|
1318
|
+
if not new and view not in current:
|
|
1319
|
+
raise ViewGoneError(f"WebKit view {view} disappeared before its inspector opened")
|
|
1320
|
+
if not new and time.monotonic() >= repress_at:
|
|
1321
|
+
# A hot key the field missed (seen once right after a modal dialog closed) is not
|
|
1322
|
+
# repeated by anyone else; pressing it again is harmless: one inspector opens either way.
|
|
1323
|
+
await asyncio.to_thread(_run_on_client_desktop, self.desktop, lambda: _press_inspector_hotkey(view))
|
|
1324
|
+
repress_at = time.monotonic() + HOTKEY_REPEAT_SECONDS
|
|
1305
1325
|
titles = await asyncio.to_thread(find_inspector_windows, self.desktop, self.client_pid)
|
|
1306
1326
|
loaded = any(title for hwnd, title in titles.items() if hwnd not in inspectors)
|
|
1307
1327
|
# Whatever appeared is a front end and must never be inspected itself.
|
|
@@ -1366,6 +1386,9 @@ class HtmlInspector:
|
|
|
1366
1386
|
except (HtmlAgentError, TimeoutError) as exc:
|
|
1367
1387
|
self.last_error = str(exc) or f"The page of WebKit view {view} did not connect within {CONNECT_TIMEOUT_SECONDS:g}s"
|
|
1368
1388
|
LOGGER.warning("%s", self.last_error)
|
|
1389
|
+
if isinstance(exc, ViewGoneError):
|
|
1390
|
+
self._view_gone = True
|
|
1391
|
+
self._attempts.pop(view, None)
|
|
1369
1392
|
return None
|
|
1370
1393
|
finally:
|
|
1371
1394
|
self._tokens.pop(token, None)
|
|
@@ -2620,7 +2620,7 @@ _UI_TREE_RAG_AUTO_PROFILES = {"diagnostic", "data", "full"}
|
|
|
2620
2620
|
def _validate_ui_tree_choice(kind: str, value: str, allowed: set[str]) -> str:
|
|
2621
2621
|
normalized = (value or "").strip().lower()
|
|
2622
2622
|
if not normalized:
|
|
2623
|
-
normalized = "
|
|
2623
|
+
normalized = "outline" if kind == "format" else "auto" if kind == "command_panels" else "include" if kind == "group_mode" else "navigation"
|
|
2624
2624
|
if normalized not in allowed:
|
|
2625
2625
|
allowed_text = ", ".join(sorted(allowed))
|
|
2626
2626
|
raise ValueError(f"Unsupported ui_tree {kind}: {value!r}. Expected one of: {allowed_text}.")
|
|
@@ -2702,7 +2702,31 @@ def _attach_optional_timings(result: Any, timings: dict[str, Any] | None, includ
|
|
|
2702
2702
|
return result
|
|
2703
2703
|
|
|
2704
2704
|
|
|
2705
|
+
_OUTLINE_LABEL_KEYS = {"type", "name", "title", "children", "objects"}
|
|
2706
|
+
_OUTLINE_FLAGS = (
|
|
2707
|
+
("visible", False, "not_visible"), ("available", False, "not_available"), ("enabled", False, "disabled"),
|
|
2708
|
+
("read_only", True, "read_only"), ("current", True, "current"), ("selected", True, "selected"),
|
|
2709
|
+
("main", True, "main"), ("home", True, "home"),
|
|
2710
|
+
)
|
|
2711
|
+
_OUTLINE_SKIPPED_KEYS = (
|
|
2712
|
+
_OUTLINE_LABEL_KEYS | {key for key, _, _ in _OUTLINE_FLAGS}
|
|
2713
|
+
| {"metrics", "_tree_ms", "_nodes_serialized", "_nodes_visited", "flat", "tree_summary", "rag_diagnostic", "root_parent_name"}
|
|
2714
|
+
)
|
|
2715
|
+
|
|
2716
|
+
|
|
2717
|
+
def _outline_attribute(key: str, value: Any) -> str:
|
|
2718
|
+
if key == "pages" and isinstance(value, list):
|
|
2719
|
+
value = [str(page.get("name") or page.get("title") or "") if isinstance(page, dict) else str(page) for page in value]
|
|
2720
|
+
if isinstance(value, (dict, list)):
|
|
2721
|
+
return f"{key}=" + json.dumps(value, ensure_ascii=False, separators=(",", ":"), default=str)
|
|
2722
|
+
if isinstance(value, str):
|
|
2723
|
+
return f"{key}=" + json.dumps(value, ensure_ascii=False)
|
|
2724
|
+
return f"{key}={_yaml_scalar(value)}"
|
|
2725
|
+
|
|
2726
|
+
|
|
2705
2727
|
def _outline_ui_tree(node: Any, indent: int = 0) -> str:
|
|
2728
|
+
"""One line per node: type, name, title, then only the state that differs from the defaults
|
|
2729
|
+
(visible, available, not read-only) and every other field the node carries as key=value."""
|
|
2706
2730
|
if not isinstance(node, dict):
|
|
2707
2731
|
return ""
|
|
2708
2732
|
label_parts = [str(node.get("type") or "Object")]
|
|
@@ -2710,15 +2734,18 @@ def _outline_ui_tree(node: Any, indent: int = 0) -> str:
|
|
|
2710
2734
|
label_parts.append(str(node["name"]))
|
|
2711
2735
|
if node.get("title") and node.get("title") != node.get("name"):
|
|
2712
2736
|
label_parts.append(f"— {node['title']}")
|
|
2713
|
-
flags = []
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
flags.append(mark)
|
|
2717
|
-
elif node.get(key) is False and key in node:
|
|
2718
|
-
flags.append(f"not_{mark}")
|
|
2737
|
+
flags = [mark for key, flagged, mark in _OUTLINE_FLAGS if key in node and node.get(key) is flagged]
|
|
2738
|
+
if "disabled" in flags and "not_available" in flags:
|
|
2739
|
+
flags.remove("disabled")
|
|
2719
2740
|
line = " " * indent + "- " + " ".join(label_parts)
|
|
2720
2741
|
if flags:
|
|
2721
2742
|
line += " [" + ", ".join(flags) + "]"
|
|
2743
|
+
for key, value in node.items():
|
|
2744
|
+
if key in _OUTLINE_SKIPPED_KEYS or value in (None, "", [], {}):
|
|
2745
|
+
continue
|
|
2746
|
+
if key == "current_page" and node.get("current_page_name"):
|
|
2747
|
+
continue
|
|
2748
|
+
line += " " + _outline_attribute(key, value)
|
|
2722
2749
|
lines = [line]
|
|
2723
2750
|
for child in node.get("children") or []:
|
|
2724
2751
|
child_text = _outline_ui_tree(child, indent + 1)
|
|
@@ -3028,7 +3055,7 @@ def _compact_rows_result(result: Any, *, include_raw: bool = False) -> Any:
|
|
|
3028
3055
|
compact = {key: row[key] for key in ("index", "row", "current", "selected", "expanded", "level") if key in row}
|
|
3029
3056
|
pairs = row.get("pairs")
|
|
3030
3057
|
if isinstance(pairs, list):
|
|
3031
|
-
compact["values"] =
|
|
3058
|
+
compact["values"] = _row_values_from_pairs(pairs)
|
|
3032
3059
|
compact_rows.append(compact)
|
|
3033
3060
|
out = dict(result)
|
|
3034
3061
|
out["rows"] = compact_rows
|
|
@@ -3036,6 +3063,84 @@ def _compact_rows_result(result: Any, *, include_raw: bool = False) -> Any:
|
|
|
3036
3063
|
return out
|
|
3037
3064
|
|
|
3038
3065
|
|
|
3066
|
+
TABLE_ROWS_MAX_CELL_CHARS = 500
|
|
3067
|
+
|
|
3068
|
+
|
|
3069
|
+
def _normalize_column_title(value: Any) -> str:
|
|
3070
|
+
return re.sub(r"\s+", " ", str(value)).strip().casefold()
|
|
3071
|
+
|
|
3072
|
+
|
|
3073
|
+
def _parse_columns_argument(columns: str) -> list[str]:
|
|
3074
|
+
text = (columns or "").strip()
|
|
3075
|
+
if not text:
|
|
3076
|
+
return []
|
|
3077
|
+
if text.startswith("["):
|
|
3078
|
+
return [str(item) for item in _json_array_argument(text, "columns")]
|
|
3079
|
+
return [part.strip() for part in text.split(",") if part.strip()]
|
|
3080
|
+
|
|
3081
|
+
|
|
3082
|
+
def _columnar_rows_result(result: Any, *, columns: str = "", max_cell_chars: int = TABLE_ROWS_MAX_CELL_CHARS) -> Any:
|
|
3083
|
+
"""Column titles once + one array of cells per row, instead of repeating every title in every row.
|
|
3084
|
+
|
|
3085
|
+
Nothing is dropped silently: a cut cell ends with ``…[+N chars]`` and the
|
|
3086
|
+
response says how many cells were cut and how to read them in full.
|
|
3087
|
+
"""
|
|
3088
|
+
if not isinstance(result, dict) or not isinstance(result.get("rows"), list):
|
|
3089
|
+
return result
|
|
3090
|
+
rows = result["rows"]
|
|
3091
|
+
if not all(isinstance(row, dict) and isinstance(row.get("values"), dict) for row in rows):
|
|
3092
|
+
return result
|
|
3093
|
+
available: list[str] = []
|
|
3094
|
+
for row in rows:
|
|
3095
|
+
for title in row["values"]:
|
|
3096
|
+
if title not in available:
|
|
3097
|
+
available.append(title)
|
|
3098
|
+
selected = available
|
|
3099
|
+
unknown: list[str] = []
|
|
3100
|
+
requested = _parse_columns_argument(columns)
|
|
3101
|
+
if requested:
|
|
3102
|
+
by_title = {_normalize_column_title(title): title for title in available}
|
|
3103
|
+
selected = []
|
|
3104
|
+
for name in requested:
|
|
3105
|
+
title = by_title.get(_normalize_column_title(name))
|
|
3106
|
+
if title is None:
|
|
3107
|
+
unknown.append(name)
|
|
3108
|
+
elif title not in selected:
|
|
3109
|
+
selected.append(title)
|
|
3110
|
+
limit = max(0, int(max_cell_chars or 0))
|
|
3111
|
+
truncated = 0
|
|
3112
|
+
out_rows: list[Any] = []
|
|
3113
|
+
with_attributes = any(len(row) > 1 for row in rows)
|
|
3114
|
+
for row in rows:
|
|
3115
|
+
cells: list[Any] = []
|
|
3116
|
+
for title in selected:
|
|
3117
|
+
cell = row["values"].get(title, "")
|
|
3118
|
+
if limit and isinstance(cell, str) and len(cell) > limit:
|
|
3119
|
+
cell = f"{cell[:limit]}…[+{len(cell) - limit} chars]"
|
|
3120
|
+
truncated += 1
|
|
3121
|
+
cells.append(cell)
|
|
3122
|
+
if with_attributes:
|
|
3123
|
+
out_rows.append({**{key: value for key, value in row.items() if key != "values"}, "cells": cells})
|
|
3124
|
+
else:
|
|
3125
|
+
out_rows.append(cells)
|
|
3126
|
+
out = {key: value for key, value in result.items() if key not in ("rows", "rows_count")}
|
|
3127
|
+
out["columns"] = selected
|
|
3128
|
+
out["rows"] = out_rows
|
|
3129
|
+
if result.get("count") != len(out_rows):
|
|
3130
|
+
out["rows_count"] = len(out_rows)
|
|
3131
|
+
if requested and len(selected) < len(available):
|
|
3132
|
+
out["other_columns"] = [title for title in available if title not in selected]
|
|
3133
|
+
if unknown:
|
|
3134
|
+
out["unknown_columns"] = unknown
|
|
3135
|
+
if truncated:
|
|
3136
|
+
out["truncated_cells"] = truncated
|
|
3137
|
+
out["truncation"] = (
|
|
3138
|
+
f"cells longer than max_cell_chars={limit} end with '…[+N chars]'; "
|
|
3139
|
+
"repeat with max_cell_chars=0 (and columns=...) to read them in full"
|
|
3140
|
+
)
|
|
3141
|
+
return out
|
|
3142
|
+
|
|
3143
|
+
|
|
3039
3144
|
def _compact_tabular_text_result(result: Any, *, include_raw: bool = False) -> Any:
|
|
3040
3145
|
if include_raw or not isinstance(result, dict):
|
|
3041
3146
|
return result
|
|
@@ -4057,7 +4162,156 @@ def _compact_payload(value: Any, *, strip_subtrees: bool = False, parent_key: st
|
|
|
4057
4162
|
return _compact_outbound_ui_node(compact) if _is_ui_node(compact) else compact
|
|
4058
4163
|
|
|
4059
4164
|
|
|
4060
|
-
|
|
4165
|
+
# Diagnostics of how the manager found a control: useful when profiling, noise otherwise.
|
|
4166
|
+
_TIMING_ONLY_KEYS = {"search_stats", "search_ms", "press_ms"}
|
|
4167
|
+
_UI_TREE_ECHO_KEYS = {
|
|
4168
|
+
"filter", "profile", "fields", "command_panels", "flat", "method", "metrics",
|
|
4169
|
+
"_tree_ms", "_nodes_serialized", "_nodes_visited",
|
|
4170
|
+
}
|
|
4171
|
+
_START_SESSION_INFRA_KEYS = {
|
|
4172
|
+
"platform_dir", "display", "client_display", "ws_port", "ibsrv_port", "testclient_port", "data_dir",
|
|
4173
|
+
"bridge_url", "manager_pid", "ws_url", "log_dir", "server_rag_enabled",
|
|
4174
|
+
}
|
|
4175
|
+
_START_SESSION_CLIENT_INFRA_KEYS = {
|
|
4176
|
+
"connection_mode", "connection_value", "target_connection_mode", "port", "client_pid", "client_log",
|
|
4177
|
+
"client_stdout_log", "auto_maximize",
|
|
4178
|
+
}
|
|
4179
|
+
|
|
4180
|
+
|
|
4181
|
+
def _row_values_from_pairs(pairs: list[Any]) -> dict[str, Any]:
|
|
4182
|
+
"""Column title -> cell text; a repeated title gets a numeric suffix instead of overwriting the first cell."""
|
|
4183
|
+
values: dict[str, Any] = {}
|
|
4184
|
+
for pair in pairs:
|
|
4185
|
+
if not isinstance(pair, dict):
|
|
4186
|
+
continue
|
|
4187
|
+
key = str(pair.get("key", ""))
|
|
4188
|
+
value = pair.get("value", "")
|
|
4189
|
+
if not key and value in ("", None):
|
|
4190
|
+
continue
|
|
4191
|
+
unique, number = key, 1
|
|
4192
|
+
while unique in values:
|
|
4193
|
+
number += 1
|
|
4194
|
+
unique = f"{key} ({number})"
|
|
4195
|
+
values[unique] = value
|
|
4196
|
+
return values
|
|
4197
|
+
|
|
4198
|
+
|
|
4199
|
+
def _is_pairs_list(value: Any) -> bool:
|
|
4200
|
+
return isinstance(value, list) and all(isinstance(item, dict) and "key" in item for item in value)
|
|
4201
|
+
|
|
4202
|
+
|
|
4203
|
+
def _shape_outbound_value(value: Any, *, keep_timings: bool, keep_pairs: bool) -> Any:
|
|
4204
|
+
"""Lossless reshaping applied to every tool response on its way to the client."""
|
|
4205
|
+
if isinstance(value, list):
|
|
4206
|
+
return [_shape_outbound_value(item, keep_timings=keep_timings, keep_pairs=keep_pairs) for item in value]
|
|
4207
|
+
if not isinstance(value, dict):
|
|
4208
|
+
return value
|
|
4209
|
+
shaped: dict[str, Any] = {}
|
|
4210
|
+
for key, item in value.items():
|
|
4211
|
+
if not keep_timings and key in _TIMING_ONLY_KEYS:
|
|
4212
|
+
continue
|
|
4213
|
+
if key == "pairs" and not keep_pairs and _is_pairs_list(item):
|
|
4214
|
+
shaped.setdefault("values", {}).update(_row_values_from_pairs(item))
|
|
4215
|
+
continue
|
|
4216
|
+
shaped[key] = _shape_outbound_value(item, keep_timings=keep_timings, keep_pairs=keep_pairs)
|
|
4217
|
+
return _drop_redundant_window_state(shaped)
|
|
4218
|
+
|
|
4219
|
+
|
|
4220
|
+
def _drop_redundant_window_state(payload: dict[str, Any]) -> dict[str, Any]:
|
|
4221
|
+
"""`*_before`/`*_after` pairs: keep only what differs and what client_diagnostics does not already say."""
|
|
4222
|
+
if "window_title_before" not in payload and "form_name_before" not in payload:
|
|
4223
|
+
return payload
|
|
4224
|
+
diagnostics = payload.get("client_diagnostics") if isinstance(payload.get("client_diagnostics"), dict) else {}
|
|
4225
|
+
for stem, active_key in (("window_title", "active_window_title"), ("form_name", "active_form_name")):
|
|
4226
|
+
before, after = payload.get(f"{stem}_before"), payload.get(f"{stem}_after")
|
|
4227
|
+
if before == after:
|
|
4228
|
+
payload.pop(f"{stem}_before", None)
|
|
4229
|
+
payload.pop(f"{stem}_after", None)
|
|
4230
|
+
continue
|
|
4231
|
+
if before in ("", None):
|
|
4232
|
+
payload.pop(f"{stem}_before", None)
|
|
4233
|
+
if after in ("", None) or after == diagnostics.get(active_key):
|
|
4234
|
+
payload.pop(f"{stem}_after", None)
|
|
4235
|
+
return payload
|
|
4236
|
+
|
|
4237
|
+
|
|
4238
|
+
def _shape_ui_tree_summary(summary: Any) -> Any:
|
|
4239
|
+
if not isinstance(summary, dict):
|
|
4240
|
+
return summary
|
|
4241
|
+
shaped = {key: value for key, value in summary.items() if value not in (0, False, None, "", [], {})}
|
|
4242
|
+
types = shaped.get("types_count")
|
|
4243
|
+
if isinstance(types, dict):
|
|
4244
|
+
# by_family is a coarser view of the same counts.
|
|
4245
|
+
by_type = types.get("by_type")
|
|
4246
|
+
if by_type:
|
|
4247
|
+
shaped["types_count"] = by_type
|
|
4248
|
+
else:
|
|
4249
|
+
shaped.pop("types_count")
|
|
4250
|
+
return shaped
|
|
4251
|
+
|
|
4252
|
+
|
|
4253
|
+
def _shape_ui_tree_response(payload: dict[str, Any], *, keep_timings: bool) -> dict[str, Any]:
|
|
4254
|
+
shaped = {key: value for key, value in payload.items() if keep_timings or key not in _UI_TREE_ECHO_KEYS}
|
|
4255
|
+
for key in ("tree_summary", "summary"):
|
|
4256
|
+
if key in shaped:
|
|
4257
|
+
shaped[key] = _shape_ui_tree_summary(shaped[key])
|
|
4258
|
+
return shaped
|
|
4259
|
+
|
|
4260
|
+
|
|
4261
|
+
def _shape_start_session_response(payload: dict[str, Any]) -> dict[str, Any]:
|
|
4262
|
+
"""Keep what the caller acts on; ports, pids, displays and paths stay in session_status."""
|
|
4263
|
+
shaped = {key: value for key, value in payload.items() if key not in _START_SESSION_INFRA_KEYS}
|
|
4264
|
+
client = shaped.get("test_client")
|
|
4265
|
+
if isinstance(client, dict):
|
|
4266
|
+
client = {key: value for key, value in client.items() if key not in _START_SESSION_CLIENT_INFRA_KEYS}
|
|
4267
|
+
maximized = client.pop("maximized", None)
|
|
4268
|
+
if isinstance(maximized, dict):
|
|
4269
|
+
if isinstance(maximized.get("window"), dict):
|
|
4270
|
+
client["window"] = maximized["window"]
|
|
4271
|
+
if maximized.get("errors"):
|
|
4272
|
+
client["maximize_errors"] = maximized["errors"]
|
|
4273
|
+
shaped["test_client"] = client
|
|
4274
|
+
notice = shaped.get("rag_notice")
|
|
4275
|
+
if isinstance(notice, dict):
|
|
4276
|
+
if not notice.get("enabled"):
|
|
4277
|
+
notice = {key: notice[key] for key in ("enabled", "reason") if key in notice}
|
|
4278
|
+
else:
|
|
4279
|
+
notice = {
|
|
4280
|
+
key: value for key, value in notice.items()
|
|
4281
|
+
if key != "summary_backend" and value not in ("", [], {}, None)
|
|
4282
|
+
and not (key == "message" and value == notice.get("reason"))
|
|
4283
|
+
}
|
|
4284
|
+
shaped["rag_notice"] = notice
|
|
4285
|
+
probe = shaped.get("web_runtime_probe")
|
|
4286
|
+
if isinstance(probe, dict) and (not probe.get("attempted") or probe.get("status") == "not_applicable"):
|
|
4287
|
+
shaped.pop("web_runtime_probe")
|
|
4288
|
+
if not shaped.get("rag_snapshot"):
|
|
4289
|
+
shaped.pop("rag_snapshot", None)
|
|
4290
|
+
return shaped
|
|
4291
|
+
|
|
4292
|
+
|
|
4293
|
+
def _shape_tool_payload(payload: Any, tool_name: str = "", arguments: Any = None) -> Any:
|
|
4294
|
+
arguments = arguments if isinstance(arguments, dict) else {}
|
|
4295
|
+
keep_timings = bool(arguments.get("include_timings"))
|
|
4296
|
+
keep_pairs = arguments.get("compact") is False or _tool_result_verbosity() == "full"
|
|
4297
|
+
payload = _shape_outbound_value(payload, keep_timings=keep_timings, keep_pairs=keep_pairs)
|
|
4298
|
+
if not isinstance(payload, dict):
|
|
4299
|
+
return payload
|
|
4300
|
+
positioning = payload.get("positioning")
|
|
4301
|
+
if isinstance(positioning, dict) and "current_row" in payload and positioning.get("row") == payload["current_row"]:
|
|
4302
|
+
# choose_current_row found the row and made it current: one copy is enough.
|
|
4303
|
+
payload["positioning"] = {key: value for key, value in positioning.items() if key != "row"}
|
|
4304
|
+
if tool_name == "table_cell_text" and isinstance(payload.get("cell"), dict):
|
|
4305
|
+
# The question was one cell; the whole row is table_current_row's answer.
|
|
4306
|
+
payload["cell"] = {key: value for key, value in payload["cell"].items() if key != "current_row"}
|
|
4307
|
+
elif tool_name == "ui_tree":
|
|
4308
|
+
payload = _shape_ui_tree_response(payload, keep_timings=keep_timings)
|
|
4309
|
+
elif tool_name == "start_session":
|
|
4310
|
+
payload = _shape_start_session_response(payload)
|
|
4311
|
+
return payload
|
|
4312
|
+
|
|
4313
|
+
|
|
4314
|
+
def _compact_json_text(text: str, *, strip_subtrees: bool = False, tool_name: str = "", arguments: Any = None) -> str:
|
|
4061
4315
|
stripped = text.lstrip()
|
|
4062
4316
|
if not stripped.startswith(("{", "[")):
|
|
4063
4317
|
return text
|
|
@@ -4065,6 +4319,10 @@ def _compact_json_text(text: str, *, strip_subtrees: bool = False) -> str:
|
|
|
4065
4319
|
payload = json.loads(text)
|
|
4066
4320
|
except ValueError:
|
|
4067
4321
|
return text
|
|
4322
|
+
try:
|
|
4323
|
+
payload = _shape_tool_payload(payload, tool_name, arguments)
|
|
4324
|
+
except Exception: # an unexpected result shape must not cost the caller the result itself
|
|
4325
|
+
logging.getLogger(__name__).exception("Could not shape the %s response", tool_name)
|
|
4068
4326
|
payload = _compact_payload(payload, strip_subtrees=strip_subtrees)
|
|
4069
4327
|
return json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
|
4070
4328
|
|
|
@@ -4098,7 +4356,9 @@ def _compact_tool_result(result: Any, tool_name: str = "", arguments: Any = None
|
|
|
4098
4356
|
if getattr(result, "is_error", False):
|
|
4099
4357
|
block.text = _compact_error_text(block.text)
|
|
4100
4358
|
else:
|
|
4101
|
-
block.text = _compact_json_text(
|
|
4359
|
+
block.text = _compact_json_text(
|
|
4360
|
+
block.text, strip_subtrees=strip_subtrees, tool_name=tool_name, arguments=arguments
|
|
4361
|
+
)
|
|
4102
4362
|
return result
|
|
4103
4363
|
|
|
4104
4364
|
_MCP_TOOL_CALL_ACTIVE: contextvars.ContextVar[bool] = contextvars.ContextVar(
|
|
@@ -5141,6 +5401,8 @@ def sessions_list() -> dict[str, Any]:
|
|
|
5141
5401
|
"configuration_name": sess.configuration_name,
|
|
5142
5402
|
"configuration_version": sess.configuration_version,
|
|
5143
5403
|
"extension_names": sess.extension_names,
|
|
5404
|
+
# пустой список без загрузки каталога значит "не определено", а не "расширений нет": его заполняют installed_extensions_from_catalog и RAG
|
|
5405
|
+
"extension_names_loaded": bool(sess.installed_extensions_cache or sess.extension_names),
|
|
5144
5406
|
"idle_timeout_seconds": sess.idle_timeout_seconds,
|
|
5145
5407
|
})
|
|
5146
5408
|
return {"count": len(items), "sessions": items}
|
|
@@ -5214,6 +5476,8 @@ def session_status(*,
|
|
|
5214
5476
|
"configuration_name": sess.configuration_name,
|
|
5215
5477
|
"configuration_version": sess.configuration_version,
|
|
5216
5478
|
"extension_names": sess.extension_names,
|
|
5479
|
+
# пустой список без загрузки каталога значит "не определено", а не "расширений нет": его заполняют installed_extensions_from_catalog и RAG
|
|
5480
|
+
"extension_names_loaded": bool(sess.installed_extensions_cache or sess.extension_names),
|
|
5217
5481
|
"idle_timeout_seconds": sess.idle_timeout_seconds,
|
|
5218
5482
|
**({"external_opens": opens} if (opens := runtime.external_opens(sess.data_dir)) else {}),
|
|
5219
5483
|
}
|
|
@@ -5691,6 +5955,8 @@ async def start_session(
|
|
|
5691
5955
|
"configuration_name": sess.configuration_name,
|
|
5692
5956
|
"configuration_version": sess.configuration_version,
|
|
5693
5957
|
"extension_names": sess.extension_names,
|
|
5958
|
+
# пустой список без загрузки каталога значит "не определено", а не "расширений нет": его заполняют installed_extensions_from_catalog и RAG
|
|
5959
|
+
"extension_names_loaded": bool(sess.installed_extensions_cache or sess.extension_names),
|
|
5694
5960
|
"web_runtime_probe": web_runtime_probe,
|
|
5695
5961
|
"idle_timeout_seconds": sess.idle_timeout_seconds,
|
|
5696
5962
|
"test_client": _compact_start_test_client_result(connect_result, include_timings=include_timings), **pipeline_info,
|
|
@@ -7573,7 +7839,7 @@ async def ui_tree(
|
|
|
7573
7839
|
title: Annotated[str, "Optional title substring filter. When name, title or type filter is set, ui_tree returns a flat matches list"] = "",
|
|
7574
7840
|
fields: Annotated[str, "Field-set profile: auto, minimal, navigation, diagnostic, data, full, or comma-separated field names"] = "auto",
|
|
7575
7841
|
group_mode: Annotated[str, "Group handling mode: include, flatten, flatten_layout, exclude, exclude_empty, or pages_only"] = "include",
|
|
7576
|
-
format: Annotated[str, "Response format:
|
|
7842
|
+
format: Annotated[str, "Response format: outline (default; one line per node, same fields), json (nested objects), yaml/yml"] = "outline",
|
|
7577
7843
|
rag_snapshot: Annotated[str, "Optional RAG snapshot name/id used for type enrichment"] = "",
|
|
7578
7844
|
delivery: Annotated[str, "Delivery mode: auto (default) returns small results inline and saves responses above token threshold as resource; inline always returns the selected JSON/outline/yaml; resource always saves full JSON and returns resource_uri + summary + preview"] = "auto",
|
|
7579
7845
|
preview_max_nodes: Annotated[int, "For delivery=auto/resource, number of top nodes/matches to include in the small inline preview when a resource is returned"] = 40,
|
|
@@ -7584,7 +7850,9 @@ async def ui_tree(
|
|
|
7584
7850
|
"""Snapshot of the active 1C UI tree.
|
|
7585
7851
|
|
|
7586
7852
|
Default profile `navigation`: visible elements, compact fields, no data, no
|
|
7587
|
-
command panels.
|
|
7853
|
+
command panels, the whole depth. Default format `outline`: one indented line
|
|
7854
|
+
per node, `Type Name — Title [state] key=value`; state lists only what differs
|
|
7855
|
+
from visible/available/not read-only. `parent_name` limits it to a subtree; `name`/`title`/`type`
|
|
7588
7856
|
return a flat `objects` list (for one control prefer find_object). Large
|
|
7589
7857
|
results are saved as a resource (`delivery=auto`); inspect them with
|
|
7590
7858
|
ui_tree_resource_search/get_node/children or ui_tree_diff. For data use
|
|
@@ -7791,6 +8059,8 @@ field_info, table_rows or tabular_documents rather than
|
|
|
7791
8059
|
format_start = time.monotonic()
|
|
7792
8060
|
text = _outline_ui_nodes(result.get("objects", [])) if isinstance(result, dict) and "objects" in result else _outline_ui_tree(result)
|
|
7793
8061
|
response = {"format": "outline", "text": text, "tree_summary": summary, "profile": profile_key, "fields": fields}
|
|
8062
|
+
if isinstance(tree, dict) and tree.get("rag_diagnostic"):
|
|
8063
|
+
response["rag_diagnostic"] = tree["rag_diagnostic"]
|
|
7794
8064
|
if parent_name:
|
|
7795
8065
|
response["parent_name"] = parent_name
|
|
7796
8066
|
metrics = _ui_tree_metrics(tree, bridge_ms=bridge_ms, python_transform_ms=python_transform_ms, format_ms=(time.monotonic() - format_start) * 1000, result=response)
|
|
@@ -7809,6 +8079,8 @@ field_info, table_rows or tabular_documents rather than
|
|
|
7809
8079
|
if fmt == "yaml":
|
|
7810
8080
|
format_start = time.monotonic()
|
|
7811
8081
|
response = {"format": "yaml", "yaml": _to_simple_yaml(result), "tree_summary": summary, "profile": profile_key, "fields": fields}
|
|
8082
|
+
if isinstance(tree, dict) and tree.get("rag_diagnostic"):
|
|
8083
|
+
response["rag_diagnostic"] = tree["rag_diagnostic"]
|
|
7812
8084
|
if parent_name:
|
|
7813
8085
|
response["parent_name"] = parent_name
|
|
7814
8086
|
metrics = _ui_tree_metrics(tree, bridge_ms=bridge_ms, python_transform_ms=python_transform_ms, format_ms=(time.monotonic() - format_start) * 1000, result=response)
|
|
@@ -8902,13 +9174,21 @@ async def table_rows(
|
|
|
8902
9174
|
name: Annotated[str, "Table technical name"] = "",
|
|
8903
9175
|
title: Annotated[str, "Table visible title"] = "",
|
|
8904
9176
|
limit: Annotated[int, "Maximum rows to return"] = 50,
|
|
8905
|
-
compact: Annotated[bool | None, "
|
|
9177
|
+
compact: Annotated[bool | None, "false: raw rows as key/value pairs, without columns/max_cell_chars; default follows ONEC_MCP_RESULT_VERBOSITY"] = None,
|
|
9178
|
+
columns: Annotated[str, "Comma-separated column titles to return (or a JSON array); empty = all columns"] = "",
|
|
9179
|
+
max_cell_chars: Annotated[int, "Cut longer cell texts, marking them '…[+N chars]'; 0 = never cut"] = TABLE_ROWS_MAX_CELL_CHARS,
|
|
8906
9180
|
*,
|
|
8907
9181
|
session_id: Annotated[str, "Session id"] = DEFAULT_SESSION,
|
|
8908
9182
|
) -> Any:
|
|
8909
|
-
"""Return rows of a tested table
|
|
9183
|
+
"""Return rows of a tested table: `columns` (titles, once) and `rows` (arrays of cell texts in column order).
|
|
9184
|
+
|
|
9185
|
+
Rows that carry attributes (index, current, selected, level) are objects
|
|
9186
|
+
with those attributes and `cells`.
|
|
9187
|
+
"""
|
|
8910
9188
|
result = await _bridge_call_recorded(session_id, "table_rows", {"name": name, "title": title, "limit": limit})
|
|
8911
|
-
|
|
9189
|
+
if not _compact_enabled(compact):
|
|
9190
|
+
return result
|
|
9191
|
+
return _columnar_rows_result(_compact_rows_result(result), columns=columns, max_cell_chars=max_cell_chars)
|
|
8912
9192
|
|
|
8913
9193
|
|
|
8914
9194
|
def _table_row_pairs(row: Any) -> dict[str, str]:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|