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(cli): permission dispaly and control
gallonH74c08ef3b7d1
diff --git a/jiuwenclaw/cli/src/app-state.ts b/jiuwenclaw/cli/src/app-state.tsindex b324630460..a0b4241dd2 100644--- a/jiuwenclaw/cli/src/app-state.ts+++ b/jiuwenclaw/cli/src/app-state.ts@@ -5,6 +5,7 @@ import {handleIncomingFrame,type AppEventDelegate,type PendingQuestion,+ type UserAnswer,} from "./core/event-handlers.js";import { isEventFrame, type EventFrame } from "./core/protocol.js";import {@@ -165,7 +166,15 @@ export class CliPiAppState {collapsedToolGroupIds: new Set(this.collapsedToolGroupIds),entries: [...this.entries],streamingState: this.streamingState,- pendingQuestion: this.pendingQuestion ? { ...this.pendingQuestion } : null,+ pendingQuestion: this.pendingQuestion+ ? {+ ...this.pendingQuestion,+ questions: this.pendingQuestion.questions.map((question) => ({+ ...question,+ options: [...question.options],+ })),+ }+ : null,lastError: this.lastError,isProcessing,isPaused: this.streamingState === StreamingState.Paused,@@ -369,17 +378,29 @@ export class CliPiAppState {this.sendEventOnly("chat.resume", {});}- answerQuestion(answer: string): void {+ submitQuestionAnswers(answers: UserAnswer[]): void {if (!this.pendingQuestion) return;- this.sendEventOnly("chat.user_answer", {- request_id: this.pendingQuestion.requestId,- content: answer,- });+ if (this.pendingQuestion.source === "permission_interrupt") {+ this.sendEventOnly("chat.send", {+ query: "",+ request_id: this.pendingQuestion.requestId,+ answers,+ });+ } else {+ this.sendEventOnly("chat.user_answer", {+ request_id: this.pendingQuestion.requestId,+ answers,+ });+ }this.pendingQuestion = null;this.streamingState = StreamingState.Idle;this.emitChange();}+ answerQuestion(answer: string): void {+ this.submitQuestionAnswers([{ selected_options: [answer], custom_input: answer }]);+ }+async restoreHistory(targetSessionId: string): Promise<void> {this.historyRequestToken += 1;const requestToken = this.historyRequestToken;diff --git a/jiuwenclaw/cli/src/core/event-handlers.ts b/jiuwenclaw/cli/src/core/event-handlers.tsindex 922415af26..ec998edbce 100644--- a/jiuwenclaw/cli/src/core/event-handlers.ts+++ b/jiuwenclaw/cli/src/core/event-handlers.ts@@ -18,7 +18,25 @@ import {export interface PendingQuestion {requestId: string;- text: string;+ source?: string;+ questions: PendingQuestionItem[];+}++export interface PendingQuestionItem {+ header: string;+ question: string;+ options: PendingQuestionOption[];+ multiSelect?: boolean;+}++export interface PendingQuestionOption {+ label: string;+ description?: string;+}++export interface UserAnswer {+ selected_options: string[];+ custom_input?: string;}export interface AppEventDelegate {@@ -74,6 +92,50 @@ function handleConnectionAck(delegate: AppEventDelegate, frame: EventFrame): booreturn true;}+function normalizePendingQuestion(payload: Record<string, unknown>): PendingQuestionItem[] {+ const rawQuestions = Array.isArray(payload.questions) ? payload.questions : [];+ const normalized = rawQuestions+ .filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object"))+ .map((item) => ({+ header: typeof item.header === "string" ? item.header : "Question",+ question: typeof item.question === "string" ? item.question : "",+ options: Array.isArray(item.options)+ ? item.options+ .filter((option): option is Record<string, unknown> => Boolean(option && typeof option === "object"))+ .map((option) => ({+ label: typeof option.label === "string" ? option.label : "",+ description: typeof option.description === "string" ? option.description : undefined,+ }))+ .filter((option) => option.label.length > 0)+ : [],+ multiSelect: item.multi_select === true,+ }))+ .filter((item) => item.question.length > 0);++ if (normalized.length > 0) {+ return normalized;+ }++ const fallbackText =+ typeof payload.text === "string"+ ? payload.text+ : typeof payload.content === "string"+ ? payload.content+ : "";+ if (!fallbackText) {+ return [];+ }++ return [+ {+ header: "Question",+ question: fallbackText,+ options: [],+ multiSelect: false,+ },+ ];+}+function handleDelta(delegate: AppEventDelegate,payload: Record<string, unknown>,@@ -370,17 +432,16 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFram}case "chat.ask_user_question": {- const text =- typeof payload.text === "string"- ? payload.text- : typeof payload.content === "string"- ? payload.content- : "";const requestId = typeof payload.request_id === "string" ? payload.request_id : "";- if (!text || !requestId) {+ const questions = normalizePendingQuestion(payload);+ if (!requestId || questions.length === 0) {return connectionChanged;}- delegate.setPendingQuestion({ requestId, text });+ delegate.setPendingQuestion({+ requestId,+ source: typeof payload.source === "string" ? payload.source : undefined,+ questions,+ });delegate.setStreamingState(StreamingState.WaitingForConfirmation);return true;}diff --git a/jiuwenclaw/cli/src/ui/app-screen.ts b/jiuwenclaw/cli/src/ui/app-screen.tsindex cf361fdcc8..edf25e9848 100644--- a/jiuwenclaw/cli/src/ui/app-screen.ts+++ b/jiuwenclaw/cli/src/ui/app-screen.ts@@ -1,6 +1,8 @@import {CombinedAutocompleteProvider,Editor,+ SelectList,+ type SelectItem,type AutocompleteItem,type Component,type Focusable,@@ -12,7 +14,7 @@ import { CommandService, parseSlashCommand } from "../core/commands/CommandServiimport { handleAppScreenKeyInput } from "./keymap.js";import { buildAppScreenLines } from "./screen-layout.js";import { padToWidth } from "./rendering/text.js";-import { editorTheme, palette } from "./theme.js";+import { editorTheme, palette, selectListTheme } from "./theme.js";const END_CURSOR = "\x1b[7m \x1b[0m";@@ -21,7 +23,10 @@ export class AppScreen implements Component, Focusable {private readonly unsubscribe: () => void;private _focused = false;private activeQuestionId: string | null = null;+ private activeQuestionIndex = 0;private draftBeforeQuestion = "";+ private pendingQuestionAnswers = new Map<number, string>();+ private questionList: SelectList | null = null;private showFullThinking = false;private showToolDetails = false;private showShortcutHelp = false;@@ -110,6 +115,13 @@ export class AppScreen implements Component, Focusable {return;}+ const snapshot = this.state.getSnapshot();+ if (snapshot.pendingQuestion && this.questionList !== null) {+ this.questionList.handleInput(data);+ this.tui.requestRender();+ return;+ }+this.editor.handleInput(data);}@@ -119,9 +131,11 @@ export class AppScreen implements Component, Focusable {? palette.border.question: palette.border.active;const editorLines = this.applySlashCommandHint(this.editor.render(width), width);+ const questionLines = this.buildPendingQuestionLines(snapshot, width);return buildAppScreenLines(snapshot, {width,terminalRows: this.tui.terminal.rows,+ questionLines,editorLines,showFullThinking: this.showFullThinking,showToolDetails: this.showToolDetails,@@ -136,7 +150,9 @@ export class AppScreen implements Component, Focusable {const snapshot = this.state.getSnapshot();if (snapshot.pendingQuestion) {- this.state.answerQuestion(text);+ if (this.questionList === null) {+ this.state.answerQuestion(text);+ }this.editor.addToHistory(text);this.editor.setText("");return;@@ -184,10 +200,18 @@ export class AppScreen implements Component, Focusable {const questionId = snapshot.pendingQuestion?.requestId ?? null;if (questionId && questionId !== this.activeQuestionId) {this.activeQuestionId = questionId;+ this.activeQuestionIndex = 0;+ this.pendingQuestionAnswers.clear();this.draftBeforeQuestion = this.editor.getText();this.editor.setText("");+ this.syncQuestionList(snapshot);+ } else if (questionId && this.activeQuestionId) {+ this.syncQuestionList(snapshot);} else if (!questionId && this.activeQuestionId) {this.activeQuestionId = null;+ this.activeQuestionIndex = 0;+ this.pendingQuestionAnswers.clear();+ this.questionList = null;if (!this.editor.getText() && this.draftBeforeQuestion) {this.editor.setText(this.draftBeforeQuestion);}@@ -262,4 +286,126 @@ export class AppScreen implements Component, Focusable {: undefined,}));}++ private buildPendingQuestionLines(snapshot: ReturnType<CliPiAppState["getSnapshot"]>, width: number): string[] {+ const pendingQuestion = snapshot.pendingQuestion;+ if (!pendingQuestion) {+ return [];+ }++ const question = pendingQuestion.questions[this.activeQuestionIndex] ?? pendingQuestion.questions[0];+ if (!question) {+ return [];+ }++ const total = pendingQuestion.questions.length;+ const progress = total > 1 ? ` (${this.activeQuestionIndex + 1}/${total})` : "";+ const lines = this.wrapQuestionText(`[${question.header || "Question"}${progress}] ${question.question}`, width).map(+ (line) => padToWidth(palette.status.warning(line), width),+ );++ if (this.questionList !== null) {+ lines.push(" ".repeat(width));+ lines.push(...this.questionList.render(width));+ lines.push(+ padToWidth(+ palette.text.dim("Use ↑/↓ to choose, Enter to confirm, Esc to reject"),+ width,+ ),+ );+ }++ lines.push(" ".repeat(width));+ return lines;+ }++ private wrapQuestionText(text: string, width: number): string[] {+ const maxWidth = Math.max(12, width - 1);+ const source = text.replace(/\r/g, "").split("\n");+ const lines: string[] = [];+ for (const rawLine of source) {+ const words = rawLine.split(/\s+/).filter((word) => word.length > 0);+ if (words.length === 0) {+ lines.push("");+ continue;+ }+ let current = "";+ for (const word of words) {+ const next = current ? `${current} ${word}` : word;+ if (next.length <= maxWidth) {+ current = next;+ continue;+ }+ if (current) {+ lines.push(current);+ }+ current = word.length <= maxWidth ? word : word.slice(0, maxWidth);+ }+ if (current) {+ lines.push(current);+ }+ }+ return lines.length > 0 ? lines : [text.slice(0, maxWidth)];+ }++ private syncQuestionList(snapshot: ReturnType<CliPiAppState["getSnapshot"]>): void {+ const pendingQuestion = snapshot.pendingQuestion;+ if (!pendingQuestion) {+ this.questionList = null;+ return;+ }++ const question = pendingQuestion.questions[this.activeQuestionIndex];+ if (!question || question.options.length === 0) {+ this.questionList = null;+ return;+ }++ const items: SelectItem[] = question.options.map((option) => ({+ value: option.label,+ label: option.label,+ description: option.description,+ }));+ const list = new SelectList(items, Math.min(Math.max(items.length, 1), 6), selectListTheme);+ list.onSelect = (item) => {+ this.handleQuestionSelection(item.value);+ };+ list.onCancel = () => {+ const reject = question.options.find((option) => option.label === "拒绝");+ if (reject) {+ this.handleQuestionSelection(reject.label);+ }+ };+ const selectedValue = this.pendingQuestionAnswers.get(this.activeQuestionIndex);+ const selectedIndex = selectedValue+ ? items.findIndex((item) => item.value === selectedValue)+ : 0;+ if (selectedIndex >= 0) {+ list.setSelectedIndex(selectedIndex);+ }+ this.questionList = list;+ }++ private handleQuestionSelection(label: string): void {+ const snapshot = this.state.getSnapshot();+ const pendingQuestion = snapshot.pendingQuestion;+ if (!pendingQuestion) {+ return;+ }++ this.pendingQuestionAnswers.set(this.activeQuestionIndex, label);+ if (this.activeQuestionIndex < pendingQuestion.questions.length - 1) {+ this.activeQuestionIndex += 1;+ this.syncQuestionList(this.state.getSnapshot());+ this.tui.requestRender();+ return;+ }++ const answers = pendingQuestion.questions.map((question, index) => ({+ selected_options: [+ this.pendingQuestionAnswers.get(index) ?? question.options[0]?.label ?? "",+ ].filter((value) => value.length > 0),+ }));+ this.state.submitQuestionAnswers(answers);+ }}diff --git a/jiuwenclaw/cli/src/ui/screen-layout.ts b/jiuwenclaw/cli/src/ui/screen-layout.tsindex a0590447bf..b36d5ac027 100644--- a/jiuwenclaw/cli/src/ui/screen-layout.ts+++ b/jiuwenclaw/cli/src/ui/screen-layout.ts@@ -9,6 +9,7 @@ import { buildWelcomeLines } from "./welcome.js";export interface ScreenLayoutOptions {width: number;terminalRows: number;+ questionLines: string[];editorLines: string[];showFullThinking: boolean;showToolDetails: boolean;@@ -33,12 +34,6 @@ function formatSubtaskStatus(status: string): string {}}-function buildQuestionLines(text: string, width: number): string[] {- const question = `[question] ${text}`;- const clipped = question.length > width ? question.slice(0, width) : question;- return [padToWidth(palette.status.warning(clipped), width), " ".repeat(width)];-}-function buildStatusLines(snapshot: AppSnapshot,width: number,@@ -154,9 +149,6 @@ function buildTranscriptLines(}export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayoutOptions): string[] {- const questionLines = snapshot.pendingQuestion- ? buildQuestionLines(snapshot.pendingQuestion.text, options.width)- : [];const statusLines = buildStatusLines(snapshot, options.width, options.transientNotice);const shortcutLines = options.showShortcutHelp ? buildShortcutLines(options.width) : [];@@ -171,7 +163,7 @@ export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayoutreturn [...transcriptLines,...todoLines,- ...questionLines,+ ...options.questionLines,...options.editorLines,...statusLines,...shortcutLines,