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
fix: solve bash exec fail not display error
chensheng1234594e87097a9ee
diff --git a/jiuwenclaw/agents/harness/common/rails/stream_event_rail.py b/jiuwenclaw/agents/harness/common/rails/stream_event_rail.pyindex 1f0c79c805..37a71a7e73 100644--- a/jiuwenclaw/agents/harness/common/rails/stream_event_rail.py+++ b/jiuwenclaw/agents/harness/common/rails/stream_event_rail.py@@ -10,6 +10,8 @@ Migrated from JiuClawReActAgent:from __future__ import annotationsimport asyncio+import json+import refrom typing import Any, List, Optionalimport tiktoken@@ -42,6 +44,88 @@ def _structured_tool_result_payload(result: Any) -> Any | None:return None+def _boolish_false(value: Any) -> bool:+ if value is False:+ return True+ return isinstance(value, str) and value.strip().lower() in {"false", "0", "no"}+++def _boolish_true(value: Any) -> bool:+ if value is True:+ return True+ return isinstance(value, str) and value.strip().lower() in {"true", "1", "yes"}+++def _nonzero_exit(value: Any) -> bool | None:+ if isinstance(value, bool):+ return None+ if isinstance(value, int):+ return value != 0+ if isinstance(value, str):+ try:+ return int(value.strip()) != 0+ except ValueError:+ return None+ return None+++def _infer_tool_result_error(value: Any) -> bool | None:+ if isinstance(value, dict):+ if "success" in value:+ if _boolish_false(value.get("success")):+ return True+ if _boolish_true(value.get("success")):+ return False+ if _boolish_true(value.get("is_error")) or _boolish_true(value.get("isError")):+ return True+ status = value.get("status")+ if isinstance(status, str) and status.strip().lower() in {"error", "failed", "failure"}:+ return True+ for key in ("exit_code", "exitCode", "returncode", "return_code"):+ exit_failed = _nonzero_exit(value.get(key))+ if exit_failed is not None:+ return exit_failed+ for key in ("data", "raw_output", "rawOutput", "result"):+ nested = value.get(key)+ if isinstance(nested, (dict, list)):+ nested_error = _infer_tool_result_error(nested)+ if nested_error is not None:+ return nested_error+ return None++ if isinstance(value, list):+ for item in value:+ item_error = _infer_tool_result_error(item)+ if item_error:+ return True+ return None++ if isinstance(value, str):+ text = value.strip()+ if not text:+ return None+ try:+ parsed = json.loads(text)+ except Exception:+ parsed = None+ if isinstance(parsed, (dict, list)):+ parsed_error = _infer_tool_result_error(parsed)+ if parsed_error is not None:+ return parsed_error+ if re.search(r"\bsuccess\s*[:=]\s*False\b", text, re.IGNORECASE):+ return True+ if text.startswith("[ERROR]"):+ return True+ exit_match = re.search(+ r"\b(?:exit(?:[_ ]?code)?|returncode|return[_ ]code)\s*[:= ]\s*(-?\d+)\b",+ text,+ re.IGNORECASE,+ )+ if exit_match:+ return int(exit_match.group(1)) != 0+ return None++class JiuClawStreamEventRail(DeepAgentRail):"""Emit frontend stream events and enforce pause/abort checkpoints.@@ -204,6 +288,12 @@ class JiuClawStreamEventRail(DeepAgentRail):}if raw_output is not None:tool_result_payload["raw_output"] = raw_output+ error_state = _infer_tool_result_error(raw_output if raw_output is not None else result)+ if error_state is not None:+ tool_result_payload["success"] = not error_state+ if error_state:+ tool_result_payload["status"] = "error"+ tool_result_payload["is_error"] = Trueawait session.write_stream(OutputSchema(type="tool_result",@@ -428,7 +518,6 @@ class JiuClawStreamEventRail(DeepAgentRail):Returns:Valid JSON string (e.g., '{"key": "value"}')."""- import jsonif isinstance(arguments, dict):return json.dumps(arguments, ensure_ascii=False)if isinstance(arguments, str):@@ -503,8 +592,6 @@ class JiuClawStreamEventRail(DeepAgentRail):Returns:Repaired JSON string, or original if no repair possible"""- import re-s = json_str.strip()# Pattern 1: Fix Windows paths (D:/path, C:/path)diff --git a/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts b/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.tsindex 0224ddd75b..a3a79d8683 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts@@ -311,6 +311,22 @@ function handleDelta(return true;}+function chooseFinalAssistantContent(streamedContent: string, finalContent: string): string {+ if (!streamedContent) {+ return finalContent;+ }+ if (!finalContent) {+ return streamedContent;+ }+ if (finalContent === streamedContent || finalContent.startsWith(streamedContent)) {+ return finalContent;+ }+ if (streamedContent.includes(finalContent)) {+ return streamedContent;+ }+ return finalContent.length >= streamedContent.length ? finalContent : streamedContent;+}+function handleFinal(delegate: AppEventDelegate,payload: Record<string, unknown>,@@ -323,6 +339,11 @@ function handleFinal(entries,(entry) => entry.kind === "assistant" && entry.streaming === true,);+ const streamedContent =+ streamingIndex !== -1 && entries[streamingIndex]?.kind === "assistant"+ ? entries[streamingIndex].content+ : "";+ const finalContent = chooseFinalAssistantContent(streamedContent, content);delegate.setEntries(streamingIndex !== -1? [@@ -331,11 +352,7 @@ function handleFinal(),{...(entries[streamingIndex] as Extract<HistoryItem, { kind: "assistant" }>),- content:- content ||- (entries[streamingIndex]?.kind === "assistant"- ? entries[streamingIndex].content- : ""),+ content: finalContent,requestId:typeof payload.request_id === "string"? payload.request_iddiff --git a/jiuwenclaw/channels/tui/frontend/src/core/history-parser.ts b/jiuwenclaw/channels/tui/frontend/src/core/history-parser.tsindex 46b194b905..a8f286ec11 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/history-parser.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/history-parser.ts@@ -160,6 +160,86 @@ function parseArguments(raw: unknown): Record<string, unknown> | undefined {return undefined;}+function parseStructuredText(raw: unknown): unknown {+ if (typeof raw !== "string") return raw;+ const text = raw.trim();+ if (!text) return raw;+ try {+ return JSON.parse(text);+ } catch {+ return raw;+ }+}++function isFalseLike(value: unknown): boolean {+ return (+ value === false ||+ (typeof value === "string" && ["false", "0", "no"].includes(value.trim().toLowerCase()))+ );+}++function isTrueLike(value: unknown): boolean {+ return (+ value === true ||+ (typeof value === "string" && ["true", "1", "yes"].includes(value.trim().toLowerCase()))+ );+}++function nonzeroExit(value: unknown): boolean | undefined {+ if (typeof value === "boolean") return undefined;+ if (typeof value === "number" && Number.isFinite(value)) return value !== 0;+ if (typeof value === "string" && value.trim()) {+ const parsed = Number(value.trim());+ return Number.isInteger(parsed) ? parsed !== 0 : undefined;+ }+ return undefined;+}++function inferToolResultError(value: unknown): boolean | undefined {+ const parsed = parseStructuredText(value);+ if (Array.isArray(parsed)) {+ for (const item of parsed) {+ if (inferToolResultError(item)) return true;+ }+ return undefined;+ }+ if (parsed && typeof parsed === "object") {+ const record = parsed as Record<string, unknown>;+ if ("success" in record) {+ if (isFalseLike(record.success)) return true;+ if (isTrueLike(record.success)) return false;+ }+ if (isTrueLike(record.is_error) || isTrueLike(record.isError)) return true;+ if (+ typeof record.status === "string" &&+ ["error", "failed", "failure"].includes(record.status.trim().toLowerCase())+ ) {+ return true;+ }+ for (const key of ["exit_code", "exitCode", "returncode", "return_code"]) {+ const failed = nonzeroExit(record[key]);+ if (failed !== undefined) return failed;+ }+ for (const key of ["data", "raw_output", "rawOutput", "result"]) {+ const nested = record[key];+ if (nested && typeof nested === "object") {+ const nestedError = inferToolResultError(nested);+ if (nestedError !== undefined) return nestedError;+ }+ }+ return undefined;+ }+ if (typeof parsed === "string") {+ if (/\bsuccess\s*[:=]\s*False\b/i.test(parsed)) return true;+ if (parsed.trimStart().startsWith("[ERROR]")) return true;+ const exitMatch = parsed.match(+ /\b(?:exit(?:[_ ]?code)?|returncode|return[_ ]code)\s*[:= ]\s*(-?\d+)\b/i,+ );+ if (exitMatch) return Number(exitMatch[1]) !== 0;+ }+ return undefined;+}+function resolveToolPayload(payload: Record<string, unknown>,key: "tool_call" | "tool_result",@@ -494,6 +574,9 @@ export function applyToolResult((success !== undefined ? !success : undefined) ??(status ? status === "error" : undefined) ??asBoolean(payload.is_error) ??+ inferToolResultError(toolPayload) ??+ inferToolResultError(payload) ??+ inferToolResultError(result) ??false;return {...tool,diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.tsindex 2661e999c5..36c7ce2a59 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts@@ -474,6 +474,7 @@ export class AppScreen implements Component, Focusable {private pendingSubmittedInput: string | null = null;private pendingSubmittedBaseline = 0;private pendingSubmittedSessionId: string | null = null;+ private transcriptScrollOffset = 0;/** Image attachments keyed by composer `@path` tokens (e.g. cached base64 for terminal preview). */private composerAttachments: FileAttachment[] = [];@@ -888,6 +889,10 @@ export class AppScreen implements Component, Focusable {return;}+ if (!snapshot.pendingQuestion && this.handleTranscriptScrollInput(data)) {+ 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,@@ -951,6 +956,10 @@ export class AppScreen implements Component, Focusable {viewedTeamMemberId: this.viewedTeamMemberId,transientNotice: this.transientNotice,animationPhase: this.animationPhase,+ transcriptScrollOffset: this.transcriptScrollOffset,+ onTranscriptScrollOffsetChange: (offset) => {+ this.transcriptScrollOffset = offset;+ },runningElapsedMs:!snapshot.isInterrupted &&(snapshot.isProcessing || teamWorking) &&@@ -1158,12 +1167,38 @@ export class AppScreen implements Component, Focusable {text: string,snapshot: ReturnType<CliPiAppState["getSnapshot"]>,): void {+ this.transcriptScrollOffset = 0;this.pendingSubmittedInput = text;this.pendingSubmittedBaseline = snapshot.entries.length;this.pendingSubmittedSessionId = snapshot.sessionId;this.tui.requestRender();}+ private handleTranscriptScrollInput(data: string): boolean {+ const pageSize = Math.max(1, Math.floor(this.tui.terminal.rows * 0.8));+ if (matchesKey(data, "pageUp") || matchesKey(data, "shift+pageUp")) {+ this.transcriptScrollOffset += pageSize;+ this.tui.requestRender();+ return true;+ }+ if (matchesKey(data, "pageDown") || matchesKey(data, "shift+pageDown")) {+ this.transcriptScrollOffset = Math.max(0, this.transcriptScrollOffset - pageSize);+ this.tui.requestRender();+ return true;+ }+ if (matchesKey(data, "ctrl+home")) {+ this.transcriptScrollOffset = Number.MAX_SAFE_INTEGER;+ this.tui.requestRender();+ return true;+ }+ if (matchesKey(data, "ctrl+end")) {+ this.transcriptScrollOffset = 0;+ this.tui.requestRender();+ return true;+ }+ return false;+ }+private clearPendingSubmittedInput(requestRender = true): void {this.pendingSubmittedInput = null;this.pendingSubmittedBaseline = 0;diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/components/tools/tool-line-renderers.ts b/jiuwenclaw/channels/tui/frontend/src/ui/components/tools/tool-line-renderers.tsindex 5d7ebd71c2..0cc649556e 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/components/tools/tool-line-renderers.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/components/tools/tool-line-renderers.ts@@ -13,7 +13,7 @@ const MAX_STRUCTURED_LINES_COLLAPSED = 6;const MAX_STRUCTURED_LINES_EXPANDED = 18;function toolPrefix(tool: ToolCallDisplay, animationPhase = 0): string {- if (tool.isError || tool.status === "error") return "! ";+ if (tool.isError || tool.status === "error") return "● ";if (tool.status === "timeout") return "◌ ";if (isToolRunning(tool)) return ["◐ ", "◓ ", "◑ ", "◒ "][animationPhase % 4]!;return "● ";diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/screen-layout.ts b/jiuwenclaw/channels/tui/frontend/src/ui/screen-layout.tsindex 7d3cf6c1fd..e11a480481 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/screen-layout.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/screen-layout.ts@@ -28,6 +28,8 @@ export interface ScreenLayoutOptions {transientNotice: string | null;animationPhase: number;runningElapsedMs?: number;+ transcriptScrollOffset?: number;+ onTranscriptScrollOffsetChange?: (offset: number) => void;}function formatSubtaskStatus(status: string): string {@@ -235,8 +237,7 @@ export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayoutoptions.width,): [];- const lines = [- ...transcriptLines,+ const fixedLines = [...todoLines,...(todoLines.length > 0 &&(teamStatusLines.length > 0 || miniTeamTreeLines.length > 0 || teamPanelLines.length > 0)@@ -253,5 +254,38 @@ export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayout...shortcutLines,];const height = Math.floor(options.height ?? 0);- return height > 0 && lines.length > height ? lines.slice(-height) : lines;+ if (height <= 0) {+ return [...transcriptLines, ...fixedLines];+ }+ if (fixedLines.length >= height) {+ if ((options.transcriptScrollOffset ?? 0) !== 0) {+ options.onTranscriptScrollOffsetChange?.(0);+ }+ return fixedLines.slice(-height);+ }++ const transcriptHeight = height - fixedLines.length;+ if (transcriptLines.length <= transcriptHeight) {+ if ((options.transcriptScrollOffset ?? 0) !== 0) {+ options.onTranscriptScrollOffsetChange?.(0);+ }+ return [...transcriptLines, ...fixedLines];+ }++ const requestedOffset = Math.max(0, Math.floor(options.transcriptScrollOffset ?? 0));+ const teamWorking =+ isTeamMode(snapshot.mode) &&+ isTeamWorking(snapshot.teamMemberEvents, snapshot.teamMessageEvents);+ const liveTranscript = snapshot.isProcessing || snapshot.isPaused || teamWorking;+ if (requestedOffset === 0 && !liveTranscript) {+ return [...transcriptLines, ...fixedLines];+ }++ const maxOffset = transcriptLines.length - transcriptHeight;+ const offset = Math.min(maxOffset, requestedOffset);+ if (offset !== requestedOffset) {+ options.onTranscriptScrollOffsetChange?.(offset);+ }+ const start = transcriptLines.length - transcriptHeight - offset;+ return [...transcriptLines.slice(start, start + transcriptHeight), ...fixedLines];}diff --git a/jiuwenclaw/server/utils/stream_utils.py b/jiuwenclaw/server/utils/stream_utils.pyindex 0e49bd3dc7..842223cd0d 100644--- a/jiuwenclaw/server/utils/stream_utils.py+++ b/jiuwenclaw/server/utils/stream_utils.py@@ -228,6 +228,9 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Anyraw_output = result_info.get("rawOutput")if raw_output is not None:result_payload["raw_output"] = raw_output+ for key in ("success", "status", "is_error", "summary"):+ if key in result_info:+ result_payload[key] = result_info.get(key)else:result_payload = {"result": str(payload)}return {