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:/init和文件拖拽上传
zp233317145f7f6570d
diff --git a/jiuwenclaw/agentserver/agent_manager.py b/jiuwenclaw/agentserver/agent_manager.pyindex 61cdca0d36..036efa94f3 100644--- a/jiuwenclaw/agentserver/agent_manager.py+++ b/jiuwenclaw/agentserver/agent_manager.py@@ -5,6 +5,7 @@from __future__ import annotationsimport logging+import osimport uuidfrom typing import Any, TYPE_CHECKING@@ -50,6 +51,7 @@ class AgentManager:def __init__(self) -> None:self.agents: dict[str, dict[str, "JiuWenClaw"]] = {}self._client_capabilities_by_channel: dict[str, dict[str, Any]] = {}+ self._latest_env_overrides: dict[str, Any] = {}async def _create_agent(self, agent_key: str, mode: str = "agent", config: dict[str, Any] | None = None@@ -65,10 +67,16 @@ class AgentManager:"""from jiuwenclaw.agentserver.interface import JiuWenClaw+ for env_key, env_value in self._latest_env_overrides.items():+ key = str(env_key)+ if env_value is None:+ os.environ.pop(key, None)+ else:+ os.environ[key] = str(env_value)logger.info("[AgentManager] Creating %s agent (mode=%s)", agent_key, mode)agent = JiuWenClaw()await agent.create_instance(config, mode=mode)- self.agents[agent_key] = {mode: agent}+ self.agents.setdefault(agent_key, {})[mode] = agentlogger.info("[AgentManager] %s agent created", agent_key)return agent@@ -95,10 +103,12 @@ class AgentManager:if "acp" in self.agents:logger.info("[AgentManager] Resetting ACP agent")- try:- await self.agents["acp"].cleanup()- except Exception as e:- logger.warning("[AgentManager] ACP agent cleanup failed: %s", e)+ for agent in self.agents.get("acp", {}).values():+ if hasattr(agent, "cleanup"):+ try:+ await agent.cleanup()+ except Exception as e:+ logger.warning("[AgentManager] ACP agent cleanup failed: %s", e)del self.agents["acp"]config = _build_acp_agent_config(extra_config)@@ -150,7 +160,7 @@ class AgentManager:if channel_id == "acp":config = _build_acp_agent_config()await self._create_agent(channel_id, mode, config)- return self.agents.get(channel_id).get(mode)+ return self.agents.get(channel_id, {}).get(mode)def get_agent_nowait(self, channel_id: str = "") -> "JiuWenClaw | None":"""获取 Agent 实例(同步,不自动创建).@@ -161,10 +171,22 @@ class AgentManager:Returns:JiuWenClaw | None: Agent 实例,如果不存在则返回 None"""- return self.agents.get(channel_id)+ channel_key = channel_id or "default"+ channel_agents = self.agents.get(channel_key, {})+ if isinstance(channel_agents, dict):+ return channel_agents.get("agent") or next(iter(channel_agents.values()), None)+ return Noneasync def reload_agents_config(self, config, env) -> None:"""reload agent config"""+ self._latest_env_overrides = dict(env) if isinstance(env, dict) else {}+ for env_key, env_value in self._latest_env_overrides.items():+ key = str(env_key)+ if env_value is None:+ os.environ.pop(key, None)+ else:+ os.environ[key] = str(env_value)+for channel_id, agents in self.agents.items():for _, agent in agents.items():await agent.reload_agent_config(@@ -175,8 +197,8 @@ class AgentManager:async def cleanup(self) -> None:"""清理所有 agent 实例."""- for key, agents in self.agents.items():- for _, agent in agents.items():+ for key, agents in list(self.agents.items()):+ for agent in agents.values():if hasattr(agent, "cleanup"):try:await agent.cleanup()diff --git a/jiuwenclaw/channel/cli_channel.py b/jiuwenclaw/channel/cli_channel.pyindex 83e853b632..e729322e7f 100644--- a/jiuwenclaw/channel/cli_channel.py+++ b/jiuwenclaw/channel/cli_channel.py@@ -9,7 +9,11 @@ import shutilfrom dataclasses import dataclassfrom typing import Any-from openjiuwen.core.foundation.llm import ProviderType+from openjiuwen.core.foundation.llm import Model, ProviderType+from openjiuwen.core.foundation.llm.schema.config import (+ ModelClientConfig,+ ModelRequestConfig,+)from jiuwenclaw.config import (get_config,@@ -20,10 +24,12 @@ from jiuwenclaw.config import (get_model_config,add_or_update_model_in_config,)+from jiuwenclaw.jiuwen_core_patch import apply_openai_model_client_patchfrom jiuwenclaw.gateway.route_binding import GatewayRouteBindingfrom jiuwenclaw.version import __version__logger = logging.getLogger(__name__)+apply_openai_model_client_patch()# ── 需要转发到 Agent 的方法集合 ──────────────────────────────@@ -157,6 +163,16 @@ _CLI_CONFIG_SET_ENV_MAP = {_CLI_CONFIG_YAML_KEYS = frozenset({"context_engine_enabled", "permissions_enabled"})+def _normalize_provider_value(value: str) -> str:+ normalized = value.strip()+ if not normalized:+ return normalized++ available_model_providers = [provider.value for provider in ProviderType]+ lookup = {provider.lower(): provider for provider in available_model_providers}+ return lookup.get(normalized.lower(), normalized)++async def _clear_agent_config_cache(agent_client=None) -> None:try:@@ -290,6 +306,9 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:if param_key not in params:continueval = params[param_key]+ if param_key.endswith("_provider") and val:+ val = _normalize_provider_value(str(val))+ params[param_key] = valif (param_key.endswith("_provider")and val@@ -355,6 +374,114 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:},)+ async def _config_validate_model(ws, req_id, params, session_id):+ if not isinstance(params, dict):+ await channel.send_response(+ ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST"+ )+ return++ api_base = str(params.get("api_base") or "").strip()+ api_key = str(params.get("api_key") or "").strip()+ model = str(params.get("model") or "").strip()+ model_provider = _normalize_provider_value(str(params.get("model_provider") or ""))+ verify_ssl = bool(params.get("verify_ssl", False))++ if not all([api_base, api_key, model, model_provider]):+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error="api_base, api_key, model, and model_provider are required",+ code="BAD_REQUEST",+ )+ return++ available_model_providers = [provider.value for provider in ProviderType]+ if model_provider not in available_model_providers:+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error=f"Model provider must be one of: {available_model_providers}",+ code="BAD_REQUEST",+ )+ return++ if api_base.endswith("/chat/completions"):+ api_base = api_base.rsplit("/chat/completions", 1)[0]+ api_base = api_base.rstrip("/")++ model_request_config = ModelRequestConfig(model=model, temperature=0)+ model_client_config = ModelClientConfig(+ client_id="config-validate",+ client_provider=model_provider,+ api_key=api_key,+ api_base=api_base,+ timeout=25.0,+ max_retries=0,+ verify_ssl=verify_ssl,+ )+ llm = Model(+ model_config=model_request_config,+ model_client_config=model_client_config,+ )++ async def _probe(max_tokens: int):+ return await llm.invoke(+ [{"role": "user", "content": "Hi"}],+ max_tokens=max_tokens,+ temperature=0,+ )++ try:+ try:+ response = await _probe(1)+ except Exception as first_exc: # noqa: BLE001+ logger.info(+ "[cli config.validate_model] max_tokens=1 failed, retrying with 16: %s",+ first_exc,+ )+ response = await _probe(16)+ except Exception as exc: # noqa: BLE001+ logger.warning("[cli config.validate_model] LLM probe failed: %s", exc)+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error=str(exc).strip() or "LLM request failed",+ code="LLM_ERROR",+ )+ return++ if hasattr(response, "content"):+ content = response.content+ elif isinstance(response, dict):+ content = response.get("content", "")+ else:+ content = str(response)++ if not (isinstance(content, str) and content.strip()):+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error="Empty response from model",+ code="LLM_ERROR",+ )+ return++ await channel.send_response(+ ws,+ req_id,+ ok=True,+ payload={+ "provider": model_provider,+ "model": model,+ "response": content.strip(),+ },+ )+async def _session_list(ws, req_id, params, session_id):import timefrom jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields@@ -786,6 +913,7 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:channel.register_local_handler(path, "config.get", _config_get)channel.register_local_handler(path, "config.set", _config_set)+ channel.register_local_handler(path, "config.validate_model", _config_validate_model)channel.register_local_handler(path, "session.list", _session_list)channel.register_local_handler(path, "session.create", _session_create)channel.register_local_handler(path, "session.delete", _session_delete)diff --git a/jiuwenclaw/cli/package.json b/jiuwenclaw/cli/package.jsonindex 762aabee19..6d6a373dbf 100644--- a/jiuwenclaw/cli/package.json+++ b/jiuwenclaw/cli/package.json@@ -13,6 +13,7 @@"build": "tsc","build:bun": "npm run clean && bun build src/index.ts --target=node --outdir dist --format=esm --sourcemap && tsc --emitDeclarationOnly","typecheck": "tsc --noEmit",+ "test": "node --experimental-strip-types tests/run-tests.ts","lint": "oxlint --deny-warnings src","format": "oxfmt --write src package.json tsconfig.json","format:check": "oxfmt --check src package.json tsconfig.json",diff --git a/jiuwenclaw/cli/src/app-state.ts b/jiuwenclaw/cli/src/app-state.tsindex ceaee503a8..c29e31a72b 100644--- a/jiuwenclaw/cli/src/app-state.ts+++ b/jiuwenclaw/cli/src/app-state.ts@@ -16,9 +16,10 @@ import {handleIncomingFrame,type AppEventDelegate,type PendingQuestion,+ type PendingQuestionItem,type UserAnswer,} from "./core/event-handlers.js";-import { isEventFrame, type EventFrame } from "./core/protocol.js";+import { isEventFrame, type EventFrame, type FileAttachment } from "./core/protocol.js";import {StreamingState,type ContextCompressionStats,@@ -80,6 +81,13 @@ export class CliPiAppState {private collapsedToolGroupIds = new Set<string>();private streamingState: StreamingState = StreamingState.Idle;private pendingQuestion: PendingQuestion | null = null;+ private localPendingQuestion:+ | {+ requestId: string;+ resolve: (answers: UserAnswer[]) => void;+ reject: (error: Error) => void;+ }+ | null = null;private lastError: string | null = null;private activeSubtasks = new Map<string, SubtaskState>();private todos: TodoItem[] = [];@@ -185,6 +193,10 @@ export class CliPiAppState {}stop(): void {+ if (this.localPendingQuestion) {+ this.localPendingQuestion.reject(new Error("app stopped while awaiting input"));+ this.localPendingQuestion = null;+ }if (this.historyFlushTimer) {clearTimeout(this.historyFlushTimer);this.historyFlushTimer = null;@@ -253,6 +265,7 @@ export class CliPiAppState {return {sendEventOnly: this.sendEventOnly,request: this.request,+ askQuestions: this.askQuestions,sendMessage: this.sendMessage,sessionId: snapshot.sessionId,entries: snapshot.entries,@@ -288,7 +301,7 @@ export class CliPiAppState {type: "req",id,method,- params: { ...params, session_id: params.session_id ?? this.sessionId },+ params: { ...params, session_id: (params.session_id as string | undefined) ?? this.sessionId },});return id;};@@ -318,6 +331,10 @@ readonly request = async <T = Record<string, unknown>>(};readonly clearEntries = (): void => {+ if (this.localPendingQuestion) {+ this.localPendingQuestion.reject(new Error("input flow was interrupted"));+ this.localPendingQuestion = null;+ }this.entries = [];this.pendingQuestion = null;this.lastError = null;@@ -414,11 +431,17 @@ readonly request = async <T = Record<string, unknown>>(readonly sendMessage = (content: string,+ attachments?: FileAttachment[],modeOverride?: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "team",): string | null => {if (this.connectionStatus !== "connected") return null;const mode = modeOverride ?? this.mode;- const requestId = this.sendEventOnly("chat.send", { content, query: content, mode });+ const requestId = this.sendEventOnly("chat.send", {+ content,+ query: content,+ mode,+ ...(attachments?.length ? { attachments } : {}),+ });this.lastError = null;this.entries = [...this.entries,@@ -435,13 +458,14 @@ readonly request = async <T = Record<string, unknown>>(return requestId;};- supplement(content: string): string | null {+ supplement(content: string, attachments?: FileAttachment[]): string | null {if (this.connectionStatus !== "connected") return null;const trimmed = content.trim();if (!trimmed) return null;const requestId = this.sendEventOnly("chat.interrupt", {intent: "supplement",new_input: trimmed,+ ...(attachments?.length ? { attachments } : {}),});this.lastError = null;this.entries = [@@ -469,6 +493,18 @@ readonly request = async <T = Record<string, unknown>>(submitQuestionAnswers(answers: UserAnswer[]): void {if (!this.pendingQuestion) return;+ if (+ this.localPendingQuestion &&+ this.pendingQuestion.requestId === this.localPendingQuestion.requestId+ ) {+ const resolver = this.localPendingQuestion;+ this.localPendingQuestion = null;+ this.pendingQuestion = null;+ this.streamingState = StreamingState.Idle;+ resolver.resolve(answers);+ this.emitChange();+ return;+ }if (this.pendingQuestion.source === "permission_interrupt") {this.sendEventOnly("chat.send", {query: "",@@ -490,6 +526,31 @@ readonly request = async <T = Record<string, unknown>>(this.submitQuestionAnswers([{ selected_options: [answer], custom_input: answer }]);}+ readonly askQuestions = (+ questions: PendingQuestionItem[],+ source = "local_command",+ ): Promise<UserAnswer[]> => {+ if (questions.length === 0) {+ return Promise.resolve([]);+ }+ if (this.pendingQuestion || this.localPendingQuestion) {+ return Promise.reject(new Error("another question is already active"));+ }++ const requestId = `local_${Date.now().toString(16)}_${Math.random().toString(36).slice(2, 6)}`;+ this.pendingQuestion = {+ requestId,+ source,+ questions,+ };+ this.streamingState = StreamingState.Idle;+ this.emitChange();++ return new Promise<UserAnswer[]>((resolve, reject) => {+ this.localPendingQuestion = { requestId, resolve, reject };+ });+ };+readonly restoreHistory = async (targetSessionId: string): Promise<void> => {this.historyRequestToken += 1;const requestToken = this.historyRequestToken;diff --git a/jiuwenclaw/cli/src/core/attachments.ts b/jiuwenclaw/cli/src/core/attachments.tsnew file mode 100644index 0000000000..db636f2f0a--- /dev/null+++ b/jiuwenclaw/cli/src/core/attachments.ts@@ -0,0 +1,162 @@+import { basename, extname, resolve } from "node:path";+import type { FileAttachment } from "./protocol.js";++export const IMAGE_MIME_TYPES: Record<string, string> = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp",+};++const SUPPORTED_FILE_EXTENSIONS = new Set([+ "ts", "tsx", "js", "jsx", "mjs", "cjs", "css", "scss", "sass", "less", "html", "vue", "svelte",+ "py", "pyi", "pyw",+ "rs", "go", "c", "cpp", "h", "hpp", "java", "kt", "kts", "scala", "swift",+ "json", "yaml", "yml", "toml", "xml", "ini", "cfg", "conf", "env",+ "md", "mdx", "txt", "rst", "adoc",+ "sh", "bash", "zsh", "bat", "cmd", "ps1",+ "sql", "graphql", "gql",+ "tf", "hcl", "dockerfile",+ "proto", "thrift", "asm", "lua", "rb", "php", "dart",+]);++const AT_MENTION_RE = /(^|[\t ])@(?:"([^"]+)"|([^\s]+))/gm;+const PASTED_PATH_RE =+ /"([^"\r\n]+)"|'([^'\r\n]+)'|(file:\/\/[^\s]+|[A-Za-z]:\\[^\s]+|~\/[^\s]+|\.{1,2}\/[^\s]+|\/[^\s]+)/g;++export type AttachmentKind = "image" | "file";++export type AttachmentCandidate = FileAttachment & {+ resolvedPath: string;+};++export type AttachmentExtractionOptions = {+ cwd?: string;+ homeDir?: string;+ classifyAttachment?: (resolvedPath: string) => AttachmentKind | null;+};++export function normalizeComposerPath(raw: string): string | null {+ const trimmed = raw+ .trim()+ .replace(/^@/, "")+ .replace(/^"(.*)"$/, "$1");+ if (!trimmed) return null;+ if (trimmed.startsWith("file://")) {+ try {+ return decodeURIComponent(trimmed.slice("file://".length));+ } catch {+ return trimmed.slice("file://".length);+ }+ }+ return trimmed;+}++export function expandUserPath(+ path: string,+ cwd: string = process.cwd(),+ homeDir: string | undefined = process.env.HOME,+): string {+ if (path === "~") {+ return homeDir ?? path;+ }+ if (path.startsWith("~/")) {+ return resolve(homeDir ?? "~", path.slice(2));+ }+ return resolve(cwd, path);+}++export function formatAttachmentMention(path: string): string {+ return /\s/.test(path) ? `@"${path}"` : `@${path}`;+}++export function detectAttachmentKind(path: string): AttachmentKind | null {+ const ext = extname(path).toLowerCase();+ if (ext in IMAGE_MIME_TYPES) {+ return "image";+ }+ if (SUPPORTED_FILE_EXTENSIONS.has(ext.replace(".", ""))) {+ return "file";+ }+ return null;+}++export function isImageAttachment(path: string): boolean {+ return detectAttachmentKind(path) === "image";+}++export function isSupportedAttachment(path: string): boolean {+ return detectAttachmentKind(path) !== null;+}++function buildAttachmentCandidate(+ rawPath: string,+ options: AttachmentExtractionOptions = {},+): AttachmentCandidate | null {+ const normalized = normalizeComposerPath(rawPath);+ if (!normalized) return null;+ const resolvedPath = expandUserPath(+ normalized,+ options.cwd,+ options.homeDir,+ );+ const kind = options.classifyAttachment?.(resolvedPath) ?? detectAttachmentKind(resolvedPath);+ if (!kind) return null;+ return {+ type: kind,+ path: resolvedPath,+ resolvedPath,+ filename: basename(resolvedPath),+ mimeType: kind === "image" ? IMAGE_MIME_TYPES[extname(resolvedPath).toLowerCase()] : undefined,+ };+}++export function extractAttachmentsFromText(+ text: string,+ options: AttachmentExtractionOptions = {},+): AttachmentCandidate[] {+ const matches = [...text.matchAll(AT_MENTION_RE)];+ const attachments: AttachmentCandidate[] = [];+ const seen = new Set<string>();++ for (const match of matches) {+ const rawPath = match[2] ?? match[3] ?? "";+ const candidate = buildAttachmentCandidate(rawPath, options);+ if (!candidate) {+ continue;+ }+ if (seen.has(candidate.resolvedPath)) {+ continue;+ }+ seen.add(candidate.resolvedPath);+ attachments.push(candidate);+ }++ return attachments;+}++export function extractFilePathsFromPaste(+ text: string,+ options: Omit<AttachmentExtractionOptions, "classifyAttachment"> = {},+): string[] {+ const matches = [...text.matchAll(PASTED_PATH_RE)];+ const paths: string[] = [];+ const seen = new Set<string>();++ for (const match of matches) {+ const rawPath = match[1] ?? match[2] ?? match[3] ?? "";+ const normalized = normalizeComposerPath(rawPath);+ if (!normalized) {+ continue;+ }+ const resolvedPath = expandUserPath(normalized, options.cwd, options.homeDir);+ if (seen.has(resolvedPath)) {+ continue;+ }+ seen.add(resolvedPath);+ paths.push(resolvedPath);+ }++ return paths;+}diff --git a/jiuwenclaw/cli/src/core/commands/builtins/init.ts b/jiuwenclaw/cli/src/core/commands/builtins/init.tsnew file mode 100644index 0000000000..97f0fe8ded--- /dev/null+++ b/jiuwenclaw/cli/src/core/commands/builtins/init.ts@@ -0,0 +1,272 @@+import { addError, addInfo } from "../helpers.js";+import { CommandKind, type SlashCommand } from "../types.js";+import type { UserAnswer } from "../../event-handlers.js";++type InitModelConfig = {+ model_provider: string;+ model: string;+ api_base: string;+ api_key: string;+};++type StoredConfigPayload = Partial<InitModelConfig> & {+ api_key_set?: boolean;+};++type ValidateModelPayload = {+ provider?: string;+ model?: string;+ response?: string;+};++export function createInitCommand(): SlashCommand {+ return {+ name: "init",+ description: "Guide default model setup",+ usage: "/init",+ example: "/init",+ kind: CommandKind.BUILT_IN,+ action: async (ctx) => {+ try {+ const stored = await readStoredModelConfig(ctx);+ const config = await runInitModelWizard(ctx, stored);+ if (!config) {+ ctx.addItem(addInfo(ctx.sessionId, "Initialization cancelled before saving.", "i"));+ return;+ }++ await persistModelConfig(ctx, config);+ ctx.addItem(+ addInfo(+ ctx.sessionId,+ `Default model saved: ${config.model_provider}/${config.model}`,+ "i",+ ),+ );+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ ctx.addItem(addError(ctx.sessionId, `init failed: ${message}`));+ }+ },+ };+}++async function readStoredModelConfig(+ ctx: Parameters<SlashCommand["action"]>[0],+): Promise<StoredConfigPayload> {+ const payload = await ctx.request<StoredConfigPayload>("config.get", { key: "model_default" });+ return {+ model_provider: String(payload.model_provider ?? "").trim(),+ model: String(payload.model ?? "").trim(),+ api_base: String(payload.api_base ?? "").trim(),+ api_key: String(payload.api_key ?? "").trim(),+ api_key_set: payload.api_key_set === true || String(payload.api_key ?? "").trim().length > 0,+ };+}++async function runInitModelWizard(+ ctx: Parameters<SlashCommand["action"]>[0],+ stored: StoredConfigPayload,+): Promise<InitModelConfig | null> {+ let candidate = buildInitialCandidate(stored);++ if (hasCompleteConfig(candidate)) {+ const maskedKey = stored.api_key_set ? "already set" : "missing";+ const useExisting = await askYesNo(+ ctx,+ "Current Config",+ `Found an existing default model:\nprovider: ${candidate.model_provider}\nmodel: ${candidate.model}\napi_base: ${candidate.api_base}\napi_key: ${maskedKey}\n\nValidate and keep this configuration?`,+ "Keep current config",+ "Edit it",+ );+ if (useExisting) {+ const validated = await validateModelConfig(ctx, candidate);+ if (validated.ok) {+ ctx.addItem(+ addInfo(+ ctx.sessionId,+ `Model validation succeeded for ${validated.payload.provider ?? candidate.model_provider}/${validated.payload.model ?? candidate.model}.`,+ "i",+ ),+ );+ return candidate;+ }+ ctx.addItem(addError(ctx.sessionId, `Existing model config failed validation: ${validated.error}`));+ }+ }++ while (true) {+ candidate = await promptForModelConfig(ctx, candidate, stored.api_key_set === true);+ const validation = await validateModelConfig(ctx, candidate);+ if (validation.ok) {+ ctx.addItem(+ addInfo(+ ctx.sessionId,+ `Model validation succeeded for ${validation.payload.provider ?? candidate.model_provider}/${validation.payload.model ?? candidate.model}.`,+ "i",+ ),+ );+ return candidate;+ }++ ctx.addItem(addError(ctx.sessionId, `Model validation failed: ${validation.error}`));+ const retry = await askYesNo(+ ctx,+ "Validation Failed",+ "The model probe failed. Do you want to re-enter the configuration?",+ "Retry",+ "Cancel init",+ );+ if (!retry) {+ return null;+ }+ }+}++function buildInitialCandidate(stored: StoredConfigPayload): InitModelConfig {+ return {+ model_provider: stored.model_provider ?? "",+ model: stored.model ?? "",+ api_base: stored.api_base ?? "",+ api_key: stored.api_key ?? "",+ };+}++function hasCompleteConfig(config: InitModelConfig): boolean {+ return Boolean(+ config.model_provider.trim() &&+ config.model.trim() &&+ config.api_base.trim() &&+ config.api_key.trim(),+ );+}++async function promptForModelConfig(+ ctx: Parameters<SlashCommand["action"]>[0],+ current: InitModelConfig,+ hadStoredApiKey: boolean,+): Promise<InitModelConfig> {+ const provider = await askRequiredText(+ ctx,+ "Provider",+ buildTextPrompt(+ "Enter the default model provider to use for chat.",+ current.model_provider,+ "Examples: openai, deepseek, anthropic, openrouter",+ ),+ );+ const model = await askRequiredText(+ ctx,+ "Model",+ buildTextPrompt(+ "Enter the default model name.",+ current.model,+ "Examples: gpt-4.1, deepseek-chat, claude-3-7-sonnet, openai/gpt-4.1",+ ),+ );+ const apiBase = await askRequiredText(+ ctx,+ "API Base",+ buildTextPrompt(+ "Enter the API base URL for the model provider.",+ current.api_base,+ "Example: https://api.openai.com/v1",+ ),+ );+ const apiKeyHint =+ current.api_key.trim().length > 0 || hadStoredApiKey+ ? "A key is already stored. Re-enter it here to validate and save this configuration."+ : "Enter the API key for this provider.";+ const apiKey = await askRequiredText(+ ctx,+ "API Key",+ `${apiKeyHint}\nInput is not masked in the TUI.`,+ );++ return {+ model_provider: provider,+ model,+ api_base: apiBase,+ api_key: apiKey,+ };+}++async function validateModelConfig(+ ctx: Parameters<SlashCommand["action"]>[0],+ config: InitModelConfig,+): Promise<{ ok: true; payload: ValidateModelPayload } | { ok: false; error: string }> {+ try {+ const payload = await ctx.request<ValidateModelPayload>("config.validate_model", config);+ return { ok: true, payload };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ return { ok: false, error: message };+ }+}++async function persistModelConfig(+ ctx: Parameters<SlashCommand["action"]>[0],+ config: InitModelConfig,+): Promise<void> {+ await ctx.request("config.set", config);+}++async function askRequiredText(+ ctx: Parameters<SlashCommand["action"]>[0],+ header: string,+ question: string,+): Promise<string> {+ while (true) {+ const [answer] = await ctx.askQuestions(+ [+ {+ header,+ question,+ options: [],+ },+ ],+ "local_command",+ );+ const value = extractAnswerText(answer).trim();+ if (value) {+ return value;+ }+ ctx.addItem(addError(ctx.sessionId, `${header} is required.`));+ }+}++async function askYesNo(+ ctx: Parameters<SlashCommand["action"]>[0],+ header: string,+ question: string,+ yesLabel: string,+ noLabel: string,+): Promise<boolean> {+ const [answer] = await ctx.askQuestions(+ [+ {+ header,+ question,+ options: [{ label: yesLabel }, { label: noLabel }],+ },+ ],+ "local_command",+ );+ return extractAnswerText(answer) === yesLabel;+}++function extractAnswerText(answer: UserAnswer | undefined): string {+ if (!answer) return "";+ return String(answer.custom_input ?? answer.selected_options[0] ?? "").trim();+}++function buildTextPrompt(base: string, currentValue: string, hint?: string): string {+ const lines = [base];+ if (currentValue.trim()) {+ lines.push(`Current value: ${currentValue.trim()}`);+ }+ if (hint) {+ lines.push(hint);+ }+ return lines.join("\n");+}diff --git a/jiuwenclaw/cli/src/core/commands/builtins/plan.ts b/jiuwenclaw/cli/src/core/commands/builtins/plan.tsindex 56511b6039..5c18ab43da 100644--- a/jiuwenclaw/cli/src/core/commands/builtins/plan.ts+++ b/jiuwenclaw/cli/src/core/commands/builtins/plan.ts@@ -48,7 +48,7 @@ export function createPlanCommand(): SlashCommand {return;}- const requestId = ctx.sendMessage(value, target);+ const requestId = ctx.sendMessage(value, undefined, target);if (!requestId) {ctx.addItem(addInfo(ctx.sessionId, "offline: waiting for reconnect before sending plan request", "p"),diff --git a/jiuwenclaw/cli/src/core/commands/registry.ts b/jiuwenclaw/cli/src/core/commands/registry.tsindex bfb8d4d4a1..04bbc6fbb0 100644--- a/jiuwenclaw/cli/src/core/commands/registry.ts+++ b/jiuwenclaw/cli/src/core/commands/registry.ts@@ -10,6 +10,7 @@ import { createDiffCommand } from "./builtins/diff.js";import { createExitCommand } from "./builtins/exit.js";import { createHelpCommand } from "./builtins/help.js";import { createHotkeyCommand } from "./builtins/hotkey.js";+import { createInitCommand } from "./builtins/init.js";import { createModelCommand } from "./builtins/model.js";import { createModeCommand } from "./builtins/mode.js";import { createPlanCommand } from "./builtins/plan.js";@@ -24,6 +25,7 @@ export function createBuiltinCommands(): SlashCommand[] {createHelpCommand(() => commands),createAddDirCommand(),createClearCommand(),+ createInitCommand(),createColorCommand(),createCompactCommand(),createConfigCommand(),diff --git a/jiuwenclaw/cli/src/core/commands/types.ts b/jiuwenclaw/cli/src/core/commands/types.tsindex 3d29d15ccc..33ee3a7d86 100644--- a/jiuwenclaw/cli/src/core/commands/types.ts+++ b/jiuwenclaw/cli/src/core/commands/types.ts@@ -1,5 +1,7 @@import type { HistoryItem } from "../types.js";import type { AccentColorName, ThemeName } from "../../ui/theme.js";+import type { PendingQuestionItem, UserAnswer } from "../event-handlers.js";+import type { FileAttachment } from "../protocol.js";export type ConnectionStatus = "idle" | "connecting" | "connected" | "reconnecting" | "auth_failed";@@ -21,8 +23,10 @@ export interface CommandContext {params: Record<string, unknown>,timeoutMs?: number,) => Promise<T>;+ askQuestions: (questions: PendingQuestionItem[], source?: string) => Promise<UserAnswer[]>;sendMessage: (content: string,+ attachments?: FileAttachment[],mode?: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "team",) => string | null;sessionId: string;diff --git a/jiuwenclaw/cli/src/core/init-scanner.ts b/jiuwenclaw/cli/src/core/init-scanner.tsnew file mode 100644index 0000000000..378e4c6a1c--- /dev/null+++ b/jiuwenclaw/cli/src/core/init-scanner.ts@@ -0,0 +1,490 @@+import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";+import { join } from "node:path";++export interface ProjectInfo {+ root: string;+ hasClaudeMd: boolean;+ languages: string[];+ frameworks: string[];+ buildTools: string[];+ testFrameworks: string[];+ lintTools: string[];+ packageManagers: string[];+ fileCounts: Record<string, number>;+ topLevelFiles: string[];+ topLevelDirs: string[];+ aiToolConfigs: string[];+ gitTracked: boolean;+ isMonorepo: boolean;+}++/** Scanning rules for detecting project characteristics. */+const PROJECT_CONFIG_FILES: Record<string, { file: string; category: string }> = {+ node: { file: "package.json", category: "languages" },+ python: { file: "pyproject.toml", category: "languages" },+ "python (setup.py)": { file: "setup.py", category: "languages" },+ "python (requirements.txt)": { file: "requirements.txt", category: "languages" },+ rust: { file: "Cargo.toml", category: "languages" },+ go: { file: "go.mod", category: "languages" },+ java: { file: "pom.xml", category: "languages" },+ "java (gradle)": { file: "build.gradle", category: "languages" },+ "java (gradle kotlin)": { file: "build.gradle.kts", category: "languages" },+ ruby: { file: "Gemfile", category: "languages" },+ php: { file: "composer.json", category: "languages" },+ swift: { file: "Package.swift", category: "languages" },+ kotlin: { file: "build.gradle.kts", category: "languages" },+ scala: { file: "build.sbt", category: "languages" },+ dart: { file: "pubspec.yaml", category: "languages" },+ dotnet: { file: "*.csproj", category: "languages" },+ terraform: { file: "*.tf", category: "languages" },+};++const BUILD_TOOL_FILES: Record<string, string> = {+ "Makefile": "make",+ "CMakeLists.txt": "cmake",+ "meson.build": "meson",+ "package.json": "npm/yarn/pnpm/bun",+ "pyproject.toml": "uv/pip/poetry",+ "Cargo.toml": "cargo",+ "go.mod": "go modules",+ "pom.xml": "maven",+ "build.gradle": "gradle",+ "build.gradle.kts": "gradle (kotlin)",+ "build.sbt": "sbt",+ "Gemfile": "bundler",+ "composer.json": "composer",+ "pubspec.yaml": "pub",+};++const TEST_FRAMEWORK_INDICATORS: Record<string, string> = {+ jest: "jest.config",+ vitest: "vitest.config",+ mocha: ".mocharc",+ pytest: "pytest.ini",+ "unittest (python)": "tests/",+ cargo_test: "Cargo.toml",+ go_test: "_test.go",+ rspec: "spec/",+};++const LINT_TOOL_INDICATORS: Record<string, string> = {+ eslint: ".eslintrc",+ prettier: ".prettierrc",+ biome: "biome.json",+ ruff: "ruff.toml",+ flake8: ".flake8",+ black: "pyproject.toml",+ clippy: "Cargo.toml",+ golangci: ".golangci.yml",+ rubocop: ".rubocop.yml",+ phpstan: "phpstan.neon",+};++const AI_TOOL_CONFIG_FILES = [+ ".cursorrules",+ ".cursor/rules",+ ".github/copilot-instructions.md",+ ".github/copilot-instructions",+ ".windsurfrules",+ ".aider.input.history",+ ".ai/",+ "AGENTS.md",+];++const MONOREPO_INDICATORS = [+ "lerna.json",+ "pnpm-workspace.yaml",+ "turbo.json",+ "nx.json",+ "bunfig.toml",+];++/**+ * Scan a project directory and return structured information.+ */+export function scanProject(root: string): ProjectInfo {+ const languages: string[] = [];+ const frameworks: string[] = [];+ const buildTools: string[] = [];+ const testFrameworks: string[] = [];+ const lintTools: string[] = [];+ const packageManagers: string[] = [];+ const fileCounts: Record<string, number> = {};+ const aiToolConfigs: string[] = [];++ const topLevelEntries = safeReaddir(root);+ const topLevelFiles = topLevelEntries.filter((e) => isFile(root, e));+ const topLevelDirs = topLevelEntries.filter((e) => isDir(root, e));++ // Detect languages from config files+ for (const [name, { file, category }] of Object.entries(PROJECT_CONFIG_FILES)) {+ if (file.includes("*")) {+ // Glob pattern - check for matching files+ const ext = file.replace("*", "");+ if (topLevelFiles.some((f) => f.endsWith(ext))) {+ languages.push(name);+ }+ } else if (topLevelFiles.includes(file)) {+ languages.push(name);+ }+ }++ // Detect build tools+ for (const [file, tool] of Object.entries(BUILD_TOOL_FILES)) {+ if (topLevelFiles.includes(file)) {+ buildTools.push(tool);+ }+ }++ // Detect test frameworks+ for (const [framework, indicator] of Object.entries(TEST_FRAMEWORK_INDICATORS)) {+ if (indicator.endsWith("/")) {+ if (topLevelDirs.includes(indicator)) {+ testFrameworks.push(framework);+ }+ } else if (topLevelFiles.some((f) => f.includes(indicator))) {+ testFrameworks.push(framework);+ }+ }++ // Detect lint tools (check both root files and deeper config)+ for (const [tool, indicator] of Object.entries(LINT_TOOL_INDICATORS)) {+ if (topLevelFiles.includes(indicator)) {+ lintTools.push(tool);+ }+ }++ // Detect package managers+ if (topLevelFiles.includes("package-lock.json")) packageManagers.push("npm");+ if (topLevelFiles.includes("yarn.lock")) packageManagers.push("yarn");+ if (topLevelFiles.includes("pnpm-lock.yaml")) packageManagers.push("pnpm");+ if (topLevelFiles.includes("bun.lockb") || topLevelFiles.includes("bun.lock")) packageManagers.push("bun");+ if (topLevelFiles.includes("uv.lock")) packageManagers.push("uv");+ if (topLevelFiles.includes("poetry.lock")) packageManagers.push("poetry");+ if (topLevelFiles.includes("Pipfile.lock")) packageManagers.push("pipenv");++ // Count file types+ const extensions = new Set<string>();+ for (const entry of topLevelEntries) {+ const ext = getExtension(entry);+ if (ext) extensions.add(ext);+ }+ // Scan subdirectories for file counts+ for (const dir of topLevelDirs.filter((d) => !d.startsWith(".") && d !== "node_modules")) {+ scanDirFileCounts(join(root, dir), fileCounts, 2);+ }++ // Detect AI tool configs+ for (const aiFile of AI_TOOL_CONFIG_FILES) {+ if (aiFile.endsWith("/")) {+ if (isDir(root, aiFile.slice(0, -1))) {+ aiToolConfigs.push(aiFile);+ }+ } else if (existsSync(join(root, aiFile))) {+ aiToolConfigs.push(aiFile);+ }+ }++ // Check git+ const gitTracked = existsSync(join(root, ".git"));++ // Check monorepo+ const isMonorepo = MONOREPO_INDICATORS.some((f) => topLevelFiles.includes(f));++ // Check CLAUDE.md+ const hasClaudeMd =+ existsSync(join(root, "CLAUDE.md")) ||+ existsSync(join(root, "CLAUDE.local.md"));++ // Read package.json for framework detection+ if (topLevelFiles.includes("package.json")) {+ const pkg = readPackageJson(root);+ if (pkg) {+ const allDeps = {+ ...pkg.dependencies,+ ...pkg.devDependencies,+ };+ const depNames = Object.keys(allDeps);++ // Framework detection+ if (depNames.some((d) => d.includes("react") || d.includes("next"))) frameworks.push("React");+ if (depNames.some((d) => d.includes("vue"))) frameworks.push("Vue");+ if (depNames.some((d) => d.includes("svelte"))) frameworks.push("Svelte");+ if (depNames.some((d) => d.includes("angular"))) frameworks.push("Angular");+ if (depNames.some((d) => d.includes("django"))) frameworks.push("Django");+ if (depNames.some((d) => d.includes("fastapi"))) frameworks.push("FastAPI");+ if (depNames.some((d) => d.includes("flask"))) frameworks.push("Flask");+ if (depNames.some((d) => d.includes("express"))) frameworks.push("Express");+ if (depNames.some((d) => d.includes("tailwind"))) frameworks.push("TailwindCSS");+ if (depNames.some((d) => d.includes("vite"))) frameworks.push("Vite");+ if (depNames.some((d) => d.includes("webpack"))) frameworks.push("Webpack");+ if (depNames.some((d) => d.includes("typescript") || pkg.devDependencies?.typescript)) {+ if (!languages.includes("typescript")) {+ frameworks.push("TypeScript");+ }+ }+ }+ }++ // Read pyproject.toml for Python framework detection+ if (topLevelFiles.includes("pyproject.toml")) {+ const content = readFile(join(root, "pyproject.toml"));+ if (content) {+ if (content.includes("django")) frameworks.push("Django");+ if (content.includes("fastapi")) frameworks.push("FastAPI");+ if (content.includes("flask")) frameworks.push("Flask");+ if (content.includes("pytest")) testFrameworks.push("pytest");+ }+ }++ return {+ root,+ hasClaudeMd,+ languages,+ frameworks,+ buildTools,+ testFrameworks,+ lintTools,+ packageManagers,+ fileCounts,+ topLevelFiles,+ topLevelDirs,+ aiToolConfigs,+ gitTracked,+ isMonorepo,+ };+}++/**+ * Generate CLAUDE.md content from project information.+ */+export function generateClaudeMd(info: ProjectInfo): string {+ const lines: string[] = [];++ lines.push("# CLAUDE.md");+ lines.push("");+ lines.push(+ "This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.",+ );+ lines.push("");++ // Project Overview+ lines.push("## Project Overview");+ lines.push("");+ if (info.languages.length > 0) {+ lines.push(`Primary languages: ${info.languages.join(", ")}`);+ }+ if (info.frameworks.length > 0) {+ lines.push(`Frameworks: ${info.frameworks.join(", ")}`);+ }+ if (info.isMonorepo) {+ lines.push("This is a monorepo.");+ }+ lines.push("");++ // Directory Structure+ lines.push("## Directory Structure");+ lines.push("");+ for (const dir of info.topLevelDirs.filter((d) => !d.startsWith("."))) {+ lines.push(`- \`${dir}/\` - ${inferDirDescription(dir)}`);+ }+ lines.push("");++ // Build/Lint/Test Commands+ const hasNpm = info.buildTools.some((t) => t.includes("npm"));+ const hasPython = info.buildTools.some((t) => t.includes("uv") || t.includes("pip"));++ lines.push("## Build/Lint/Test Commands");+ lines.push("");+ if (hasNpm) {+ lines.push("```bash");+ lines.push("# Install dependencies");+ lines.push("npm install");+ lines.push("");+ lines.push("# Build");+ lines.push("npm run build");+ lines.push("");+ lines.push("# Test");+ lines.push("npm test");+ lines.push("");+ lines.push("# Lint");+ lines.push("npm run lint");+ lines.push("```");+ lines.push("");+ }+ if (hasPython) {+ lines.push("```bash");+ lines.push("# Install dependencies");+ lines.push("uv sync");+ lines.push("");+ lines.push("# Test");+ lines.push("uv run pytest");+ lines.push("");+ if (info.lintTools.includes("ruff")) {+ lines.push("# Lint");+ lines.push("uv run ruff check .");+ }+ lines.push("```");+ lines.push("");+ }+ if (!hasNpm && !hasPython && info.buildTools.length === 0) {+ lines.push("_(Build commands not yet configured. Add them here.)_");+ lines.push("");+ }++ // Code Style+ lines.push("## Code Style");+ lines.push("");+ if (info.lintTools.length > 0) {+ lines.push(`Linting/formatting tools: ${info.lintTools.join(", ")}`);+ if (info.lintTools.includes("prettier")) {+ lines.push("- Format: `npx prettier --write .`");+ }+ if (info.lintTools.includes("ruff")) {+ lines.push("- Lint: `ruff check .`; Format: `ruff format .`");+ }+ if (info.lintTools.includes("eslint")) {+ lines.push("- Lint: `npx eslint .`");+ }+ } else {+ lines.push("_(Code style not yet configured. Add linting/formatting rules here.)_");+ }+ lines.push("");++ // Agent-Specific Instructions+ lines.push("## Important Conventions");+ lines.push("");+ lines.push("- Before making any changes, read relevant source files first");+ lines.push("- Use all available tools to ensure changes are correct before submitting");+ lines.push("- Never remove or modify existing tests unless explicitly requested");+ lines.push("- Always write safe, secure, and correct code");+ lines.push("");++ // Existing AI Configs+ if (info.aiToolConfigs.length > 0) {+ lines.push("## Existing AI Tool Configurations");+ lines.push("");+ lines.push("The following AI tool config files were detected and may contain relevant context:");+ lines.push("");+ for (const aiFile of info.aiToolConfigs) {+ lines.push(`- \`${aiFile}\``);+ }+ lines.push("");+ }++ return lines.join("\n");+}++// --- Helper functions ---++function safeReaddir(dir: string): string[] {+ try {+ return readdirSync(dir);+ } catch {+ return [];+ }+}++function isFile(root: string, name: string): boolean {+ try {+ return statSync(join(root, name)).isFile();+ } catch {+ return false;+ }+}++function isDir(root: string, name: string): boolean {+ try {+ return statSync(join(root, name)).isDirectory();+ } catch {+ return false;+ }+}++function getExtension(name: string): string {+ const dot = name.lastIndexOf(".");+ return dot >= 0 ? name.slice(dot + 1).toLowerCase() : "";+}++function scanDirFileCounts(+ dir: string,+ counts: Record<string, number>,+ remainingDepth: number,+): void {+ if (remainingDepth <= 0) return;+ const entries = safeReaddir(dir);+ for (const entry of entries) {+ if (entry === "node_modules" || entry === ".git" || entry.startsWith(".")) continue;+ const fullPath = join(dir, entry);+ try {+ const stat = statSync(fullPath);+ if (stat.isFile()) {+ const ext = getExtension(entry);+ counts[ext] = (counts[ext] ?? 0) + 1;+ } else if (stat.isDirectory()) {+ scanDirFileCounts(fullPath, counts, remainingDepth - 1);+ }+ } catch {+ // Skip inaccessible files+ }+ }+}++function readPackageJson(root: string): {+ dependencies?: Record<string, string>;+ devDependencies?: Record<string, string>;+} | null {+ const content = readFile(join(root, "package.json"));+ if (!content) return null;+ try {+ return JSON.parse(content);+ } catch {+ return null;+ }+}++function readFile(path: string): string | null {+ try {+ return readFileSync(path, "utf-8");+ } catch {+ return null;+ }+}++function inferDirDescription(name: string): string {+ const descriptions: Record<string, string> = {+ src: "source code",+ lib: "library code",+ app: "application code",+ packages: "monorepo packages",+ apps: "monorepo applications",+ test: "tests",+ tests: "tests",+ __test__: "tests",+ __tests__: "tests",+ spec: "test specs",+ docs: "documentation",+ doc: "documentation",+ scripts: "build/utility scripts",+ bin: "executable scripts",+ config: "configuration files",+ conf: "configuration files",+ public: "static assets",+ static: "static assets",+ assets: "static assets",+ components: "UI components",+ pages: "page components",+ routes: "route definitions",+ api: "API endpoints",+ services: "service layer",+ utils: "utility functions",+ helpers: "helper functions",+ types: "TypeScript type definitions",+ models: "data models",+ schemas: "data schemas",+ migrations: "database migrations",+ docker: "Docker configuration",+ ".github": "GitHub workflows and config",+ };+ return descriptions[name] || "project files";+}diff --git a/jiuwenclaw/cli/src/core/protocol.ts b/jiuwenclaw/cli/src/core/protocol.tsindex 6f0f3587c9..a827595bc4 100644--- a/jiuwenclaw/cli/src/core/protocol.ts+++ b/jiuwenclaw/cli/src/core/protocol.ts@@ -1,8 +1,22 @@+export interface FileAttachment {+ readonly type: "file" | "image";+ readonly path: string;+ readonly filename: string;+ readonly mimeType?: string;+ readonly content?: string; // base64 for images+}+export interface ReqFrame {readonly type: "req";readonly id: string;readonly method: string;- readonly params: Record<string, unknown>;+ readonly params: Record<string, unknown> & {+ content?: string;+ mode?: string;+ query?: string;+ session_id?: string;+ attachments?: FileAttachment[];+ };}export interface ResFrame {diff --git a/jiuwenclaw/cli/src/ui/app-screen.ts b/jiuwenclaw/cli/src/ui/app-screen.tsindex 56348e6694..ae27eaa5e1 100644--- a/jiuwenclaw/cli/src/ui/app-screen.ts+++ b/jiuwenclaw/cli/src/ui/app-screen.ts@@ -11,13 +11,20 @@ import {matchesKey,} from "@mariozechner/pi-tui";import { statSync } from "node:fs";-import { basename, extname, resolve } from "node:path";import { spawnSync } from "node:child_process";import type { CliPiAppState } from "../app-state.js";+import {+ extractAttachmentsFromText,+ extractFilePathsFromPaste,+ formatAttachmentMention,+ isImageAttachment,+ isSupportedAttachment,+} from "../core/attachments.js";import { CommandService, parseSlashCommand } from "../core/commands/CommandService.js";import { addError, addInfo } from "../core/commands/helpers.js";-import type { SessionListPayload, SessionMeta } from "../core/commands/builtins/resume.js";+import type { FileAttachment } from "../core/protocol.js";import type { ModelListPayload } from "../core/commands/builtins/model.js";+import type { SessionListPayload, SessionMeta } from "../core/commands/builtins/resume.js";import { handleAppScreenKeyInput } from "./keymap.js";import { buildAppScreenLines } from "./screen-layout.js";import {@@ -29,7 +36,6 @@ import { padToWidth } from "./rendering/text.js";import { editorTheme, palette, selectListTheme } from "./theme.js";const END_CURSOR = "\x1b[7m \x1b[0m";-const COMPOSER_ATTACHMENT_TOKEN_RE = /\[Image #(\d+)\]/g;const PERMISSION_TOOL_RE = /工具\s+`([^`]+)`\s+需要授权/;const PERMISSION_RISK_RE = /安全风险评估:\**\s*([^\s*]+)?\s*\**([^*\n]+?风险)\**/m;const PERMISSION_QUOTE_RE = /^>\s*(.+)$/gm;@@ -43,13 +49,6 @@ type PermissionSummary = {description?: string;};-type ComposerAttachment = {- id: string;- kind: "image";- path: string;- filename: string;-};-type ResumeSessionListState = {list: SelectList;sessions: SessionMeta[];@@ -62,14 +61,6 @@ type ModelListState = {current: string;};-const IMAGE_MIME_TYPES: Record<string, string> = {- ".png": "image/png",- ".jpg": "image/jpeg",- ".jpeg": "image/jpeg",- ".gif": "image/gif",- ".webp": "image/webp",-};-function resolveFdBinary(): string | null {for (const candidate of ["fd", "fdfind"]) {const result = spawnSync(candidate, ["--version"], {@@ -83,141 +74,6 @@ function resolveFdBinary(): string | null {return null;}-function normalizeComposerPath(raw: string): string | null {- const trimmed = raw- .trim()- .replace(/^@/, "")- .replace(/^"(.*)"$/, "$1");- if (!trimmed) return null;- if (trimmed.startsWith("file://")) {- try {- return decodeURIComponent(trimmed.slice("file://".length));- } catch {- return trimmed.slice("file://".length);- }- }- return trimmed;-}--function looksLikeImagePath(path: string): boolean {- return extname(path).toLowerCase() in IMAGE_MIME_TYPES;-}--function expandUserPath(path: string): string {- if (path === "~") {- return process.env.HOME ?? path;- }- if (path.startsWith("~/")) {- return resolve(process.env.HOME ?? "~", path.slice(2));- }- return resolve(process.cwd(), path);-}--function formatComposerAttachmentPath(path: string): string {- return /\s/.test(path) ? `@"${path}"` : `@${path}`;-}--function composerAttachmentToken(index: number): string {- return `[Image #${index}] `;-}--function findAttachmentTokenAtCursor(- line: string,- cursorCol: number,-): { start: number; end: number } | null {- for (const match of line.matchAll(COMPOSER_ATTACHMENT_TOKEN_RE)) {- const start = match.index ?? -1;- if (start < 0) continue;- const end = start + match[0].length;- if (cursorCol > start && cursorCol <= end) {- return { start, end };- }- }- return null;-}--function syncComposerImageTokens(- text: string,- existingAttachments: ComposerAttachment[],- shouldConsume: (path: string) => boolean,-): { normalizedText: string; attachments: ComposerAttachment[] } {- let attachments = [...existingAttachments];- let working = text;-- const findOrAddAttachment = (resolvedPath: string): number => {- const existingIndex = attachments.findIndex((attachment) => attachment.path === resolvedPath);- if (existingIndex >= 0) {- return existingIndex + 1;- }- attachments.push({- id: `attachment-${Date.now().toString(16)}-${attachments.length}`,- kind: "image",- path: resolvedPath,- filename: basename(resolvedPath),- });- return attachments.length;- };-- const consume = (rawPath: string): string | null => {- const normalized = normalizeComposerPath(rawPath);- if (!normalized) return null;- const resolved = expandUserPath(normalized);- if (!shouldConsume(resolved)) return null;- return composerAttachmentToken(findOrAddAttachment(resolved));- };-- working = working.replace(/(^|[\t ])@(?:"([^"]+)"|([^\s]+))/gm, (full, prefix, quoted, plain) => {- const replacement = consume(quoted ?? plain ?? "");- return replacement ? `${prefix}${replacement}` : full;- });-- working = working.replace(- /(^|[\t ])((?:file:\/\/[^\s]+|(?:~\/|\.{1,2}\/|\/)[^\s"'`]+\.(?:png|jpe?g|gif|webp)))(?=$|[\t ])/gim,- (full, prefix, rawPath) => {- const replacement = consume(rawPath ?? "");- return replacement ? `${prefix}${replacement}` : full;- },- );-- const tokenMatches = [...working.matchAll(/\[Image #(\d+)\]/g)];- const nextAttachments: ComposerAttachment[] = [];- for (const match of tokenMatches) {- const tokenIndex = Number.parseInt(match[1] ?? "", 10);- if (!Number.isFinite(tokenIndex) || tokenIndex < 1) {- continue;- }- const attachment = attachments[tokenIndex - 1];- if (attachment) {- nextAttachments.push(attachment);- }- }- attachments = nextAttachments;-- let tokenOrdinal = 0;- working = working.replace(/\[Image #(\d+)\]\s*/g, () => {- tokenOrdinal += 1;- return composerAttachmentToken(tokenOrdinal);- });-- const normalizedText = working- .replace(/[ \t]+\n/g, "\n")- .replace(/\n[ \t]+/g, "\n")- .replace(/[ \t]{2,}/g, " ");-- return { normalizedText, attachments };-}--function expandComposerImageTokens(text: string, attachments: ComposerAttachment[]): string {- return text.replace(/\[Image #(\d+)\]\s*/g, (_full, rawIndex: string) => {- const index = Number.parseInt(rawIndex, 10);- if (!Number.isFinite(index) || index < 1) {- return "";- }- const attachment = attachments[index - 1];- return attachment ? `${formatComposerAttachmentPath(attachment.path)} ` : "";- });-}-function isPermissionRequest(source: string | undefined, questionText: string): boolean {return source === "permission" || PERMISSION_TOOL_RE.test(questionText);}@@ -450,8 +306,6 @@ export class AppScreen implements Component, Focusable {private activeQuestionId: string | null = null;private activeQuestionIndex = 0;private draftBeforeQuestion = "";- private draftAttachmentsBeforeQuestion: ComposerAttachment[] = [];- private composerAttachments: ComposerAttachment[] = [];private syncingComposerInput = false;private pendingQuestionAnswers = new Map<number, string>();private questionList: SelectList | null = null;@@ -485,7 +339,6 @@ export class AppScreen implements Component, Focusable {);this.editor.setAutocompleteProvider(this.composerAutocompleteProvider);this.editor.onChange = () => {- this.syncComposerAttachmentsFromEditor();this.tui.requestRender();};this.editor.onSubmit = (value) => {@@ -651,21 +504,15 @@ export class AppScreen implements Component, Focusable {return;}- if (- !snapshot.pendingQuestion &&- this.editor.getText().length === 0 &&- this.composerAttachments.length > 0- ) {- if (matchesKey(data, "backspace")) {- this.composerAttachments = this.composerAttachments.slice(0, -1);- this.tui.requestRender();- return;- }- }-- if (!snapshot.pendingQuestion && matchesKey(data, "backspace")) {- if (this.deleteComposerAttachmentTokenBackwards()) {- this.tui.requestRender();+ // 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,+ // so we detect file paths in any multi-character input.+ if (!snapshot.pendingQuestion && data.length > 4) {+ const pastedContent = data.replace(/\x1b\[200~/, "").replace(/\x1b\[201~/, "");+ const filePaths = extractFilePathsFromPaste(pastedContent);+ if (filePaths.length > 0) {+ this.handleDroppedFiles(filePaths);return;}}@@ -681,9 +528,7 @@ export class AppScreen implements Component, Focusable {this.editor.borderColor = snapshot.pendingQuestion? palette.border.question: palette.border.panel;- const editorLines = this.applyComposerTokenHighlight(- this.applySlashCommandHint(this.editor.render(width), width),- );+ const editorLines = this.applySlashCommandHint(this.editor.render(width), width);const composerPreviewLines: string[] = [];const questionLines = [...this.buildResumeSessionListLines(width),@@ -715,17 +560,16 @@ export class AppScreen implements Component, Focusable {private async handleSubmit(raw: string): Promise<void> {const text = raw.trim();- const content = this.composeOutgoingMessage(text);- if (!content) return;+ if (!text) return;++ const { content, attachments } = this.buildOutgoingMessage(text);const snapshot = this.state.getSnapshot();if (snapshot.pendingQuestion) {if (this.questionList === null) {this.state.answerQuestion(text);}- this.editor.addToHistory(text);this.editor.setText("");- this.composerAttachments = [];return;}@@ -733,21 +577,18 @@ export class AppScreen implements Component, Focusable {if (/^\/(?:resume|continue)\s*$/.test(text)) {this.editor.addToHistory(text);this.editor.setText("");- this.composerAttachments = [];await this.openResumeSessionList();return;}if (/^\/model\s*$/.test(text)) {this.editor.addToHistory(text);this.editor.setText("");- this.composerAttachments = [];await this.openModelList();return;}this.beginPendingSubmittedInput(text, snapshot);this.editor.addToHistory(text);this.editor.setText("");- this.composerAttachments = [];try {await this.commands.execute(text, {...this.state.getCommandContext(),@@ -761,7 +602,7 @@ export class AppScreen implements Component, Focusable {if (snapshot.isProcessing || snapshot.isPaused) {this.beginPendingSubmittedInput(text, snapshot);- const requestId = this.state.supplement(content);+ const requestId = this.state.supplement(content, attachments);if (!requestId) {this.clearPendingSubmittedInput();this.state.addItem({@@ -775,12 +616,11 @@ export class AppScreen implements Component, Focusable {}this.editor.addToHistory(text);this.editor.setText("");- this.composerAttachments = [];return;}this.beginPendingSubmittedInput(text, snapshot);- const requestId = this.state.sendMessage(content);+ const requestId = this.state.sendMessage(content, attachments);if (!requestId) {this.clearPendingSubmittedInput();this.state.addItem({@@ -795,7 +635,6 @@ export class AppScreen implements Component, Focusable {this.editor.addToHistory(text);this.editor.setText("");- this.composerAttachments = [];}private handleStateChange(): void {@@ -813,9 +652,7 @@ export class AppScreen implements Component, Focusable {this.activeQuestionIndex = 0;this.pendingQuestionAnswers.clear();this.draftBeforeQuestion = this.editor.getText();- this.draftAttachmentsBeforeQuestion = [...this.composerAttachments];this.editor.setText("");- this.composerAttachments = [];this.syncQuestionList(snapshot);} else if (questionId && this.activeQuestionId) {this.syncQuestionList(snapshot);@@ -828,8 +665,6 @@ export class AppScreen implements Component, Focusable {this.editor.setText(this.draftBeforeQuestion);}this.draftBeforeQuestion = "";- this.composerAttachments = [...this.draftAttachmentsBeforeQuestion];- this.draftAttachmentsBeforeQuestion = [];}this.syncTeamPanelSelection(snapshot);this.syncAnimationLoop(snapshot);@@ -1008,7 +843,9 @@ export class AppScreen implements Component, Focusable {this.tui.requestRender();} catch (error) {const message = error instanceof Error ? error.message : String(error);- this.state.addItem(addError(this.state.getSnapshot().sessionId, `Failed to switch model: ${message}`));+ this.state.addItem(+ addError(this.state.getSnapshot().sessionId, `Failed to switch model: ${message}`),+ );this.tui.requestRender();}}@@ -1023,73 +860,25 @@ export class AppScreen implements Component, Focusable {width,),...this.modelList.list.render(width),- padToWidth(palette.text.dim("↑/↓ choose · Enter switch · Esc cancel"), width),+ padToWidth(palette.text.dim("choose model · Enter switch · Esc cancel"), width),];}- private syncComposerAttachmentsFromEditor(): void {- if (this.syncingComposerInput) {- return;- }-- const originalText = this.editor.getText();- const { normalizedText, attachments } = syncComposerImageTokens(- originalText,- this.composerAttachments,- (path) => this.isComposerImageFile(path),- );-- this.composerAttachments = attachments;-- if (normalizedText !== originalText) {- this.syncingComposerInput = true;- this.editor.setText(normalizedText);- this.syncingComposerInput = false;- }- }-- private deleteComposerAttachmentTokenBackwards(): boolean {- const cursor = this.editor.getCursor();- const lines = this.editor.getLines();- const currentLine = lines[cursor.line] ?? "";- const tokenRange = findAttachmentTokenAtCursor(currentLine, cursor.col);- if (!tokenRange) {- return false;- }-- const nextLine =- `${currentLine.slice(0, tokenRange.start)}${currentLine.slice(tokenRange.end)}`.replace(- / {2,}/g,- " ",- );- const nextLines = [...lines];- nextLines[cursor.line] = nextLine;- const nextText = nextLines.join("\n");- const nextCol = Math.min(tokenRange.start, nextLine.length);-- this.syncingComposerInput = true;- this.editor.setText(nextText);- const editorState = this.editor as unknown as {- state?: { cursorLine: number; cursorCol: number };+ private buildOutgoingMessage(text: string): { content: string; attachments: FileAttachment[] } {+ return {+ content: text.replace(/[ \t]{2,}/g, " ").replace(/[ \t]+\n/g, "\n").trim(),+ attachments: this.collectComposerAttachments(text),};- if (editorState.state) {- editorState.state.cursorLine = cursor.line;- editorState.state.cursorCol = nextCol;- }- this.syncingComposerInput = false;- this.syncComposerAttachmentsFromEditor();- return true;}- private composeOutgoingMessage(text: string): string {- return expandComposerImageTokens(text, this.composerAttachments)- .replace(/[ \t]{2,}/g, " ")- .replace(/[ \t]+\n/g, "\n")- .trim();+ private collectComposerAttachments(text: string): FileAttachment[] {+ return extractAttachmentsFromText(text, {+ classifyAttachment: (path) => (this.isAcceptedAttachment(path) ? (isImageAttachment(path) ? "image" : "file") : null),+ }).map(({ resolvedPath, ...attachment }) => attachment);}- private isComposerImageFile(path: string): boolean {- if (!looksLikeImagePath(path)) {+ private isAcceptedAttachment(path: string): boolean {+ if (!isSupportedAttachment(path)) {return false;}@@ -1104,6 +893,23 @@ export class AppScreen implements Component, Focusable {}}+ /** Handle pasted/dragged content - detects file paths and converts to @path references. */+ private handleDroppedFiles(filePaths: string[]): void {+ const insertText = filePaths+ .filter((path) => this.isAcceptedAttachment(path))+ .map((path) => formatAttachmentMention(path))+ .join(" ");++ if (!insertText) return;++ const currentText = this.editor.getText();+ const newText = currentText ? `${currentText}\n${insertText}` : insertText;+ this.syncingComposerInput = true;+ this.editor.setText(newText);+ this.syncingComposerInput = false;+ this.tui.requestRender();+ }+private syncAnimationLoop(snapshot: ReturnType<CliPiAppState["getSnapshot"]>): void {const hasRunningTools = snapshot.toolExecutions.some((execution) => execution.tool.status === "running",@@ -1164,12 +970,6 @@ export class AppScreen implements Component, Focusable {return nextLines;}- private applyComposerTokenHighlight(editorLines: string[]): string[] {- return editorLines.map((line) =>- line.replace(COMPOSER_ATTACHMENT_TOKEN_RE, (token) => palette.text.info(token)),- );- }-private getInlineSlashCommandHint(): string | null {const text = this.editor.getText();if (!text.startsWith("/") || text.includes("\n")) {diff --git a/jiuwenclaw/gateway/agent_client.py b/jiuwenclaw/gateway/agent_client.pyindex 22c4241c48..d959916467 100644--- a/jiuwenclaw/gateway/agent_client.py+++ b/jiuwenclaw/gateway/agent_client.py@@ -24,6 +24,7 @@ from jiuwenclaw.schema.agent import AgentResponse, AgentResponseChunklogger = logging.getLogger(__name__)_STREAM_TRAILING_MESSAGE_GRACE_SECONDS = 0.7_UNARY_REQUEST_TIMEOUT_SECONDS = 60.0+_WS_MAX_SIZE = 8 * 2**20def _wire_request_id_key(request_id: Any) -> str:@@ -145,6 +146,7 @@ class WebSocketAgentServerClient(AgentServerClient):ping_interval=self._ping_interval,ping_timeout=self._ping_timeout,close_timeout=5.0,+ max_size=_WS_MAX_SIZE,)logger.info("[WebSocketAgentServerClient] 已连接: %s", uri)diff --git a/jiuwenclaw/gateway/message_handler.py b/jiuwenclaw/gateway/message_handler.pyindex 034f4f666c..a5fb40ae41 100644--- a/jiuwenclaw/gateway/message_handler.py+++ b/jiuwenclaw/gateway/message_handler.py@@ -6,11 +6,14 @@ from __future__ import annotationsimport loggingimport asyncio+import os+import reimport secretsimport timefrom abc import ABC, abstractmethodfrom dataclasses import dataclass, replacefrom enum import Enum+from pathlib import Pathfrom typing import TYPE_CHECKING, Any, Dictfrom jiuwenclaw.channel.base import ChannelTypefrom jiuwenclaw.e2a.constants import E2A_WIRE_INTERNAL_METADATA_KEYS@@ -26,6 +29,7 @@ logger = logging.getLogger(__name__)_ACP_CHANNEL_ID = "acp"_ACP_ORIGINAL_SESSION_ID_KEY = "acp_original_session_id"+_DEFAULT_INLINE_FILE_SIZE_LIMIT = 128 * 1024_KNOWN_JIUWENCLAW_SESSION_PREFIXES = ("sess_","acp_",@@ -122,7 +126,7 @@ class MessageHandler(ABC):self._stream_metadata: dict[str, dict[str, Any] | None] = {} # request_id -> request metadataself._stream_modes: dict[str, str] = {} # request_id -> modeself._pending_evolution_approval: dict[str, str] = {} # session_id -> approval_request_id- self._queued_supplement_input: dict[str, str] = {} # session_id -> queued_new_input+ self._queued_supplement_input: dict[str, dict[str, Any]] = {} # session_id -> queued supplement payloadself._session_evolution_in_progress: set[str] = set()self._acp_session_aliases: dict[str, str] = {} # external_session_id -> internal_session_idself._acp_session_alias_lock = asyncio.Lock()@@ -864,6 +868,165 @@ class MessageHandler(ABC):return externalreturn sid+ @staticmethod+ def _resolve_at_file_references(+ content: str,+ cwd: str | None = None,+ max_file_size: int | None = _DEFAULT_INLINE_FILE_SIZE_LIMIT,+ ) -> str:+ """Parse ``@path`` references in *content* and inline the file text.++ Supported forms:+ - ``@relative/path`` / ``@/absolute/path`` — resolved against *cwd*+ - ``@"path with spaces"`` — quoted paths+ - ``@path#L10-20`` — line-range suffix (ignored for now, whole file read)++ Returns content with ``@path`` replaced by a ``<file-content>`` block+ containing the actual text. If a file cannot be read the original+ ``@path`` is kept unchanged.+ """+ if not content:+ return content++ working_dir = cwd or os.getcwd()++ # Match @path or @"quoted path", optionally followed by #L... line range+ pattern = re.compile(+ r'(?P<prefix>(?:^|(?<=\s)))@(?:"(?P<quoted>[^"]+)"|(?P<plain>[^\s#]+))(?:#[^#\s]*)?'+ )++ def _replacer(m: re.Match[str]) -> str:+ raw = m.group("quoted") or m.group("plain") or ""+ if not raw:+ return m.group(0)++ # Resolve path+ if raw.startswith("~/"):+ home = os.path.expanduser("~")+ resolved = os.path.join(home, raw[2:])+ elif MessageHandler._is_absolute_reference_path(raw):+ resolved = raw+ else:+ resolved = os.path.join(working_dir, raw)++ try:+ path = Path(resolved)+ if not path.is_file():+ return m.group(0)+ size = path.stat().st_size+ truncated = False+ if max_file_size is None:+ text = path.read_text(encoding="utf-8", errors="replace")+ else:+ with path.open("r", encoding="utf-8", errors="replace") as handle:+ text = handle.read(max_file_size + 1)+ if size > max_file_size or len(text) > max_file_size:+ truncated = True+ if len(text) > max_file_size:+ text = text[:max_file_size]+ if truncated:+ suffix = f"\n... (truncated, original_size={size} bytes)"+ text = f"{text}{suffix}"+ return (+ f'\n<file-content path="{raw}">\n{text}\n</file-content>\n'+ )+ except (OSError, UnicodeDecodeError):+ return m.group(0)++ return pattern.sub(_replacer, content)++ @staticmethod+ def _is_absolute_reference_path(raw: str) -> bool:+ return raw.startswith("/") or (len(raw) >= 3 and raw[1] == ":" and raw[2] == "\\")++ @staticmethod+ def _resolve_reference_path(raw: str, cwd: str | None = None) -> str:+ working_dir = cwd or os.getcwd()+ if raw.startswith("~/"):+ return os.path.join(os.path.expanduser("~"), raw[2:])+ if MessageHandler._is_absolute_reference_path(raw):+ return raw+ return os.path.join(working_dir, raw)++ @classmethod+ def _normalize_structured_attachments(+ cls,+ attachments: Any,+ cwd: str | None = None,+ ) -> list[dict[str, Any]]:+ if not isinstance(attachments, list):+ return []++ normalized: list[dict[str, Any]] = []+ seen: set[str] = set()+ for item in attachments:+ if not isinstance(item, dict):+ continue+ raw_path = str(item.get("path") or "").strip()+ if not raw_path:+ continue+ resolved_path = cls._resolve_reference_path(raw_path, cwd)+ if resolved_path in seen:+ continue+ seen.add(resolved_path)+ normalized.append(+ {+ "path": resolved_path,+ "type": str(item.get("type") or "file").strip() or "file",+ "filename": str(item.get("filename") or Path(resolved_path).name).strip(),+ }+ )+ return normalized++ @classmethod+ def _strip_attached_mentions(+ cls,+ content: str,+ attachments: list[dict[str, Any]],+ cwd: str | None = None,+ ) -> str:+ if not content or not attachments:+ return content++ attached_paths = {+ cls._resolve_reference_path(str(item.get("path") or ""), cwd)+ for item in attachments+ if str(item.get("path") or "").strip()+ }+ if not attached_paths:+ return content++ pattern = re.compile(+ r'(?P<prefix>(?:^|(?<=\s)))@(?:"(?P<quoted>[^"]+)"|(?P<plain>[^\s#]+))(?:#[^#\s]*)?'+ )++ def _replacer(match: re.Match[str]) -> str:+ raw = match.group("quoted") or match.group("plain") or ""+ if not raw:+ return match.group(0)+ resolved = cls._resolve_reference_path(raw, cwd)+ if resolved not in attached_paths:+ return match.group(0)+ return f"{match.group('prefix')}{raw}"++ return pattern.sub(_replacer, content)++ @classmethod+ def _resolve_structured_attachments(+ cls,+ content: str,+ attachments: Any,+ cwd: str | None = None,+ ) -> str:+ normalized = cls._normalize_structured_attachments(attachments, cwd)+ if not normalized:+ return content++ prefix = " ".join(f'@"{item["path"]}"' for item in normalized)+ cleaned_content = cls._strip_attached_mentions(content, normalized, cwd)+ merged_content = f"{prefix} {cleaned_content}".strip()+ return cls._resolve_at_file_references(merged_content, cwd=cwd)+@staticmethoddef message_to_e2a(msg: "Message") -> "E2AEnvelope":from jiuwenclaw.e2a.gateway_normalize import message_to_e2a_or_fallback@@ -1221,12 +1384,20 @@ class MessageHandler(ABC):def _is_evolution_approval_request_id(request_id: Any) -> bool:return isinstance(request_id, str) and request_id.startswith("skill_evolve_approve_")- def _queue_supplement_input(self, session_id: str | None, new_input: str) -> None:+ def _queue_supplement_input(+ self,+ session_id: str | None,+ new_input: str,+ attachments: list[dict[str, Any]] | None = None,+ ) -> None:if not session_id:return- self._queued_supplement_input[session_id] = new_input+ payload: dict[str, Any] = {"new_input": new_input}+ if attachments:+ payload["attachments"] = attachments+ self._queued_supplement_input[session_id] = payload- def _pop_queued_supplement_input(self, session_id: str | None) -> str | None:+ def _pop_queued_supplement_input(self, session_id: str | None) -> dict[str, Any] | None:if not session_id:return Nonereturn self._queued_supplement_input.pop(session_id, None)@@ -1261,20 +1432,27 @@ class MessageHandler(ABC):self._pop_queued_supplement_input(session_id)@staticmethod- def _build_queued_chat_send_message(msg: "Message", new_input: str) -> "Message":+ def _build_queued_chat_send_message(+ msg: "Message",+ new_input: str,+ attachments: list[dict[str, Any]] | None = None,+ ) -> "Message":from jiuwenclaw.schema.message import Message, ReqMethodnew_req_id = f"req_{int(time.time() * 1000):x}_{msg.id}"+ params: dict[str, Any] = {+ "query": new_input,+ "session_id": msg.session_id,+ "is_supplement": True,+ }+ if attachments:+ params["attachments"] = attachmentsreturn Message(id=new_req_id,type="req",channel_id=msg.channel_id,session_id=msg.session_id,- params={- "query": new_input,- "session_id": msg.session_id,- "is_supplement": True,- },+ params=params,timestamp=time.time(),ok=True,req_method=ReqMethod.CHAT_SEND,@@ -1342,9 +1520,15 @@ class MessageHandler(ABC):if self._is_evolution_approval_request_id(answer_request_id):self._clear_pending_evolution_approval(msg.session_id)self._clear_session_evolution_in_progress(msg.session_id)- queued_input = self._pop_queued_supplement_input(msg.session_id)- if isinstance(queued_input, str) and queued_input.strip():- queued_msg = self._build_queued_chat_send_message(msg, queued_input.strip())+ queued_payload = self._pop_queued_supplement_input(msg.session_id)+ queued_input = str((queued_payload or {}).get("new_input") or "").strip()+ queued_attachments = (queued_payload or {}).get("attachments")+ if queued_input:+ queued_msg = self._build_queued_chat_send_message(+ msg,+ queued_input,+ queued_attachments if isinstance(queued_attachments, list) else None,+ )self._user_messages.put_nowait(queued_msg)logger.info("[MessageHandler] evolution approval answered, queued supplement dispatched: id=%s session_id=%s",@@ -1360,6 +1544,10 @@ class MessageHandler(ABC):)new_input = (msg.params or {}).get("new_input")has_new_input = isinstance(new_input, str) and new_input.strip()+ raw_attachments = (msg.params or {}).get("attachments")+ supplement_attachments = (+ raw_attachments if isinstance(raw_attachments, list) else None+ )intent = (msg.params or {}).get("intent", "cancel")if has_new_input:@@ -1371,7 +1559,11 @@ class MessageHandler(ABC):)):queued_input = new_input.strip()- self._queue_supplement_input(msg.session_id, queued_input)+ self._queue_supplement_input(+ msg.session_id,+ queued_input,+ supplement_attachments,+ )logger.info("[MessageHandler] evolution phase pending, queue supplement input: session_id=%s",msg.session_id,@@ -1444,6 +1636,11 @@ class MessageHandler(ABC):"query": new_input.strip(),"session_id": msg.session_id,"is_supplement": True,+ **(+ {"attachments": supplement_attachments}+ if supplement_attachments+ else {}+ ),},timestamp=time.time(),ok=True,@@ -1486,6 +1683,32 @@ class MessageHandler(ABC):if not should_forward:continue # 不相关消息,跳过+ # ---- Resolve @file references in chat.send content ----+ if msg.req_method == ReqMethod.CHAT_SEND and msg.params:+ content = msg.params.get("query") or msg.params.get("content") or ""+ attachments = msg.params.get("attachments")+ cwd = None+ if isinstance(msg.metadata, dict):+ cwd = msg.metadata.get("cwd")+ enriched = content+ if attachments:+ enriched = self._resolve_structured_attachments(+ content,+ attachments,+ cwd=cwd,+ )+ elif content and "@" in content:+ enriched = self._resolve_at_file_references(content, cwd=cwd)+ if enriched != content:+ msg.params = dict(msg.params)+ msg.params["query"] = enriched+ if "content" in msg.params:+ msg.params["content"] = enriched+ logger.info(+ "[MessageHandler] attachments resolved in chat.send: id=%s",+ msg.id,+ )+logger.info("[MessageHandler] 从 user_messages 取出,发往 AgentServer: id=%s channel_id=%s is_stream=%s",msg.id, msg.channel_id, msg.is_stream,diff --git a/tests/unit_tests/gateway/test_cli_channel_handlers.py b/tests/unit_tests/gateway/test_cli_channel_handlers.pyindex 51f33c22e0..dd0e00552a 100644--- a/tests/unit_tests/gateway/test_cli_channel_handlers.py+++ b/tests/unit_tests/gateway/test_cli_channel_handlers.py@@ -48,6 +48,7 @@ async def test_register_cli_handlers_registers_local_methods():cli_handlers = server.local_handlers["/tui"]assert "config.get" in cli_handlers+ assert "config.validate_model" in cli_handlersassert "session.list" in cli_handlersassert "chat.send" in cli_handlersassert "chat.resume" in cli_handlers@@ -80,5 +81,57 @@ def test_build_cli_route_binding_creates_route_and_install_hook():cli_handlers = server.local_handlers["/tui"]assert "config.get" in cli_handlers+ assert "config.validate_model" in cli_handlersassert "session.list" in cli_handlersassert "chat.send" in cli_handlers+++async def test_config_validate_model_handler_uses_local_probe(monkeypatch):+ server = FakeGatewayServer()++ register_cli_handlers(+ CliHandlersBindParams(+ channel=server,+ agent_client=None,+ message_handler=None,+ on_config_saved=None,+ path="/tui",+ )+ )++ cli_handlers = server.local_handlers["/tui"]++ class FakeModel:+ def __init__(self, *args, **kwargs):+ self.args = args+ self.kwargs = kwargs++ async def invoke(self, *args, **kwargs):+ return {"content": "hello"}++ monkeypatch.setattr("jiuwenclaw.channel.cli_channel.Model", FakeModel)++ await cli_handlers["config.validate_model"](+ object(),+ "req-validate",+ {+ "model_provider": "openai",+ "model": "gpt-4.1",+ "api_base": "https://api.openai.com/v1",+ "api_key": "secret",+ },+ "sess-1",+ )++ assert server.responses[-1] == {+ "id": "req-validate",+ "ok": True,+ "payload": {+ "provider": "OpenAI",+ "model": "gpt-4.1",+ "response": "hello",+ },+ "error": None,+ "code": None,+ }