JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(hitl): add AskUserRail to CodeAgent
hwxiajing03bb1bc5616e
diff --git a/jiuwenclaw/agentserver/deep_agent/interrupt/interrupt_helpers.py b/jiuwenclaw/agentserver/deep_agent/interrupt/interrupt_helpers.pyindex 9b45eb26e0..f5938bafb2 100644--- a/jiuwenclaw/agentserver/deep_agent/interrupt/interrupt_helpers.py+++ b/jiuwenclaw/agentserver/deep_agent/interrupt/interrupt_helpers.py@@ -70,42 +70,44 @@ def build_permission_rail(return permission_rail-def build_ask_user_rail() -> Any | None:- """Build AskUserRail for user input requests.-- Returns:- AskUserRail instance or None if creation failed- """- from openjiuwen.harness.rails.interrupt.ask_user_rail import AskUserRail-- try:- ask_user_rail = AskUserRail()- logger.info("[InterruptHelpers] AskUserRail created successfully")- except Exception as exc:- logger.warning("[InterruptHelpers] AskUserRail create failed: %s", exc)- ask_user_rail = None- return ask_user_rail-def convert_interactions_to_ask_user_question(state_outputs: list) -> dict | None:"""Convert __interaction__ list to frontend chat.ask_user_question format.- Args:- state_outputs: List of OutputSchema(type=__interaction__, payload=InteractionOutput)- Note: In streaming mode, this list contains only one element per chunk+ AskUserRail 中断: value 有 questions 字段 → source="ask_user_interrupt"+ PermissionRail 中断: value 无 questions 字段 → source="permission_interrupt"- Returns:- Frontend expected chat.ask_user_question format dict+ state_outputs 中的元素可能是:+ - InteractionOutput 对象 (有 id, value 属性, value 是 ToolCallInterruptRequest)+ - dict (有 id, value 键)"""if not state_outputs:return None- payload = state_outputs[0].payload if hasattr(state_outputs[0], 'payload') else state_outputs[0]- question_data = extract_question_from_interaction(payload)- if not question_data:+ interaction = state_outputs[0]+ if hasattr(interaction, "id"):+ request_id = interaction.id+ value_obj = interaction.value+ elif isinstance(interaction, dict):+ request_id = interaction.get("id", "")+ value_obj = interaction.get("value", {})+ else:return None- request_id = getattr(payload, 'id', '') if hasattr(payload, 'id') else payload.get('id', '')+ questions_raw = _extract_questions_from_value(value_obj)++ if questions_raw is not None:+ questions = _build_multi_questions(questions_raw)+ return {+ "event_type": "chat.ask_user_question",+ "request_id": request_id,+ "questions": questions,+ "source": "ask_user_interrupt",+ }++ question_data = extract_question_from_interaction(interaction)+ if not question_data:+ return Nonereturn {"event_type": "chat.ask_user_question",@@ -115,6 +117,47 @@ def convert_interactions_to_ask_user_question(state_outputs: list) -> dict | Non}+def _extract_questions_from_value(value_obj: Any) -> list | None:+ """从 value 对象中提取 questions 列表.++ AskUserRail 的 value (ToolCallInterruptRequest) 有 questions 属性.+ 如果 questions 存在且非空, 返回列表; 否则返回 None 表示不是 AskUserRail 中断.+ """+ if hasattr(value_obj, "questions"):+ qs = value_obj.questions+ if qs and len(qs) > 0:+ return qs+ elif isinstance(value_obj, dict):+ qs = value_obj.get("questions", [])+ if qs and len(qs) > 0:+ return qs+ return None+++def _build_multi_questions(questions_data: list) -> list:+ """Build frontend PendingQuestionItem list from questions data.++ 有选项的问题: 保留原始选项 + 追加 __other__ (自定义输入)+ 无选项的问题: 不追加 __other__, 前端应直接进入自由输入模式+ """+ questions = []+ for q in questions_data:+ raw_options = q.get("options", [])+ if raw_options:+ options = [{"label": opt["label"], "description": opt.get("description", "")}+ for opt in raw_options]+ options.append({"label": "Other", "description": "Custom input"})+ else:+ options = []+ questions.append({+ "question": q["question"],+ "header": q["header"],+ "options": options,+ "multi_select": q.get("multi_select", False),+ })+ return questions++def extract_question_from_interaction(payload: Any) -> dict | None:"""Extract question info from a single interaction payload.diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex fa00427f0a..08fe0551ff 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -251,7 +251,8 @@ class JiuWenClaw:answers = request.params.get("answers", [])if answers:request_id = request.params.get("request_id", "")- interactive_input = self._build_interactive_input_from_answers(request_id, answers)+ source = request.params.get("source", "")+ interactive_input = self._build_interactive_input_from_answers(request_id, answers, source)final_query = interactive_input if interactive_input is not None else build_user_prompt(query,files=request.params.get("files", {}),@@ -294,13 +295,14 @@ class JiuWenClaw:return inputs, memory_mode, querydef _build_interactive_input_from_answers(- self, request_id: str, answers: list[dict]+ self, request_id: str, answers: list[dict], source: str = "") -> Any:"""从用户答案构建 InteractiveInput.Args:request_id: 工具调用 IDanswers: 用户答案列表,每个答案对应一个问题+ source: 中断来源,用于区分 PermissionRail 和 AskUserRailReturns:InteractiveInput 实例@@ -309,6 +311,22 @@ class JiuWenClaw:interactive_input = InteractiveInput()+ if source == "ask_user_interrupt":+ answers_dict = {}+ for answer in answers:+ if isinstance(answer, dict):+ question_text = answer.get("question", "")+ selected_options = answer.get("selected_options", [])+ answer_value = selected_options[0] if selected_options else ""+ if question_text and answer_value:+ answers_dict[question_text] = answer_value+ interactive_input.update(request_id, {"answers": answers_dict})+ logger.info(+ "[JiuWenClaw] AskUserRail InteractiveInput.update: request_id=%s payload=%s",+ request_id, {"answers": answers_dict}+ )+ return interactive_input+answer = answers[0] if answers else {}selected_options = answer.get("selected_options", []) if isinstance(answer, dict) else []custom_input = answer.get("custom_input", "") if isinstance(answer, dict) else ""@@ -329,7 +347,7 @@ class JiuWenClaw:interactive_input.update(request_id, confirm_payload)logger.info(- "[JiuWenClaw] InteractiveInput.update: request_id=%s payload=%s",+ "[JiuWenClaw] PermissionRail InteractiveInput.update: request_id=%s payload=%s",request_id, confirm_payload)diff --git a/jiuwenclaw/cli/src/app-state.ts b/jiuwenclaw/cli/src/app-state.tsindex 3c5e706e93..2583429d5c 100644--- a/jiuwenclaw/cli/src/app-state.ts+++ b/jiuwenclaw/cli/src/app-state.ts@@ -676,11 +676,13 @@ readonly request = async <T = Record<string, unknown>>(this.emitChange();return;}- if (this.pendingQuestion.source === "permission_interrupt") {+ const source = this.pendingQuestion.source;+ if (source === "permission_interrupt" || source === "ask_user_interrupt") {this.sendEventOnly("chat.send", {query: "",request_id: this.pendingQuestion.requestId,answers,+ source,mode: this.mode,});} else {diff --git a/jiuwenclaw/cli/src/ui/app-screen.ts b/jiuwenclaw/cli/src/ui/app-screen.tsindex bdb2646129..ef595f4644 100644--- a/jiuwenclaw/cli/src/ui/app-screen.ts+++ b/jiuwenclaw/cli/src/ui/app-screen.ts@@ -336,6 +336,7 @@ export class AppScreen implements Component, Focusable {private syncingComposerInput = false;private pendingQuestionAnswers = new Map<number, string>();private questionList: SelectList | null = null;+ private otherInputMode = false;private resumeSessionList: ResumeSessionListState | null = null;private modelList: ModelListState | null = null;private configEditorState: ConfigEditorState | null = null;@@ -606,6 +607,18 @@ export class AppScreen implements Component, Focusable {return;}+ if (snapshot.pendingQuestion && this.otherInputMode) {+ if (matchesKey(data, "escape")) {+ this.otherInputMode = false;+ this.syncQuestionList(this.state.getSnapshot());+ this.tui.requestRender();+ return;+ }+ this.editor.handleInput(data);+ this.tui.requestRender();+ return;+ }+// Detect pasted file paths (drag-and-drop) in the terminal// When files are dragged in, they arrive as a pasted string.// Windows/PowerShell may not send bracketed paste markers,@@ -694,6 +707,30 @@ export class AppScreen implements Component, Focusable {const snapshot = this.state.getSnapshot();if (snapshot.pendingQuestion) {if (this.questionList === null) {+ if (this.otherInputMode) {+ this.pendingQuestionAnswers.set(this.activeQuestionIndex, text);+ this.otherInputMode = false;++ const pendingQuestion = snapshot.pendingQuestion;+ if (this.activeQuestionIndex < pendingQuestion.questions.length - 1) {+ this.activeQuestionIndex += 1;+ this.syncQuestionList(this.state.getSnapshot());+ this.editor.setText("");+ this.tui.requestRender();+ return;+ }++ const answers = pendingQuestion.questions.map((question, index) => {+ const answerValue = this.pendingQuestionAnswers.get(index) ?? question.options[0]?.label ?? "";+ return {+ question: question.question,+ selected_options: [answerValue],+ };+ });+ this.state.submitQuestionAnswers(answers);+ this.editor.setText("");+ return;+ }this.state.answerQuestion(text);}this.editor.setText("");@@ -1560,6 +1597,28 @@ export class AppScreen implements Component, Focusable {const summary = parsePermissionSummary(question.question);const title = progress ? `Permission ${this.activeQuestionIndex + 1}/${total}` : "Permission";lines.push(...renderPermissionBlock(width, summary, title));+ } else if (this.otherInputMode) {+ lines.push(+ ...wrapPlainText(+ `[${question.header || "Question"}${progress}] ${question.question}`,+ width,+ ).map((line) => padToWidth(palette.status.warning(line), width)),+ );+ if (question.options.length > 0) {+ lines.push("");+ for (const opt of question.options) {+ const optLine = ` ${opt.label}${opt.description ? ` - ${opt.description}` : ""}`;+ lines.push(padToWidth(palette.text.dim(optLine), width));+ }+ }+ lines.push("");+ lines.push(+ ...wrapPlainText(+ `[Answer] Please enter your answer:`,+ width,+ ).map((line) => padToWidth(palette.status.info(line), width)),+ );+ lines.push(padToWidth(palette.text.dim("Type your answer · Enter submit · Esc back to options"), width));} else {lines.push(...wrapPlainText(@@ -1638,6 +1697,13 @@ export class AppScreen implements Component, Focusable {return;}+ if (label === "Other") {+ this.otherInputMode = true;+ this.questionList = null;+ this.tui.requestRender();+ return;+ }+this.pendingQuestionAnswers.set(this.activeQuestionIndex, label);if (this.activeQuestionIndex < pendingQuestion.questions.length - 1) {this.activeQuestionIndex += 1;@@ -1646,11 +1712,13 @@ export class AppScreen implements Component, Focusable {return;}- const answers = pendingQuestion.questions.map((question, index) => ({- selected_options: [- this.pendingQuestionAnswers.get(index) ?? question.options[0]?.label ?? "",- ].filter((value) => value.length > 0),- }));+ const answers = pendingQuestion.questions.map((question, index) => {+ const answerValue = this.pendingQuestionAnswers.get(index) ?? question.options[0]?.label ?? "";+ return {+ question: question.question,+ selected_options: [answerValue],+ };+ });this.state.submitQuestionAnswers(answers);}}