-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwflow.py
More file actions
1320 lines (1084 loc) · 53.6 KB
/
wflow.py
File metadata and controls
1320 lines (1084 loc) · 53.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
wflow - Workflow Runner
Запускает workflow из YAML файлов с гарантированным выполнением шагов.
Использует iFlow SDK для взаимодействия с iFlow CLI.
Переменные окружения (можно задать в .env файле):
WFLOW_PROJECT_ROOT - Корневая директория проекта (по умолчанию cwd)
WFLOW_WORKFLOWS_DIR - Директория с workflow файлами
WFLOW_PROMPTS_DIR - Директория с файлами промптов
WFLOW_RUNNER_DIR - Директория установки runner (определяется автоматически)
Usage:
python wflow.py # Интерактивный режим
python wflow.py workflow.yaml -i key=value
python wflow.py workflows/code-review.yaml -i branch=feature/my-feature
"""
# =============================================================================
# Bootstrap: Автоматическое переключение на venv если нужно
# =============================================================================
import os
import sys
from pathlib import Path
# Определяем директорию runner
_RUNNER_DIR = Path(__file__).parent.resolve()
# Ищем venv (пробуем оба варианта: .venv и venv)
_VENV_DIR = None
for venv_name in (".venv", "venv"):
candidate = _RUNNER_DIR / venv_name
if candidate.exists():
_VENV_DIR = candidate
break
# Если запущен не из venv, и venv существует — перезапускаем из venv
if _VENV_DIR and not sys.prefix.startswith(str(_VENV_DIR)):
_VENV_PYTHON = _VENV_DIR / "bin" / "python3"
if _VENV_PYTHON.exists():
import subprocess
result = subprocess.run([str(_VENV_PYTHON), __file__] + sys.argv[1:])
sys.exit(result.returncode)
# =============================================================================
# Основной код
# =============================================================================
import argparse
import asyncio
import json
import logging
import re
import socket
import subprocess
import time
from datetime import datetime
from typing import Any
import yaml
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.table import Table
# Rich console для красивого вывода
console = Console()
# Logger для отладки
logger = logging.getLogger(__name__)
# =============================================================================
# ACP Server Check
# =============================================================================
def check_acp_server(host: str = "localhost", port: int = 8090, timeout: float = 2.0) -> bool:
"""Проверяет, запущен ли ACP сервер на указанном порту.
Args:
host: Хост для проверки
port: Порт для проверки
timeout: Таймаут подключения в секундах
Returns:
True если сервер доступен, False иначе
"""
try:
with socket.create_connection((host, port), timeout=timeout):
return True
except OSError:
return False
def find_acp_server(start_port: int = 8090, max_attempts: int = 10) -> int | None:
"""Ищет запущенный ACP сервер, проверяя порты.
Args:
start_port: Начальный порт для проверки
max_attempts: Количество портов для проверки
Returns:
Номер порта если сервер найден, None иначе
"""
for port in range(start_port, start_port + max_attempts):
if check_acp_server("localhost", port):
return port
return None
def start_acp_server(port: int = 8090, timeout: float = 10.0) -> tuple[bool, int | None]:
"""Запускает ACP сервер и ждёт его готовности.
Args:
port: Порт для запуска
timeout: Максимальное время ожидания в секундах
Returns:
Tuple (success, actual_port)
"""
import subprocess
import time
# Проверяем, не занят ли порт
if check_acp_server("localhost", port):
return True, port
# Запускаем iFlow
cmd = ["iflow", "--experimental-acp", "--port", str(port)]
logger.debug(f"Starting iFlow: {' '.join(cmd)}")
try:
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.DEVNULL,
start_new_session=True # Отделяем от текущего процесса
)
except FileNotFoundError:
return False, None
except Exception as e:
logger.error(f"Failed to start iFlow: {e}")
return False, None
# Ждём готовности с информативным выводом
start_time = time.time()
check_interval = 0.5
while time.time() - start_time < timeout:
if check_acp_server("localhost", port):
return True, port
# Проверяем, не упал ли процесс
if process.poll() is not None:
return False, None
time.sleep(check_interval)
# Таймаут
process.terminate()
return False, None
def ensure_acp_server(auto_start: bool = True, preferred_port: int = 8090) -> tuple[int | None, bool]:
"""Проверяет и при необходимости запускает ACP сервер.
Args:
auto_start: Запускать сервер если не найден
preferred_port: Предпочитаемый порт
Returns:
Tuple (port, was_started) - порт и был ли сервер запущен этим вызовом
"""
# Сначала ищем уже запущенный сервер
existing_port = find_acp_server(preferred_port)
if existing_port:
return existing_port, False
if not auto_start:
return None, False
# Запускаем сервер
success, port = start_acp_server(preferred_port)
if success:
return port, True
return None, False
# Загружаем .env файлы
try:
from dotenv import load_dotenv
DOTENV_AVAILABLE = True
except ImportError:
DOTENV_AVAILABLE = False
try:
from iflow_sdk import IFlowClient, IFlowOptions, ApprovalMode, ErrorMessage
from iflow_sdk.types import (
AssistantMessage, TaskFinishMessage,
ToolCallMessage, ToolResultMessage, PlanMessage,
ToolConfirmationRequestMessage
)
except ImportError:
print("Error: iflow-cli-sdk not installed")
print("Install: pip install iflow-cli-sdk")
sys.exit(1)
# Применяем патчи SDK (добавляет поддержку _iflow/user/questions)
import sdk_patches
from sdk_patches import UserQuestionsMessage
# =============================================================================
# Конфигурация через переменные окружения
# =============================================================================
class Config:
"""Конфигурация runner из переменных окружения."""
# Директория установки runner (где лежит этот скрипт)
RUNNER_DIR: Path = Path(__file__).parent.resolve()
# ACP сервер
ACP_HOST: str = "localhost"
ACP_PORT: int = 8090
ACP_AUTO_START: bool = False # Не автостартовать iFlow
@classmethod
def load(cls, project_dir: Path | None = None):
"""Загружает конфигурацию из .env файлов и переменных окружения."""
# Определяем project root
cls.PROJECT_ROOT = Path(
os.getenv("WFLOW_PROJECT_ROOT", "") or
str(project_dir or Path.cwd())
).resolve()
# Загружаем .env из проекта (приоритет)
project_env = cls.PROJECT_ROOT / ".env"
if DOTENV_AVAILABLE and project_env.exists():
load_dotenv(project_env, override=True)
# Загружаем .env из runner (значения по умолчанию)
runner_env = cls.RUNNER_DIR / ".env"
if DOTENV_AVAILABLE and runner_env.exists():
load_dotenv(runner_env, override=False)
# Директория с workflows
cls.WORKFLOWS_DIR = cls._resolve_path(
os.getenv("WFLOW_WORKFLOWS_DIR"),
[cls.PROJECT_ROOT / ".wflow" / "workflows", cls.RUNNER_DIR / "workflows"]
)
# Директория с prompts
cls.PROMPTS_DIR = cls._resolve_path(
os.getenv("WFLOW_PROMPTS_DIR"),
[cls.PROJECT_ROOT / ".wflow" / "prompts", cls.RUNNER_DIR / "prompts"]
)
# ACP сервер
cls.ACP_HOST = os.getenv("WFLOW_ACP_HOST", "localhost")
cls.ACP_PORT = int(os.getenv("WFLOW_ACP_PORT", "8090"))
cls.ACP_AUTO_START = os.getenv("WFLOW_ACP_AUTO_START", "true").lower() in ("true", "1", "yes")
# Переопределяем PROJECT_ROOT если изменился в .env
cls.PROJECT_ROOT = Path(
os.getenv("WFLOW_PROJECT_ROOT", str(cls.PROJECT_ROOT))
).resolve()
@classmethod
def _resolve_path(cls, env_value: str | None, fallbacks: list[Path]) -> Path:
"""Разрешает путь из переменной окружения или fallback-ов."""
if env_value:
path = Path(env_value)
if path.is_absolute():
return path
return (cls.PROJECT_ROOT / path).resolve()
for fallback in fallbacks:
if fallback.exists():
return fallback
return fallbacks[-1]
@classmethod
def info(cls) -> str:
"""Возвращает информацию о конфигурации."""
acp_status = "running" if check_acp_server(cls.ACP_HOST, cls.ACP_PORT) else "not running"
return f"""
Configuration:
PROJECT_ROOT: {cls.PROJECT_ROOT}
WORKFLOWS_DIR: {cls.WORKFLOWS_DIR}
PROMPTS_DIR: {cls.PROMPTS_DIR}
RUNNER_DIR: {cls.RUNNER_DIR}
ACP Server:
Host: {cls.ACP_HOST}
Port: {cls.ACP_PORT}
Status: {acp_status}
Auto-start: {cls.ACP_AUTO_START}
"""
class WorkflowRunner:
"""Исполнитель workflow с гарантированным порядком шагов."""
def __init__(self, workflow_path: str, verbose: bool = False, debug: bool = False):
self.verbose = verbose
self.debug = debug
# Разрешаем путь к workflow
self.workflow_path = self._resolve_workflow_path(workflow_path)
self.workflow = self._load_workflow()
# Состояние выполнения
self.state: dict[str, Any] = {}
self.context: dict[str, Any] = {}
self.failed = False
self.error_message: str | None = None
def _resolve_workflow_path(self, workflow_path: str) -> Path:
"""Разрешает путь к workflow файлу."""
path = Path(workflow_path)
if path.is_absolute():
if path.exists():
return path
raise FileNotFoundError(f"Workflow not found: {path}")
search_paths = [
Config.PROJECT_ROOT / workflow_path,
Config.WORKFLOWS_DIR / workflow_path,
Config.WORKFLOWS_DIR / f"{workflow_path}.yaml"
]
for search_path in search_paths:
if search_path.exists():
return search_path
raise FileNotFoundError(
f"Workflow not found: {workflow_path}\n"
f"Searched in:\n" +
"\n".join(f" - {p}" for p in search_paths)
)
def _load_workflow(self) -> dict:
"""Загружает workflow из YAML файла."""
with open(self.workflow_path, encoding="utf-8") as f:
workflow = yaml.safe_load(f)
if "steps" not in workflow:
raise ValueError("Workflow must contain 'steps' section")
return workflow
def get_required_inputs(self) -> dict[str, dict]:
"""Возвращает описание требуемых inputs из workflow."""
inputs_schema = self.workflow.get("inputs", {})
return inputs_schema
def _resolve_variables(self, text: str) -> str:
"""Подставляет переменные в формате ${{ var }} или ${var}."""
if not text:
return text
all_vars = {**self.context, **self.state}
all_vars["PROJECT_ROOT"] = str(Config.PROJECT_ROOT)
all_vars["WORKFLOWS_DIR"] = str(Config.WORKFLOWS_DIR)
all_vars["PROMPTS_DIR"] = str(Config.PROMPTS_DIR)
def replace_full(match):
expr = match.group(1).strip()
if expr.startswith("steps."):
parts = expr.split(".")
if len(parts) >= 2:
step_name = parts[1]
if step_name in self.state:
if len(parts) == 2:
return str(self.state[step_name])
elif parts[2] == "outputs" and len(parts) >= 4:
field = parts[3]
step_result = self.state[step_name]
if isinstance(step_result, dict) and field in step_result:
return str(step_result[field])
if expr.startswith("env."):
var_name = expr[4:]
return str(all_vars.get(var_name, ""))
if expr.startswith("inputs."):
var_name = expr[7:]
return str(all_vars.get(var_name, ""))
if expr.startswith("config."):
var_name = expr[7:].upper()
return str(all_vars.get(var_name, ""))
return str(all_vars.get(expr, match.group(0)))
text = re.sub(r"\$\{\{\s*([^}]+)\s*\}\}", replace_full, text)
def replace_simple(match):
var_name = match.group(1)
return str(all_vars.get(var_name, match.group(0)))
text = re.sub(r"\$\{(\w+)\}", replace_simple, text)
return text
def _load_prompt(self, step: dict) -> str:
"""Загружает промпт из строки или файла."""
if "prompt" in step:
return self._resolve_variables(step["prompt"])
if "prompt_file" in step:
prompt_file = step["prompt_file"]
search_paths = [
self.workflow_path.parent / prompt_file,
Config.PROMPTS_DIR / prompt_file,
Config.RUNNER_DIR / "prompts" / prompt_file,
]
for path in search_paths:
if path.exists():
content = path.read_text(encoding="utf-8")
return self._resolve_variables(content)
raise FileNotFoundError(
f"Prompt file not found: {prompt_file}\n"
f"Searched in:\n" +
"\n".join(f" - {p}" for p in search_paths)
)
raise ValueError(f"Step '{step.get('name', 'unknown')}' must have 'prompt' or 'prompt_file'")
def _build_context_for_step(self, step: dict) -> str:
"""Строит контекст из указанных переменных."""
context_vars = step.get("context", [])
if not context_vars:
return ""
context_parts = []
for var_name in context_vars:
if var_name in self.state:
value = self.state[var_name]
context_parts.append(f"## {var_name}\n{value}")
elif var_name in self.context:
context_parts.append(f"## {var_name}\n{self.context[var_name]}")
return "\n\n".join(context_parts)
def _check_dependencies(self, step: dict) -> bool:
"""Проверяет, что все зависимости выполнены."""
deps = step.get("depends_on", [])
for dep in deps:
if dep not in self.state:
return False
return True
def _print_step_header(self, step_name: str, step_num: int, total: int):
"""Выводит заголовок шага."""
console.print()
console.print(Panel(
f"[bold blue]STEP [{step_num}/{total}]: {step_name}[/]",
border_style="blue",
padding=(0, 2)
))
def _print_step_footer(self, step_name: str, success: bool, duration: float):
"""Выводит итог шага."""
if success:
console.print(f"[green]✓ SUCCESS[/] [{step_name}] ({duration:.1f}s)")
else:
console.print(f"[red]✗ FAILED[/] [{step_name}] ({duration:.1f}s)")
async def _execute_step(self, client: IFlowClient, step: dict, step_num: int, total: int) -> str:
"""Выполняет один шаг workflow."""
step_name = step.get("name", f"step_{step_num}")
if not self._check_dependencies(step):
pending_deps = [d for d in step.get("depends_on", []) if d not in self.state]
raise RuntimeError(f"Dependencies not satisfied: {pending_deps}")
# Проверяем interactive флаг - запрос подтверждения перед шагом
if step.get("interactive"):
self._print_step_header(step_name, step_num, total)
print("\n⚠️ This step requires confirmation.")
step_desc = step.get("description", "")
if step_desc:
print(f" Description: {step_desc}")
while True:
try:
answer = input("\nProceed with this step? [Y/n]: ").strip().lower()
if answer in ("", "y", "yes", "д", "да"):
break
elif answer in ("n", "no", "н", "нет"):
raise RuntimeError(f"Step '{step_name}' cancelled by user")
else:
print("Please enter Y or N")
except KeyboardInterrupt:
print("\nCancelled.")
raise RuntimeError(f"Step '{step_name}' cancelled by user")
else:
self._print_step_header(step_name, step_num, total)
start_time = datetime.now()
prompt = self._load_prompt(step)
context_text = self._build_context_for_step(step)
if context_text:
prompt = f"{prompt}\n\n---\n## Context from previous steps:\n{context_text}"
if self.verbose:
print(f"\n[PROMPT]\n{prompt}\n[/PROMPT]\n")
# Переопределение approval_mode для конкретного шага
step_approval = step.get("approval")
if step_approval:
# Определяем режим для шага
if step_approval.lower() == "ask":
step_approval_mode = ApprovalMode.DEFAULT
elif step_approval.lower() == "auto":
step_approval_mode = ApprovalMode.AUTO_EDIT
elif step_approval.lower() == "yolo":
step_approval_mode = ApprovalMode.YOLO
elif step_approval.lower() == "plan":
step_approval_mode = ApprovalMode.PLAN
else:
step_approval_mode = self.global_approval_mode
# Если режим отличается от текущего, нужно пересоздать клиент
if step_approval_mode != self.global_approval_mode:
if self.debug:
print(f"\n\033[33m🔒 [APPROVAL] Switching to {step_approval.upper()} for this step\033[0m")
# Обновляем approval_mode в текущей сессии через options
client._options.approval_mode = step_approval_mode
await client.send_message(prompt)
result = ""
current_agent = None
async for msg in client.receive_messages():
# === Assistant Message (text + thinking) ===
if isinstance(msg, AssistantMessage):
# Показываем мысли (thinking mode)
if msg.chunk.thought and self.debug:
console.print("[dim]💭 [THINKING][/]")
for line in msg.chunk.thought.split('\n'):
console.print(f"[dim] {line}[/]")
# Показываем текст ответа
if msg.chunk.text:
text = msg.chunk.text
result += text
# Выводим текст как Markdown (убираем лишние переносы в конце)
text_clean = text.rstrip('\n')
if text_clean:
console.print(Markdown(text_clean))
# Показываем субагента
if msg.agent_info and self.debug:
agent_id = msg.agent_info.agent_id
if current_agent != agent_id:
current_agent = agent_id
console.print(f"[cyan]🤖 [SUBAGENT: {agent_id}][/]")
# === Tool Call ===
elif isinstance(msg, ToolCallMessage):
if self.debug:
agent_str = ""
if msg.agent_info:
agent_str = f" (by {msg.agent_info.agent_id})"
console.print(f"[yellow]🔧 [TOOL] {msg.tool_name}[/]{agent_str}")
if msg.args:
args_str = json.dumps(msg.args, ensure_ascii=False, indent=2)
for line in args_str.split('\n')[:10]: # Limit args display
console.print(f"[yellow] {line}[/]")
# === Tool Result ===
elif isinstance(msg, ToolResultMessage):
if self.debug:
status = "✓" if msg.status.value == "completed" else "✗"
status_style = "green" if msg.status.value == "completed" else "red"
console.print(f"[{status_style}]📦 [RESULT] {status} {msg.tool_name}[/]")
if msg.content and msg.content.markdown:
lines = msg.content.markdown.split('\n')[:5] # Limit result display
for line in lines:
console.print(f"[green] {line[:100]}[/]")
# === Plan Update ===
elif isinstance(msg, PlanMessage):
if self.debug:
console.print("[magenta]📋 [PLAN][/]")
status_icons = {"pending": "⏳", "in_progress": "▶", "completed": "✓"}
for entry in msg.entries[:10]: # Limit entries display
icon = status_icons.get(entry.status, "•")
priority_str = f"[{entry.priority}]" if entry.priority else ""
console.print(f"[magenta] {icon} {priority_str} {entry.content[:60]}[/]")
# === Error ===
elif isinstance(msg, ErrorMessage):
console.print(f"[red]❌ [ERROR] {msg}[/]")
# === Permission Request (Tool Confirmation) ===
elif isinstance(msg, ToolConfirmationRequestMessage):
console.print(Panel(
f"[bold]Kind:[/] {msg.tool_call.kind}\n[bold]Title:[/] {msg.tool_call.title}",
title="[yellow]🔐 PERMISSION REQUEST[/]",
border_style="yellow"
))
if msg.tool_call.locations:
for loc in msg.tool_call.locations[:3]:
console.print(f" [dim]Location:[/] {loc.path}")
if loc.line_start:
console.print(f" [dim]Lines:[/] {loc.line_start}-{loc.line_end or loc.line_start}")
console.print("\n[bold]Options:[/]")
for i, opt in enumerate(msg.options, 1):
kind_display = f" [dim]({opt.kind})[/]" if opt.kind else ""
console.print(f" [cyan][{i}][/][bold]{opt.name}[/]{kind_display}")
# Запрашиваем выбор пользователя
while True:
try:
choice = console.input("\n [bold]Select option (number):[/] ").strip()
if choice.isdigit():
idx = int(choice) - 1
if 0 <= idx < len(msg.options):
selected = msg.options[idx]
await client.respond_to_tool_confirmation(
msg.request_id, selected.option_id
)
console.print(f"[green]✓ Selected: {selected.name}[/]")
break
console.print(f"[yellow]Please enter a number from 1 to {len(msg.options)}[/]")
except KeyboardInterrupt:
await client.cancel_tool_confirmation(msg.request_id)
console.print("[yellow]✗ Cancelled by user[/]")
raise RuntimeError("Permission request cancelled by user")
# === User Questions (from agent) ===
elif isinstance(msg, UserQuestionsMessage):
console.print()
console.print(Panel(
f"[bold]Agent задаёт {len(msg.questions)} вопрос(ов):[/]",
title="[cyan]❓ ВОПРОСЫ[/]",
border_style="cyan"
))
answers = []
for i, q in enumerate(msg.questions, 1):
header = q.get("header", f"Вопрос {i}")
question = q.get("question", "")
options = q.get("options", [])
multi_select = q.get("multiSelect", False)
# Разделитель между вопросами
if i > 1:
console.print()
console.print(f"[dim]{'─' * 60}[/]")
console.print(f"\n[cyan bold]❓ [{header}][/]")
console.print(f"[bold]{question}[/]\n")
if options:
console.print("[bold]Варианты:[/]")
for j, opt in enumerate(options, 1):
label = opt.get("label", str(opt))
desc = opt.get("description", "")
if desc:
# Ограничиваем длину описания
desc_short = desc[:70] + "..." if len(desc) > 70 else desc
console.print(f" [cyan bold][{j}][/][bold]{label}[/]")
console.print(f" [dim]{desc_short}[/]")
else:
console.print(f" [cyan bold][{j}][/][bold]{label}[/]")
# Показываем опцию для произвольного ввода
other_num = len(options) + 1
console.print(f" [yellow bold][{other_num}][/][bold]Другое...[/]")
console.print(" [dim]Ввести свой ответ[/]")
if multi_select:
console.print("\n[dim]💡 Можно выбрать несколько через запятую: 1,2,3[/]")
while True:
try:
prompt_text = " [bold]Выберите вариант:[/] " if not multi_select else " [bold]Выберите (через запятую):[/] "
choice = console.input(prompt_text).strip()
if multi_select:
# Парсим множественный выбор
parts = [x.strip() for x in choice.split(",")]
indices = []
other_text = None
for part in parts:
if part.isdigit():
idx = int(part) - 1
if 0 <= idx < len(options):
indices.append(idx)
elif idx == len(options): # "Other" option
other_text = console.input(" [bold]Введите ответ:[/] ").strip()
if indices or other_text:
selected_labels = [options[idx].get("label") for idx in indices if idx < len(options)]
selected_indices = [idx for idx in indices if idx < len(options)]
if other_text:
selected_labels.append(other_text)
answers.append({
"question": i - 1,
"selected": selected_labels,
"selectedIndices": selected_indices, # Индексы выбранных опций
"answer": ", ".join(selected_labels)
})
break
else:
if choice.isdigit():
idx = int(choice) - 1
if 0 <= idx < len(options):
answers.append({
"question": i - 1,
"selectedIndex": idx, # Индекс выбранной опции
"answer": options[idx].get("label", options[idx])
})
break
elif idx == len(options): # "Other" option
other_answer = console.input(" [bold]Введите ответ:[/] ").strip()
if other_answer:
answers.append({
"question": i - 1,
"answer": other_answer
})
break
# Произвольный текст как ответ
if choice:
answers.append({
"question": i - 1,
"answer": choice
})
break
console.print("[yellow]Введите номер варианта или свой текст[/]")
except KeyboardInterrupt:
raise RuntimeError("Questions cancelled by user")
else:
# Свободный ввод
try:
answer = console.input(" [bold]Ответ:[/] ").strip()
answers.append({
"question": i - 1,
"answer": answer
})
except KeyboardInterrupt:
raise RuntimeError("Questions cancelled by user")
# Отправляем ответы
console.print()
await client._protocol.respond_to_user_questions(
msg.request_id,
answers,
msg.questions # Передаём вопросы для получения header и labels
)
console.print("[green]✓ Ответы отправлены[/]")
# === Task Finished ===
elif isinstance(msg, TaskFinishMessage):
console.print()
break
# Восстанавливаем глобальный approval_mode после шага
if step_approval:
client._options.approval_mode = self.global_approval_mode
duration = (datetime.now() - start_time).total_seconds()
self._print_step_footer(step_name, True, duration)
if step.get("output_format") == "json":
try:
json_match = re.search(r"```(?:json)?\s*([\s\S]*?)```", result)
if json_match:
result = json.loads(json_match.group(1))
else:
result = json.loads(result)
except json.JSONDecodeError:
pass
return result
def run(self, inputs: dict[str, str]) -> dict[str, Any]:
"""Запускает workflow синхронно."""
return asyncio.run(self._run_async(inputs))
async def _run_async(self, inputs: dict[str, str]) -> dict[str, Any]:
"""Асинхронное выполнение workflow."""
self.context = {
"PROJECT_ROOT": str(Config.PROJECT_ROOT),
"WORKFLOWS_DIR": str(Config.WORKFLOWS_DIR),
"PROMPTS_DIR": str(Config.PROMPTS_DIR),
**self.workflow.get("env", {}),
**inputs
}
console.print()
console.print(Panel(
f"[bold blue]{self.workflow.get('name', self.workflow_path.stem)}[/]",
border_style="blue"
))
if self.verbose:
console.print(Config.info())
console.print("\n[bold]Inputs:[/]")
for key, value in inputs.items():
console.print(f" [cyan]{key}:[/] {value}")
# Проверяем и при необходимости запускаем ACP сервер
console.print()
acp_port, was_started = ensure_acp_server(
auto_start=Config.ACP_AUTO_START,
preferred_port=Config.ACP_PORT
)
if acp_port is None:
console.print(Panel(
f"[red bold]ACP сервер не найден и не удалось его запустить[/]\n\n"
f"[yellow]Запустите iFlow вручную:[/]\n\n"
f" [cyan]iflow --experimental-acp --port {Config.ACP_PORT}[/]",
title="[red bold]ACP SERVER ERROR[/]",
border_style="red"
))
raise RuntimeError(f"ACP server not running and auto-start failed")
if was_started:
console.print(f"[green]✓ ACP сервер запущен на порту {acp_port}[/]")
elif acp_port != Config.ACP_PORT:
console.print(f"[cyan]ℹ️ ACP сервер найден на порту {acp_port} (не на {Config.ACP_PORT})[/]")
else:
console.print(f"[dim]✓ ACP сервер уже запущен на порту {acp_port}[/]")
# Default approval_mode - DEFAULT (безопаснее чем YOLO)
approval_mode_str = self.workflow.get("approval_mode", "DEFAULT").upper()
self.global_approval_mode = getattr(ApprovalMode, approval_mode_str, ApprovalMode.DEFAULT)
options = IFlowOptions(
url=f"ws://{Config.ACP_HOST}:{acp_port}/acp",
file_access=True,
file_allowed_dirs=[str(Config.PROJECT_ROOT)],
cwd=str(Config.PROJECT_ROOT),
timeout=self.workflow.get("timeout", 600.0),
approval_mode=self.global_approval_mode,
auto_start_process=False, # Мы сами управляем запуском
)
total_steps = len(self.workflow["steps"])
try:
async with IFlowClient(options) as client:
for i, step in enumerate(self.workflow["steps"], 1):
step_name = step.get("name", f"step_{i}")
# Определяем количество попыток
on_failure = step.get("on_failure", {})
max_retries = on_failure.get("retry", 0) if isinstance(on_failure, dict) else 0
attempt = 0
while True:
try:
result = await self._execute_step(client, step, i, total_steps)
self.state[step_name] = result
if "on_success" in step:
print(f"\n[HOOK] {step['on_success']}")
break # Успех - выходим из цикла попыток
except Exception as e:
attempt += 1
if attempt <= max_retries:
print(f"\n\033[33m⚠️ [RETRY] Attempt {attempt}/{max_retries} for step '{step_name}'\033[0m")
if on_failure.get("notify"):
print(f"\n[NOTIFY] Step '{step_name}' failed, retrying...")
continue # Повторяем попытку
# Попытки исчерпаны
self.failed = True
self.error_message = str(e)
if isinstance(on_failure, dict) and on_failure.get("notify"):
print(f"\n[NOTIFY] Step failed after {max_retries} retries: {step_name}")
raise RuntimeError(f"Step '{step_name}' failed: {e}")
except Exception as e:
console.print()
console.print(Panel(
f"[red bold]{e}[/]",
title="[red bold]WORKFLOW FAILED[/]",
border_style="red"
))
raise
console.print()
console.print(Panel(
f"[green bold]Executed {total_steps} steps[/]",
title="[green bold]WORKFLOW COMPLETED SUCCESSFULLY[/]",
border_style="green"
))
return self.state
# =============================================================================
# Интерактивный режим
# =============================================================================
def list_available_workflows() -> list[Path]:
"""Возвращает список доступных workflow файлов."""
workflows = []
# Ищем в WORKFLOWS_DIR
if Config.WORKFLOWS_DIR.exists():
workflows.extend(Config.WORKFLOWS_DIR.glob("*.yaml"))
workflows.extend(Config.WORKFLOWS_DIR.glob("*.yml"))
# Убираем дубликаты и сортируем
workflows = sorted(set(workflows), key=lambda p: p.stem)
return workflows
def select_workflow_interactive() -> Path | None:
"""Интерактивный выбор workflow."""
workflows = list_available_workflows()
if not workflows:
console.print("[yellow]No workflows found.[/]")
console.print(f"\nCreate workflow files in: [cyan]{Config.WORKFLOWS_DIR}[/]")
return None
console.print()
console.print(Panel("[bold]Available Workflows[/]", border_style="blue"))
for i, wf_path in enumerate(workflows, 1):
# Читаем название из файла
try:
with open(wf_path, encoding="utf-8") as f:
wf_data = yaml.safe_load(f)
name = wf_data.get("name", wf_path.stem)
desc = wf_data.get("description", "")
if desc:
desc_display = desc[:60] + "..." if len(desc) > 60 else desc
console.print(f"\n [cyan][{i}][/][bold]{wf_path.stem}[/]")
console.print(f" [dim]{name}[/]")
console.print(f" [dim]{desc_display}[/]")
else:
console.print(f"\n [cyan][{i}][/][bold]{wf_path.stem}[/] — [dim]{name}[/]")
except Exception:
console.print(f"\n [cyan][{i}][/][bold]{wf_path.stem}[/]")
console.print()
while True:
try:
choice = console.input("[bold]Select workflow (number or name):[/] ").strip()
if not choice:
console.print("[yellow]Cancelled.[/]")
return None
# Проверяем по номеру
if choice.isdigit():
idx = int(choice) - 1
if 0 <= idx < len(workflows):
return workflows[idx]
console.print(f"[yellow]Invalid number. Choose 1-{len(workflows)}[/]")
continue
# Проверяем по имени
for wf_path in workflows:
if wf_path.stem.lower() == choice.lower():
return wf_path
console.print(f"[yellow]Workflow '{choice}' not found[/]")
except KeyboardInterrupt:
console.print("\n[yellow]Cancelled.[/]")
return None
def collect_inputs_interactive(workflow: dict) -> dict[str, str]:
"""Интерактивный сбор inputs для workflow."""
inputs_schema = workflow.get("inputs", {})