diff --git a/packages/codingcode/package.json b/packages/codingcode/package.json index bdd29203..a0f17544 100644 --- a/packages/codingcode/package.json +++ b/packages/codingcode/package.json @@ -10,7 +10,6 @@ ".": "./src/layer.ts", "./server": "./src/server/index.ts", "./approval/types": "./src/approval/types.ts", - "./agent/profile": "./src/agent/profile.ts", "./sink/types": "./src/sink/types.ts", "./llm/types": "./src/llm/types.ts", "./todo/types": "./src/todo/types.ts", diff --git a/packages/codingcode/src/agent/agent.ts b/packages/codingcode/src/agent/agent.ts index 4b765773..86eb8193 100644 --- a/packages/codingcode/src/agent/agent.ts +++ b/packages/codingcode/src/agent/agent.ts @@ -3,7 +3,7 @@ import { AgentError } from '../util/error.js'; import { Result } from '../util/result.js'; import { AgentService, ToolEnvPort } from './port.js'; import type { RunTurnOptions } from './port.js'; -import { ApprovalService, getToolNames } from '../approval/port.js'; +import { ApprovalService } from '../approval/port.js'; import { CheckpointService } from '../checkpoint/port.js'; import { ContextService } from '../context/port.js'; import { EventSinkService } from '../sink/port.js'; @@ -17,12 +17,13 @@ import { RulesService } from '../rules/port.js'; import { SessionService } from '../session/port.js'; import { SkillService } from '../skills/port.js'; import { ToolExecutorService } from '../tools/port.js'; -import { buildSystemPrompt, renderSkillBlock } from './prompt.js'; +import { BUILD_PROMPT, buildSystemPrompt, renderSkillBlock } from './prompt.js'; import type { FrameBody, FrameError, ResponseMeta, ToolOutcome } from '../sink/types.js'; import { isTurnEnd } from '../sink/types.js'; import type { SessionRef } from '../session/types.js'; import type { TodoItem } from '../todo/types.js'; import type { PermissionMode } from '../util/enums.js'; +import type { SandboxMode, SandboxPolicy } from '../sandbox/types.js'; import type { ToolCatalog, ToolResult } from '../tools/types.js'; import { mediaKindOf, textOf, textPart, type IncomingPart } from '../llm/types.js'; import type { ToolCall } from '../llm/types.js'; @@ -31,8 +32,6 @@ import { sniffMediaMime } from '../util/media.js'; import { loadConfig } from '../infra/config.js'; import { createLogger } from '../infra/logger.js'; import { normalizePath } from '../util/path.js'; -import { resolveProfile } from './profile.js'; -import type { AgentProfile } from './profile.js'; function toolOutcomeOf(result: ToolResult): ToolOutcome { return result.status === 'denied' @@ -135,11 +134,11 @@ export const AgentLayer = Layer.effect( let parentSessionId = opts.parentSessionId; const model = opts.model; if (!sessionId) { - if (!opts.activeProfile || !opts.permissionMode) { + if (!opts.permissionMode) { return yield* Effect.fail( new AgentError( 'CONFIG_MISSING', - 'new session requires activeProfile and permissionMode' + 'new session requires permissionMode' ) ); } @@ -148,7 +147,6 @@ export const AgentLayer = Layer.effect( { model, title: textOf(input) || 'New session', - activeProfile: opts.activeProfile, permissionMode: opts.permissionMode, }, { @@ -185,7 +183,6 @@ export const AgentLayer = Layer.effect( } return yield* Effect.gen(function* () { - const profileName = opts.activeProfile ?? state.activeProfile; const effectivePerm = opts.permissionMode ?? state.permissionMode; if (opts.permissionMode) { yield* session.setPermissionMode( @@ -196,24 +193,10 @@ export const AgentLayer = Layer.effect( opts.parentChain ); } - if (opts.activeProfile) { - yield* session.setActiveProfile( - normalizedCwd, - sid, - opts.activeProfile, - parentSessionId, - opts.parentChain - ); - } - state.memorySnapshot = yield* memory.loadMemoryForPrompt(state.cwd); - const profile: AgentProfile | undefined = profileName - ? resolveProfile(profileName) - : undefined; - const mcpTools = yield* mcp.listProjectMcpTools(normalizedCwd); - const catalog = yield* executor.prepare(getToolNames(profileName), mcpTools); + const catalog = yield* executor.prepare(mcpTools); const toolEnv = yield* toolEnvPort.getToolEnv(); @@ -247,13 +230,14 @@ export const AgentLayer = Layer.effect( { state, model, - profile, catalog, rulesText, abortSignal: opts.signal, sid, projectPath: state.cwd, permissionMode: effectivePerm, + sandboxMode: opts.sandboxMode, + sandboxPolicy: opts.sandboxPolicy, parentChain: opts.parentChain ?? [], systemPrompt: opts.systemPrompt, }, @@ -307,13 +291,14 @@ export const AgentLayer = Layer.effect( opts: { state: any; model: string; - profile: AgentProfile | undefined; abortSignal: AbortSignal | undefined; catalog: ToolCatalog; rulesText: string; sid: string; projectPath: string; permissionMode: PermissionMode; + sandboxMode?: SandboxMode; + sandboxPolicy?: SandboxPolicy; parentChain: readonly string[]; systemPrompt?: string; }, @@ -322,7 +307,6 @@ export const AgentLayer = Layer.effect( const { state, model, - profile, abortSignal, catalog, rulesText, @@ -339,7 +323,7 @@ export const AgentLayer = Layer.effect( platform: process.platform, shell: process.env.SHELL || process.env.ComSpec || 'bash', rules: rulesText, - profileSystemPrompt: opts.systemPrompt ?? profile?.systemPrompt, + customSystemPrompt: opts.systemPrompt ?? BUILD_PROMPT, }); const memoryBlock = state.memorySnapshot; @@ -570,51 +554,84 @@ export const AgentLayer = Layer.effect( ); yield* context.absorb(sessionRef, [assistantToolEv]); - const approvedCalls: any[] = []; - const deniedResults: any[] = []; - for (const tc of toolCalls) { - const decision = yield* approval.evaluate({ - tool: tc.name, - input: tc.arguments ?? {}, - callId: tc.id, + const preparedBatch = yield* executor.prepareBatch( + toolCalls, + state.sessionId, + { + turnId: state.currentTurnId, + projectPath, + signal: abortSignal, + permissionMode, + sandboxMode: opts.sandboxMode, + parentPolicy: opts.sandboxPolicy, + model, + parentChain, + agentName: state.agentName, + }, + toolLookup + ); + const escalationDecisions = yield* approval.evaluateEscalationBatch( + preparedBatch.escalations.map(({ request }) => request) + ); + const escalatedCalls = preparedBatch.escalations + .filter((_, index) => escalationDecisions[index]?.type === 'allow') + .map(({ prepared }) => prepared); + const decisions = yield* approval.evaluateBatch( + preparedBatch.prepared.map((prepared) => ({ + tool: prepared.call.name, + input: prepared.parsedArgs as Record, + prepared, + callId: prepared.call.id, sessionId: state.sessionId, projectPath, permissionMode, - profile: profile?.name, - }); - if (decision.type === 'deny') { - deniedResults.push({ - status: 'denied', - id: tc.id, - name: tc.name, - reason: decision.reason, - }); - } else { - approvedCalls.push(tc); - } + })) + ); + const approvedCalls = [ + ...preparedBatch.prepared.filter((_, index) => decisions[index]?.type === 'allow'), + ...escalatedCalls, + ]; + const deniedResults: ToolResult[] = [ + ...preparedBatch.denied, + ...preparedBatch.prepared.flatMap((prepared, index) => { + const decision = decisions[index]; + return decision?.type === 'deny' + ? [{ status: 'denied' as const, id: prepared.call.id, name: prepared.call.name, reason: decision.reason }] + : []; + }), + ...preparedBatch.escalations.flatMap(({ prepared }, index) => { + const decision = escalationDecisions[index]; + return decision?.type === 'deny' + ? [{ + status: 'denied' as const, + id: prepared.call.id, + name: prepared.call.name, + reason: decision.reason, + }] + : []; + }), + ]; + + if ( + approvedCalls.length > 0 && + !state.parentSessionId + ) { + yield* checkpoint.ensureBaseline(state.cwd, sid, state.currentTurnId); } const approvedResults = approvedCalls.length > 0 - ? yield* executor.executeBatch( - approvedCalls, - state.sessionId, - { - turnId: state.currentTurnId, - projectPath, - signal: abortSignal, - activeProfile: profile?.name, - model, - parentChain, - agentName: state.agentName, - onBeforeMutation: checkpoint.snapshotBeforeWrite( - state.cwd, - sid, - state.currentTurnId - ), - }, - toolLookup - ) + ? yield* executor.executeBatch(approvedCalls, state.sessionId, { + turnId: state.currentTurnId, + projectPath, + signal: abortSignal, + permissionMode, + sandboxMode: opts.sandboxMode, + parentPolicy: opts.sandboxPolicy, + model, + parentChain, + agentName: state.agentName, + }) : []; const resultsById = new Map(); diff --git a/packages/codingcode/src/agent/port.ts b/packages/codingcode/src/agent/port.ts index 2f373ae9..069a05dc 100644 --- a/packages/codingcode/src/agent/port.ts +++ b/packages/codingcode/src/agent/port.ts @@ -1,7 +1,9 @@ import { Context } from 'effect'; import type { Effect } from 'effect'; import type { FrameBody } from '../sink/types.js'; -import type { ProfileName, PermissionMode } from '../util/enums.js'; +import type { PermissionMode } from '../util/enums.js'; +import type { SandboxMode } from '../sandbox/types.js'; +import type { SandboxPolicy } from '../sandbox/types.js'; import type { IncomingPart } from '../llm/types.js'; import type { AgentError } from '../util/error.js'; @@ -11,8 +13,9 @@ export interface RunTurnOptions { cwd: string; signal?: AbortSignal; permissionMode?: PermissionMode; + sandboxMode?: SandboxMode; + sandboxPolicy?: SandboxPolicy; model: string; - activeProfile?: ProfileName; parentSessionId?: string; agentName?: string; /** 子智能体用途描述;仅新建会话时写入 meta */ diff --git a/packages/codingcode/src/agent/profile.ts b/packages/codingcode/src/agent/profile.ts deleted file mode 100644 index 88cdd3ae..00000000 --- a/packages/codingcode/src/agent/profile.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { PLAN_PROFILE_NAME, BUILD_PROFILE_NAME, type ProfileName } from '../util/enums.js'; - -export interface AgentProfile { - name: ProfileName; - systemPrompt?: string; -} - -export const BUILD_PROMPT = `You are a coding assistant —an AI agent that helps users with software engineering tasks. - -## How you work -- Your text output is displayed to the user as formatted text. Tool calls and their results are shown separately —the user can see what tools you used and their outcomes. -- Tools run behind a permission system. If a tool call is denied, the user declined it —adjust your approach, do not retry the same call verbatim. -- Messages may contain tags injected by the system, not by the user. They contain useful operational information —always read and follow them. - -## Rules -1. Read files before modifying them —never guess file contents -2. Use search_code or search_files to locate code before reading —this is faster than reading entire files blindly -3. Prefer editing existing files over creating new ones -4. Make small, focused changes —avoid large rewrites -5. Run tests or type-check after changes when applicable -6. If the user's request is ambiguous, ask for clarification -7. For complex or broad tasks (understanding a whole module, cross-file analysis, comprehensive search): - a. Briefly assess the task scope using your own reasoning —do not use tools for exploration at this stage, as that would consume your limited context window. - b. If you can clearly handle it without extensive file reading or searching, proceed yourself. - c. Otherwise spawn_agent: give the subagent a short agentName, a self-contained prompt, and a write set that does not overlap yours. Then keep working on your own part; call wait_agent only when its result blocks your next step, and give the wait a generous timeout instead of polling. - -## Using your tools -- **Prefer dedicated tools over shell commands.** Use read_file instead of cat, edit_file instead of sed, search_code instead of grep. Dedicated tools give the user better visibility into your work. -- **Call multiple tools in parallel** when they are independent —for example, reading several files at once, or searching with different patterns. Do NOT make sequential calls when the calls don't depend on each other. -- After editing a file, do NOT re-read it to verify —the edit tool already confirms success or reports failure. Only re-read if you suspect the edit did not apply correctly. -- Reserve execute_command for actual system commands and terminal operations (git, npm, build, test). Do not use it for file operations that dedicated tools can handle. - -## Executing actions with care -Consider the reversibility and blast radius of actions before taking them: -- **Freely take** local, reversible actions: editing files, running tests, reading code. -- **Confirm with the user before** hard-to-reverse or outward-facing actions: pushing code, deleting files/branches, force-pushing, modifying CI/CD pipelines, sending messages to external services. -- **Never** use destructive commands (rm -rf /, sudo, git reset --hard, git push --force, git clean -f) unless explicitly requested and approved by the user. -- When you encounter unexpected state (unfamiliar files, branches, or configuration), investigate before deleting or overwriting —it may be the user's in-progress work. Never revert changes you did not make. - -## Git operations -- Do NOT commit changes unless the user explicitly asks you to. -- Do NOT push to remote unless the user explicitly asks you to. -- Do NOT use destructive git commands (git reset --hard, git push --force, git clean -f, git checkout -- .) unless explicitly requested and approved. -- If you notice unexpected changes in the working tree that you did not make, investigate before acting —they may be the user's in-progress work. - -## Professional objectivity -Prioritize technical accuracy over validating the user's beliefs. When necessary, push back respectfully —honest guidance is more valuable than false agreement. -- Do not begin responses with conversational interjections ("Got it", "Sure", "Great question") -- Do not apologize unnecessarily when results are unexpected - -## Follow existing conventions -When modifying code, first look at the surrounding code's style (naming, frameworks, imports) and match it: -- **Never assume a library is available** —check imports in neighboring files, or check the dependency file (package.json, cargo.toml, requirements.txt, etc.) before using it. -- **When creating a new component**, first look at existing components to understand naming conventions, typing patterns, and framework choices. -- **When editing code**, look at the surrounding context (especially imports) to understand the code's choice of frameworks and libraries, then make your change in the most idiomatic way. -- **Comments**: default to writing no comments. Only add one when the WHY is non-obvious —a hidden constraint, a subtle invariant, or a workaround for a specific bug. Do not explain WHAT the code does. - -## Code references -When referencing code, use the format \`file_path:line_number\` for easy navigation. - -## Output efficiency -- Be concise. Lead with the answer or action, not with reasoning or preamble. -- Skip filler words and unnecessary transitions. Do not restate what the user said —just do it. -- When working on a multi-step task, give brief updates at key moments (when you find something, change direction, or hit a blocker). One sentence per update is enough. -- When the task is done, give a one-to-two sentence summary of what changed. Do not narrate your entire process. -- Match the response to the question: a simple question gets a direct answer, not headers and sections. - - -Respond in the user's language. Use code blocks for code.`; - -export const PLAN_PROMPT = `You are a planning agent. Your role is to analyze the codebase and produce an implementation plan that the user reviews and approves before any code is written. - -You can read files and search code. You can submit a plan via the \`submit_plan\` tool — each call overwrites the previous plan file; use it to revise your plan based on user feedback. - -In plan profile, write_file / edit_file / execute_command are denied. The only write operation allowed is \`submit_plan\`. - -## Research process -1. Understand the project structure and conventions -2. Identify relevant files and existing patterns -3. Analyze dependencies and potential impacts -4. Assess complexity and risks -5. Check for existing implementations or similar patterns - -## Output format -When ready, call \`submit_plan({ title, plan_content: "..." })\` with a Markdown plan: -- **Current state**: What exists today -- **Key files**: Files that need modification or creation, with line references -- **Dependencies and risks**: Breaking changes, third-party concerns -- **Recommended approach**: Step-by-step implementation strategy -- **Phases**: If complex, break into ordered phases - -## After submit_plan -submit_plan returns synchronously after writing the plan file. Once you have called it, stop and wait for the user's decision — do not call submit_plan again until the user responds, and do not attempt to use any other write tool. - -The user's decision arrives as the next user message. The system has already handled the agent-profile switch (plan → build on approval, plan → plan on revise, no change on cancel); the message body itself is your signal: - -- "Implement"/"proceed"/"go ahead" (or any explicit approval) — the plan is approved. Acknowledge briefly and stop. The build agent will pick up the plan from the persisted file. -- The body contains a revised plan (a Markdown document, often with explicit section headers, or with a "Revise the plan with these changes:" wrapper) — treat the body as the new plan_content, call \`submit_plan\` again with the same title and the revised content, then stop. -- "Cancel"/"do not implement" — the plan is rejected. Acknowledge briefly and stop. - -Never re-call submit_plan on your own initiative. Never treat an implement message as a request for further exploration.`; - -export const PLAN_PROFILE: AgentProfile = { - name: PLAN_PROFILE_NAME, - systemPrompt: PLAN_PROMPT, -}; - -export const BUILD_PROFILE: AgentProfile = { - name: BUILD_PROFILE_NAME, - systemPrompt: BUILD_PROMPT, -}; - -export function isAgentProfileName(name: string): name is ProfileName { - return name === PLAN_PROFILE_NAME || name === BUILD_PROFILE_NAME; -} - -export function resolveProfile(name: ProfileName): AgentProfile { - return name === PLAN_PROFILE_NAME ? PLAN_PROFILE : BUILD_PROFILE; -} diff --git a/packages/codingcode/src/agent/prompt.ts b/packages/codingcode/src/agent/prompt.ts index e8a9c2ef..31f986f9 100644 --- a/packages/codingcode/src/agent/prompt.ts +++ b/packages/codingcode/src/agent/prompt.ts @@ -1,4 +1,65 @@ -import { BUILD_PROMPT } from './profile.js'; +export const BUILD_PROMPT = `You are a coding assistant —an AI agent that helps users with software engineering tasks. + +## How you work +- Your text output is displayed to the user as formatted text. Tool calls and their results are shown separately —the user can see what tools you used and their outcomes. +- Tools run behind a permission system. If a tool call is denied, the user declined it —adjust your approach, do not retry the same call verbatim. +- Messages may contain tags injected by the system, not by the user. They contain useful operational information —always read and follow them. + +## Rules +1. Read files before modifying them —never guess file contents +2. Use search_code or search_files to locate code before reading —this is faster than reading entire files blindly +3. Prefer editing existing files over creating new ones +4. Make small, focused changes —avoid large rewrites +5. Run tests or type-check after changes when applicable +6. If the user's request is ambiguous, ask for clarification +7. For complex or broad tasks (understanding a whole module, cross-file analysis, comprehensive search): + a. Briefly assess the task scope using your own reasoning —do not use tools for exploration at this stage, as that would consume your limited context window. + b. If you can clearly handle it without extensive file reading or searching, proceed yourself. + c. Otherwise spawn_agent: give the subagent a short agentName, a self-contained prompt, and a write set that does not overlap yours. Then keep working on your own part; call wait_agent only when its result blocks your next step, and give the wait a generous timeout instead of polling. + +## Using your tools +- **Prefer dedicated tools over shell commands.** Use read_file instead of cat, edit_file instead of sed, search_code instead of grep. Dedicated tools give the user better visibility into your work. +- **Call multiple tools in parallel** when they are independent —for example, reading several files at once, or searching with different patterns. Do NOT make sequential calls when the calls don't depend on each other. +- After editing a file, do NOT re-read it to verify —the edit tool already confirms success or reports failure. Only re-read if you suspect the edit did not apply correctly. +- Reserve execute_command for actual system commands and terminal operations (git, npm, build, test). Do not use it for file operations that dedicated tools can handle. + +## Executing actions with care +Consider the reversibility and blast radius of actions before taking them: +- **Freely take** local, reversible actions: editing files, running tests, reading code. +- **Confirm with the user before** hard-to-reverse or outward-facing actions: pushing code, deleting files/branches, force-pushing, modifying CI/CD pipelines, sending messages to external services. +- **Never** use destructive commands (rm -rf /, sudo, git reset --hard, git push --force, git clean -f) unless explicitly requested and approved by the user. +- When you encounter unexpected state (unfamiliar files, branches, or configuration), investigate before deleting or overwriting —it may be the user's in-progress work. Never revert changes you did not make. + +## Git operations +- Do NOT commit changes unless the user explicitly asks you to. +- Do NOT push to remote unless the user explicitly asks you to. +- Do NOT use destructive git commands (git reset --hard, git push --force, git clean -f, git checkout -- .) unless explicitly requested and approved. +- If you notice unexpected changes in the working tree that you did not make, investigate before acting —they may be the user's in-progress work. + +## Professional objectivity +Prioritize technical accuracy over validating the user's beliefs. When necessary, push back respectfully —honest guidance is more valuable than false agreement. +- Do not begin responses with conversational interjections ("Got it", "Sure", "Great question") +- Do not apologize unnecessarily when results are unexpected + +## Follow existing conventions +When modifying code, first look at the surrounding code's style (naming, frameworks, imports) and match it: +- **Never assume a library is available** —check imports in neighboring files, or check the dependency file (package.json, cargo.toml, requirements.txt, etc.) before using it. +- **When creating a new component**, first look at existing components to understand naming conventions, typing patterns, and framework choices. +- **When editing code**, look at the surrounding context (especially imports) to understand the code's choice of frameworks and libraries, then make your change in the most idiomatic way. +- **Comments**: default to writing no comments. Only add one when the WHY is non-obvious —a hidden constraint, a subtle invariant, or a workaround for a specific bug. Do not explain WHAT the code does. + +## Code references +When referencing code, use the format \`file_path:line_number\` for easy navigation. + +## Output efficiency +- Be concise. Lead with the answer or action, not with reasoning or preamble. +- Skip filler words and unnecessary transitions. Do not restate what the user said —just do it. +- When working on a multi-step task, give brief updates at key moments (when you find something, change direction, or hit a blocker). One sentence per update is enough. +- When the task is done, give a one-to-two sentence summary of what changed. Do not narrate your entire process. +- Match the response to the question: a simple question gets a direct answer, not headers and sections. + + +Respond in the user's language. Use code blocks for code.`; import type { Skill } from '../skills/types.js'; import { SUBAGENT_MESSAGE_PREFIX, SUBAGENT_RESULT_PREFIX } from '../session/types.js'; @@ -7,7 +68,7 @@ interface SystemPromptOptions { platform: string; shell: string; rules?: string; - profileSystemPrompt?: string; + customSystemPrompt?: string; } const DEFAULT_ENV_PROMPT = `## Environment @@ -32,7 +93,7 @@ function renderBase(opts: SystemPromptOptions): string { export function buildSystemPrompt(opts: SystemPromptOptions): string { let prompt = renderBase(opts); - prompt += '\n\n' + (opts.profileSystemPrompt ?? BUILD_PROMPT); + prompt += '\n\n' + (opts.customSystemPrompt ?? BUILD_PROMPT); prompt += `\n\n${SYSTEM_NOTES}`; const rules = opts.rules; diff --git a/packages/codingcode/src/approval/approval.ts b/packages/codingcode/src/approval/approval.ts index 6ac8133b..76f75af5 100644 --- a/packages/codingcode/src/approval/approval.ts +++ b/packages/codingcode/src/approval/approval.ts @@ -4,94 +4,60 @@ import type { HookShape } from '../hooks/port.js'; import { ASK_BEFORE_EXEC_PERMISSION_MODE, BYPASS_PERMISSION_MODE, - PLAN_PROFILE_NAME, + UNRESTRICTED_PERMISSION_MODE, type PermissionMode, - type ProfileName, } from '../util/enums.js'; -import type { PermissionRule, ToolCallRequest } from './types.js'; -import { PLAN_ALLOWED_TOOLS } from './tool-policy.js'; -import { createRuleEngine, type RuleEngine } from './rule-engine.js'; +import { createRuleEngine } from './rule-engine.js'; import { userConfirmAsync } from './confirmation.js'; import { ApprovalWaitService } from './wait-port.js'; import { EventSinkService } from '../sink/port.js'; import { ApprovalService } from './port.js'; import type { ApprovalDecision, ApprovalRequest } from './port.js'; - -const DANGEROUS_TOOL_NAMES = ['execute_command']; - -const LAYER_NAMES = [ - 'RuleEngine', - 'PermissionMode', - 'HookPreToolUse', - 'UserConfirmation', - 'AuditLog', -] as const; +import type { ToolApprovalMetadata } from '../tools/types.js'; +import type { ToolCallRequest } from './types.js'; +import type { SandboxEscalationRequest } from '../sandbox/types.js'; + +const LAYER_NAMES = ['RuleEngine', 'PermissionMode', 'HookPreToolUse', 'UserConfirmation', 'AuditLog'] as const; +const HARD_DANGERS = new Set([ + 'workspace_escape', + 'destructive_delete', + 'permission_change', + 'credential_access', + 'remote_code_fetch', + 'repository_history_write', + 'system_configuration', +]); interface PipelineOptions { - ruleEngine: RuleEngine; - destructiveTools: Set; + ruleEngine: ReturnType; permissionMode: PermissionMode; - profile?: ProfileName; - onAlways?: (rule: PermissionRule) => void; - onNever?: (rule: PermissionRule) => void; + operation: ToolApprovalMetadata; sessionId: string; projectPath?: string; callId?: string; } -function applyPermissionMode( - tool: string, - mode: PermissionMode, - profile: ProfileName | undefined, - destructiveTools: Set -): ApprovalDecision | null { - if (profile === PLAN_PROFILE_NAME) { - if (PLAN_ALLOWED_TOOLS.has(tool)) { - return { type: 'allow', source: 'permission-mode' }; - } - return { - type: 'deny', - reason: 'Write operations denied in plan profile. Use submit_plan to submit a plan.', - source: 'permission-mode', - }; - } - - switch (mode) { - case BYPASS_PERMISSION_MODE: - return { type: 'allow', source: 'permission-mode' }; - - case ASK_BEFORE_EXEC_PERMISSION_MODE: - if (!destructiveTools.has(tool)) { - return { type: 'allow', source: 'permission-mode' }; - } - return null; - - default: - return null; - } -} - function recordAuditAndReturn( hooks: HookShape, request: ToolCallRequest, decision: ApprovalDecision, - passedLayers: string[], - projectPath: string | undefined -): Effect.Effect { + layers: string[], + projectPath?: string +) { return Effect.gen(function* () { - passedLayers.push(LAYER_NAMES[4]); + layers.push(LAYER_NAMES[4]); yield* hooks.emit('tool.approval.post', { tool: request.tool, input: request.input, decision, - layers: passedLayers, + layers, projectPath, }); return decision; }); } -export function runPipeline( +function runPipeline( request: ToolCallRequest, opts: PipelineOptions ): Effect.Effect { @@ -99,119 +65,112 @@ export function runPipeline( const hooks = yield* HookService; const layers: string[] = []; - // Layer 1: Rule Engine - { - const result = opts.ruleEngine.evaluate(request.tool, request.input); - if (result) { - layers.push(LAYER_NAMES[0]); - const final = yield* recordAuditAndReturn(hooks, request, result, layers, opts.projectPath); - return final; - } + if (opts.permissionMode === UNRESTRICTED_PERMISSION_MODE) { + layers.push('PermissionMode'); + return yield* recordAuditAndReturn( + hooks, + request, + { type: 'allow', source: 'unrestricted' }, + layers, + opts.projectPath + ); } - // Layer 2: Permission Mode - { - const modeResult = applyPermissionMode( - request.tool, - opts.permissionMode, - opts.profile, - opts.destructiveTools + if ( + (opts.operation.dangerous ?? []).some((operation) => HARD_DANGERS.has(operation)) + ) { + layers.push('DangerousOperation'); + return yield* recordAuditAndReturn( + hooks, + request, + { + type: 'deny', + reason: 'Dangerous operation denied by policy', + source: 'dangerous-operation', + }, + layers, + opts.projectPath ); - if (modeResult) { - layers.push(LAYER_NAMES[1]); - const final = yield* recordAuditAndReturn( - hooks, - request, - modeResult, - layers, - opts.projectPath - ); - return final; - } } - // Layer 3: Hook PreToolUse - { - const hookResult = yield* Effect.gen(function* () { - const result = yield* hooks.emitDecision('tool.approval.pre', { - toolName: request.tool, - args: request.input, - sessionId: opts.sessionId, - projectPath: opts.projectPath, - }); - if (result && result.decision === 'continue') { - return null; - } - return result; - }); - if (hookResult) { - layers.push(LAYER_NAMES[2]); - if (hookResult.decision === 'deny') { - const result: ApprovalDecision = { - type: 'deny', - reason: hookResult.reason ?? 'Denied by PreToolUse hook', - source: 'hook', - }; - const final = yield* recordAuditAndReturn( - hooks, - request, - result, - layers, - opts.projectPath - ); - return final; - } - if (hookResult.decision === 'allow') { - const result: ApprovalDecision = { type: 'allow', source: 'hook' }; - const final = yield* recordAuditAndReturn( - hooks, - request, - result, - layers, - opts.projectPath - ); - return final; - } - const nextRequest: ToolCallRequest = { ...request }; - if (hookResult.modifiedInput) { - nextRequest.input = hookResult.modifiedInput; - } - request = nextRequest; - } + const ruleResult = opts.ruleEngine.evaluate(request.tool, request.input); + if (ruleResult) { + layers.push(LAYER_NAMES[0]); + return yield* recordAuditAndReturn(hooks, request, ruleResult, layers, opts.projectPath); } - // Layer 4: User Confirmation - { - layers.push(LAYER_NAMES[3]); + if ( + opts.permissionMode === BYPASS_PERMISSION_MODE + ) { + layers.push(LAYER_NAMES[1]); + return yield* recordAuditAndReturn( + hooks, + request, + { type: 'allow', source: 'permission-mode' }, + layers, + opts.projectPath + ); + } - const confirmResult = yield* userConfirmAsync( - request.tool, - request.input, - opts.sessionId, - opts.callId ?? '' + const hookResult = yield* hooks.emitDecision('tool.approval.pre', { + toolName: request.tool, + args: request.input, + sessionId: opts.sessionId, + projectPath: opts.projectPath, + }); + if (hookResult?.decision === 'deny') { + layers.push(LAYER_NAMES[2]); + return yield* recordAuditAndReturn( + hooks, + request, + { + type: 'deny', + reason: hookResult.reason ?? 'Denied by PreToolUse hook', + source: 'hook', + }, + layers, + opts.projectPath + ); + } + if (hookResult?.decision === 'allow') { + layers.push(LAYER_NAMES[2]); + return yield* recordAuditAndReturn( + hooks, + request, + { type: 'allow', source: 'hook' }, + layers, + opts.projectPath ); + } - let result: ApprovalDecision; - switch (confirmResult.type) { - case 'allow': - result = { type: 'allow', source: 'user-confirm' }; - break; - case 'deny': - result = { type: 'deny', reason: 'Denied by user', source: 'user-confirm' }; - break; - case 'always': - opts.onAlways?.(confirmResult.rule); - result = { type: 'allow', source: 'user-confirm' }; - break; - case 'never': - opts.onNever?.(confirmResult.rule); - result = { type: 'deny', reason: 'Never allow for this tool', source: 'user-confirm' }; - break; - } - - const final = yield* recordAuditAndReturn(hooks, request, result, layers, opts.projectPath); - return final; + if (!opts.operation.requiresConfirmation) { + layers.push(LAYER_NAMES[1]); + return yield* recordAuditAndReturn( + hooks, + request, + { type: 'allow', source: 'permission-mode' }, + layers, + opts.projectPath + ); } + + layers.push(LAYER_NAMES[3]); + const confirmResult = yield* userConfirmAsync( + request.tool, + request.input, + opts.sessionId, + opts.callId ?? '', + opts.operation.action + ); + return yield* recordAuditAndReturn( + hooks, + request, + confirmResult.type === 'allow' + ? { type: 'allow', source: 'user-confirm' } + : { type: 'deny', reason: 'Denied by user', source: 'user-confirm' }, + layers, + opts.projectPath + ); }); } @@ -221,34 +180,67 @@ export const ApprovalLayer = Layer.effect( const hooks = yield* HookService; const sink = yield* EventSinkService; const approvalWait = yield* ApprovalWaitService; - const ruleEngine: RuleEngine = createRuleEngine(); - const destructiveTools = new Set(DANGEROUS_TOOL_NAMES); - - return { - evaluate: (request: ApprovalRequest): Effect.Effect => - runPipeline( - { - tool: request.tool, - input: request.input, - context: request.context, - callId: request.callId, - }, - { - ruleEngine, - destructiveTools, - permissionMode: request.permissionMode ?? ASK_BEFORE_EXEC_PERMISSION_MODE, - profile: request.profile, - onAlways: (rule) => ruleEngine.addRule(rule), - onNever: (rule) => ruleEngine.addRule(rule), - sessionId: request.sessionId, - projectPath: request.projectPath, - callId: request.callId, - } - ).pipe( - Effect.provideService(HookService, hooks), - Effect.provideService(EventSinkService, sink), - Effect.provideService(ApprovalWaitService, approvalWait) - ), + const ruleEngine = createRuleEngine(); + + const evaluate = (request: ApprovalRequest): Effect.Effect => { + const operation = request.prepared.operation; + return runPipeline( + { + tool: request.tool, + input: request.input, + context: request.context, + callId: request.callId, + }, + { + ruleEngine, + permissionMode: request.permissionMode ?? ASK_BEFORE_EXEC_PERMISSION_MODE, + operation, + sessionId: request.sessionId, + projectPath: request.projectPath, + callId: request.callId, + } + ).pipe( + Effect.provideService(HookService, hooks), + Effect.provideService(EventSinkService, sink), + Effect.provideService(ApprovalWaitService, approvalWait) + ); }; + + const evaluateBatch = (requests: readonly ApprovalRequest[]): Effect.Effect => + Effect.forEach(requests, evaluate, { concurrency: 1 }); + + const evaluateEscalation = ( + request: SandboxEscalationRequest + ): Effect.Effect => + runPipeline( + { + tool: request.toolName, + input: { + currentMode: request.currentMode, + targetMode: request.targetMode, + additionalWritableRoots: request.additionalWritableRoots ?? [], + justification: request.justification, + }, + callId: request.callId, + }, + { + ruleEngine, + permissionMode: ASK_BEFORE_EXEC_PERMISSION_MODE, + operation: { action: 'sandbox', requiresConfirmation: true }, + sessionId: request.sessionId, + callId: request.callId, + } + ).pipe( + Effect.provideService(HookService, hooks), + Effect.provideService(EventSinkService, sink), + Effect.provideService(ApprovalWaitService, approvalWait) + ); + + const evaluateEscalationBatch = ( + requests: readonly SandboxEscalationRequest[] + ): Effect.Effect => + Effect.forEach(requests, evaluateEscalation, { concurrency: 1 }); + + return { evaluate, evaluateBatch, evaluateEscalation, evaluateEscalationBatch }; }) ); diff --git a/packages/codingcode/src/approval/confirmation.ts b/packages/codingcode/src/approval/confirmation.ts index 121b1896..83a99f01 100644 --- a/packages/codingcode/src/approval/confirmation.ts +++ b/packages/codingcode/src/approval/confirmation.ts @@ -1,19 +1,16 @@ import { Effect } from 'effect'; -import type { PermissionRule } from './types.js'; import { ApprovalWaitService } from './wait-port.js'; import { EventSinkService } from '../sink/port.js'; +import type { ApprovalAction } from './types.js'; -export type ConfirmResult = - | { type: 'allow' } - | { type: 'deny' } - | { type: 'always'; rule: PermissionRule } - | { type: 'never'; rule: PermissionRule }; +export type ConfirmResult = { type: 'allow' } | { type: 'deny' }; export function userConfirmAsync( tool: string, args: Record, sessionId: string, - callId: string + callId: string, + action: ApprovalAction ): Effect.Effect { return Effect.gen(function* () { const waitSvc = yield* ApprovalWaitService; @@ -22,7 +19,7 @@ export function userConfirmAsync( yield* sink.emit(sessionId, { family: 'event', - event: { type: 'approval_request', id, tool, args }, + event: { type: 'approval_request', id, tool, action, args }, }); return yield* waitSvc.waitForConfirm(id, sessionId); @@ -35,28 +32,6 @@ export function parseApprovalResponse(response: string): ConfirmResult { return { type: 'allow' }; case 'deny': return { type: 'deny' }; - case 'always': - return { - type: 'always', - rule: { - id: `user-allow-${Date.now()}`, - action: 'allow', - toolPattern: '*', - reason: 'User always allows', - source: 'user', - }, - }; - case 'never': - return { - type: 'never', - rule: { - id: `user-deny-${Date.now()}`, - action: 'deny', - toolPattern: '*', - reason: 'User never allows', - source: 'user', - }, - }; default: return { type: 'deny' }; } diff --git a/packages/codingcode/src/approval/port.ts b/packages/codingcode/src/approval/port.ts index 0fd2620f..8fcb9fc6 100644 --- a/packages/codingcode/src/approval/port.ts +++ b/packages/codingcode/src/approval/port.ts @@ -1,9 +1,9 @@ import { Context } from 'effect'; import type { Effect } from 'effect'; -import type { ProfileName, PermissionMode } from '../util/enums.js'; +import type { PermissionMode } from '../util/enums.js'; import type { ToolCallRequest } from './types.js'; - -export * from './tool-policy.js'; +import type { PreparedToolCall } from '../tools/types.js'; +import type { SandboxEscalationRequest } from '../sandbox/types.js'; export type ApprovalDecision = | { type: 'deny'; reason: string; source: string } @@ -11,14 +11,19 @@ export type ApprovalDecision = /** 审批请求:工具调用 + 审批上下文。 */ export interface ApprovalRequest extends ToolCallRequest { + prepared: PreparedToolCall; sessionId: string; projectPath?: string; permissionMode?: PermissionMode; - profile?: ProfileName; } export interface ApprovalShape { evaluate(request: ApprovalRequest): Effect.Effect; + evaluateBatch(requests: readonly ApprovalRequest[]): Effect.Effect; + evaluateEscalation(request: SandboxEscalationRequest): Effect.Effect; + evaluateEscalationBatch( + requests: readonly SandboxEscalationRequest[] + ): Effect.Effect; } export class ApprovalService extends Context.Tag('Approval')() {} diff --git a/packages/codingcode/src/approval/tool-policy.ts b/packages/codingcode/src/approval/tool-policy.ts deleted file mode 100644 index b0d2dc26..00000000 --- a/packages/codingcode/src/approval/tool-policy.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { isPlanProfile, type ProfileName } from '../util/enums.js'; - -export const PLAN_TOOL_NAMES: readonly string[] = [ - 'read_file', - 'search_files', - 'search_code', - 'todo_write', - 'todo_read', - 'ask_user', - 'fetch_url', - 'submit_plan', -]; - -export const BUILD_TOOL_NAMES: readonly string[] = [ - 'read_file', - 'write_file', - 'edit_file', - 'execute_command', - 'search_code', - 'search_files', - 'fetch_url', - 'web_search', - 'todo_write', - 'todo_read', - 'ask_user', - 'spawn_agent', - 'wait_agent', - 'resume_agent', - 'send_message', - 'interrupt_agent', - 'list_agents', -]; - -export const PLAN_ALLOWED_TOOLS: ReadonlySet = new Set(PLAN_TOOL_NAMES); - -export function getToolNames(name: ProfileName | undefined): readonly string[] { - return isPlanProfile(name) ? PLAN_TOOL_NAMES : BUILD_TOOL_NAMES; -} diff --git a/packages/codingcode/src/approval/types.ts b/packages/codingcode/src/approval/types.ts index 9687a3fc..662cfbb0 100644 --- a/packages/codingcode/src/approval/types.ts +++ b/packages/codingcode/src/approval/types.ts @@ -14,6 +14,8 @@ export interface ToolCallRequest { export type RuleAction = 'deny' | 'allow' | 'ask'; +export type ApprovalAction = 'file' | 'exec' | 'network' | 'mcp' | 'subagent' | 'sandbox' | 'other'; + export interface PermissionRule { id: string; action: RuleAction; diff --git a/packages/codingcode/src/checkpoint/checkpoint.ts b/packages/codingcode/src/checkpoint/checkpoint.ts index 77255569..941e004d 100644 --- a/packages/codingcode/src/checkpoint/checkpoint.ts +++ b/packages/codingcode/src/checkpoint/checkpoint.ts @@ -14,7 +14,6 @@ import { CheckpointService } from './port.js'; // ---- Effect Service ---- const shadowGitByProject = new ProjectCache(10); -const baselineTurnBySession = new Map(); export const CheckpointLayer = Layer.effect( CheckpointService, @@ -44,16 +43,19 @@ export const CheckpointLayer = Layer.effect( sg.commit(rollbackSnapshotMsg(sessionId, rollbackTurnId)); } + const ensureBaseline = (projectPath: string, sessionId: string, turnId: number) => + Effect.sync(() => { + const sg = ensure(projectPath); + if (sg.findCommitByMessage(commitMsg(sessionId, turnId))) return; + sg.stageAll(); + const hasHead = sg.git('rev-parse', '--verify', 'HEAD').status === 0; + const hasChanges = !hasHead || sg.git('diff', '--cached', '--quiet', 'HEAD').status !== 0; + if (hasChanges && !sg.isTooLargeForSnapshot()) sg.commit(commitMsg(sessionId, turnId)); + }); + return { - snapshotBeforeWrite: (projectPath: string, sessionId: string, turnId: number) => - Effect.sync(() => { - if (baselineTurnBySession.get(sessionId) === turnId) return; - baselineTurnBySession.set(sessionId, turnId); - const sg = ensure(projectPath); - sg.stageAll(); - if (sg.isTooLargeForSnapshot()) return; - sg.commit(commitMsg(sessionId, turnId)); - }), + ensureBaseline, + snapshotBeforeWrite: ensureBaseline, getCheckpointDiff: (projectPath: string, sessionId: string, turnId?: number) => Effect.sync(() => { diff --git a/packages/codingcode/src/checkpoint/port.ts b/packages/codingcode/src/checkpoint/port.ts index 4251ac97..a52c4df4 100644 --- a/packages/codingcode/src/checkpoint/port.ts +++ b/packages/codingcode/src/checkpoint/port.ts @@ -3,6 +3,8 @@ import type { Effect } from 'effect'; import type { CheckpointDiff, CodeRollbackResult, RollbackPreviewDiff } from './types.js'; export interface CheckpointShape { + ensureBaseline(projectPath: string, sessionId: string, turnId: number): Effect.Effect; + /** @deprecated use ensureBaseline */ snapshotBeforeWrite(projectPath: string, sessionId: string, turnId: number): Effect.Effect; getCheckpointDiff( projectPath: string, diff --git a/packages/codingcode/src/infra/config.ts b/packages/codingcode/src/infra/config.ts index 50672cae..00414a25 100644 --- a/packages/codingcode/src/infra/config.ts +++ b/packages/codingcode/src/infra/config.ts @@ -2,7 +2,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs'; import { join, dirname } from 'path'; import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'; import { getGlobalDir } from '../util/path.js'; -import { ASK_BEFORE_EXEC_PERMISSION_MODE, BUILD_PROFILE_NAME } from '../util/enums.js'; +import { ASK_BEFORE_EXEC_PERMISSION_MODE } from '../util/enums.js'; export interface ContextConfig { compactionModel: string; @@ -27,7 +27,6 @@ export interface AppConfig { maxSteps: number; maxStopContinuations: number; activeModel?: ActiveModelConfig; - activeProfile: string; permissionMode: string; context: ContextConfig; memory: MemoryConfig; @@ -51,7 +50,6 @@ export const DEFAULT_SUBAGENT: SubagentConfig = { export const DEFAULT_CONFIG: AppConfig = { maxSteps: 200, maxStopContinuations: 2, - activeProfile: BUILD_PROFILE_NAME, permissionMode: ASK_BEFORE_EXEC_PERMISSION_MODE, context: DEFAULT_CONTEXT, memory: DEFAULT_MEMORY, @@ -94,13 +92,6 @@ export function updateActiveModel(model: string, apiKeyEnv: string, configPath?: writeConfig(p, existing); } -export function updateActiveProfile(activeProfile: string, configPath?: string): void { - const p = configPath ?? getUserConfigPath(); - const existing = readExistingConfig(p); - existing.activeProfile = activeProfile; - writeConfig(p, existing); -} - export function updatePermissionMode(permissionMode: string, configPath?: string): void { const p = configPath ?? getUserConfigPath(); const existing = readExistingConfig(p); diff --git a/packages/codingcode/src/sandbox/file-boundary.ts b/packages/codingcode/src/sandbox/file-boundary.ts new file mode 100644 index 00000000..77c2f13d --- /dev/null +++ b/packages/codingcode/src/sandbox/file-boundary.ts @@ -0,0 +1,51 @@ +import { realpath } from 'node:fs/promises'; +import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'; +import { AgentError } from '../util/error.js'; +import type { SandboxPolicy } from './types.js'; + +function contains(root: string, target: string): boolean { + const rel = relative(root, target); + return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)); +} + +async function canonicalTarget(path: string): Promise { + try { + return await realpath(path); + } catch { + const missing: string[] = []; + let current = path; + while (true) { + try { + const existing = await realpath(current); + return resolve(existing, ...missing.reverse()); + } catch { + const parent = dirname(current); + if (parent === current) + throw new AgentError('SANDBOX_PATH_DENIED', `Path cannot be resolved: ${path}`); + missing.push(current.slice(parent.length + 1)); + current = parent; + } + } + } +} + +export async function resolveFileTarget( + policy: SandboxPolicy, + input: string, + operation: 'read' | 'write' +): Promise { + if (!input || input.includes('\0')) + throw new AgentError('SANDBOX_PATH_DENIED', 'Invalid file path'); + const requested = isAbsolute(input) ? input : resolve(policy.workspaceRoot, input); + if (policy.mode === 'unrestricted' || policy.mode === 'danger-full-access') return requested; + + const target = await canonicalTarget(requested); + const roots = [policy.workspaceRoot, ...policy.additionalWritableRoots]; + if (!roots.some((root) => contains(root, target))) { + throw new AgentError('SANDBOX_PATH_DENIED', `Path is outside the sandbox roots: ${input}`); + } + if (operation === 'write' && policy.mode === 'read-only') { + throw new AgentError('SANDBOX_PATH_DENIED', 'The current sandbox is read-only'); + } + return target; +} diff --git a/packages/codingcode/src/sandbox/network.ts b/packages/codingcode/src/sandbox/network.ts new file mode 100644 index 00000000..3c0f2ecf --- /dev/null +++ b/packages/codingcode/src/sandbox/network.ts @@ -0,0 +1,23 @@ +import { AgentError } from '../util/error.js'; +import type { SandboxPolicy } from './types.js'; + +export function assertNetworkTarget(policy: SandboxPolicy, url: string): void { + const parsed = new URL(url); + if (policy.mode === 'unrestricted' || policy.network.mode === 'unrestricted') return; + if (policy.network.mode === 'none') { + throw new AgentError( + 'SANDBOX_NETWORK_DENIED', + `Network access is disabled: ${parsed.hostname}` + ); + } + if (!policy.network.hosts.includes(parsed.hostname)) { + throw new AgentError( + 'SANDBOX_NETWORK_DENIED', + `Network host is not allowlisted: ${parsed.hostname}` + ); + } + const port = parsed.port ? Number(parsed.port) : parsed.protocol === 'https:' ? 443 : 80; + if (!policy.network.ports.includes(port)) { + throw new AgentError('SANDBOX_NETWORK_DENIED', `Network port is not allowlisted: ${port}`); + } +} diff --git a/packages/codingcode/src/sandbox/policy.ts b/packages/codingcode/src/sandbox/policy.ts new file mode 100644 index 00000000..4be0ddfa --- /dev/null +++ b/packages/codingcode/src/sandbox/policy.ts @@ -0,0 +1,127 @@ +import { createHash } from 'node:crypto'; +import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'; +import { normalizePath } from '../util/path.js'; +import type { PermissionMode } from '../util/enums.js'; +import type { + SandboxMode, + SandboxPolicy, + SandboxPolicyContext, + SandboxResolution, +} from './types.js'; + +const MODE_RANK: Record = { + 'read-only': 0, + 'workspace-write': 1, + 'danger-full-access': 2, + unrestricted: 3, +}; + +function canonicalRoot(value: string): string | undefined { + if (!value || !isAbsolute(value)) return undefined; + return normalizePath(resolve(value)); +} + +function isWithin(root: string, target: string): boolean { + const rel = relative(root, target); + return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)); +} + +function stableValue(value: unknown): string { + if (value === null || typeof value !== 'object') return JSON.stringify(value); + if (Array.isArray(value)) return `[${value.map(stableValue).join(',')}]`; + return `{${Object.keys(value as Record) + .sort() + .map((key) => `${JSON.stringify(key)}:${stableValue((value as Record)[key])}`) + .join(',')}}`; +} + +function fingerprint(policy: Omit): string { + return createHash('sha256').update(stableValue(policy)).digest('hex'); +} + +function requestedMode(permissionMode: PermissionMode): SandboxMode { + if (permissionMode === 'unrestricted') return 'unrestricted'; + if (permissionMode === 'bypass') return 'danger-full-access'; + return 'read-only'; +} + +function networkFor(context: SandboxPolicyContext, mode: SandboxMode): SandboxPolicy['network'] { + if (mode === 'danger-full-access' || mode === 'unrestricted') { + return { mode: 'unrestricted', hosts: [], ports: [] }; + } + + if (context.operation?.network) { + return { + mode: 'allowlist', + hosts: [...context.operation.network.hosts].sort(), + ports: [...context.operation.network.ports].sort((a, b) => a - b), + }; + } + + return { mode: 'none', hosts: [], ports: [] }; +} + +export function resolveSandboxPolicy(context: SandboxPolicyContext): SandboxResolution { + const workspaceRoot = canonicalRoot(context.projectPath); + if (!workspaceRoot) return { kind: 'deny', reason: 'projectPath must be an absolute path' }; + + const requested = context.requestedMode ?? requestedMode(context.permissionMode as PermissionMode); + const parent = context.parentPolicy; + const requiresWrite = context.operation?.workspace?.write === true; + const existingRoots = [ + workspaceRoot, + ...(context.additionalWritableRoots ?? []).map(canonicalRoot).filter((v): v is string => !!v), + ]; + const outsideWritePaths = (context.operation?.workspace?.paths ?? []) + .map((path) => resolve(workspaceRoot, path)) + .filter((path) => !existingRoots.some((root) => isWithin(root, path))); + if ( + outsideWritePaths.length > 0 && + context.permissionMode !== 'askBeforeExec' && + context.permissionMode !== 'unrestricted' + ) { + return { kind: 'deny', reason: 'write target is outside the sandbox roots' }; + } + const escalation = + requiresWrite && + requested === 'read-only' && + context.permissionMode === 'askBeforeExec'; + const mode = escalation ? 'workspace-write' : requested; + if (parent && MODE_RANK[mode] > MODE_RANK[parent.mode]) { + return { kind: 'deny', reason: `sandbox mode ${mode} exceeds parent mode ${parent.mode}` }; + } + const additionalWritableRoots = [ + ...(context.additionalWritableRoots ?? []), + ...outsideWritePaths.map((path) => dirname(path)), + ] + .map(canonicalRoot) + .filter((value): value is string => value !== undefined) + .sort(); + const policyWithoutFingerprint: Omit = { + mode, + workspaceRoot, + additionalWritableRoots, + network: networkFor(context, mode), + sessionId: context.sessionId, + enforcement: mode === 'read-only' || mode === 'workspace-write' ? 'required' : 'disabled', + }; + + const policy = { ...policyWithoutFingerprint, fingerprint: fingerprint(policyWithoutFingerprint) }; + if (escalation) { + return { + kind: 'escalation', + policy, + request: { + currentMode: 'read-only', + targetMode: 'workspace-write', + sessionId: context.sessionId, + callId: context.callId ?? '', + toolName: context.toolName ?? '', + argsHash: context.argsHash ?? '', + justification: 'This tool call writes to the workspace.', + additionalWritableRoots, + }, + }; + } + return { kind: 'ready', policy }; +} diff --git a/packages/codingcode/src/sandbox/provider.ts b/packages/codingcode/src/sandbox/provider.ts new file mode 100644 index 00000000..960fd8a6 --- /dev/null +++ b/packages/codingcode/src/sandbox/provider.ts @@ -0,0 +1,117 @@ +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { Effect } from 'effect'; +import { AgentError } from '../util/error.js'; +import type { ConfinedCommand, SandboxPolicy } from './types.js'; + +const execFileAsync = promisify(execFile); + +function quoteProfilePath(path: string): string { + return JSON.stringify(path); +} + +function seatbeltProfile(policy: SandboxPolicy): string { + const writable = [policy.workspaceRoot, ...policy.additionalWritableRoots] + .map((root) => `(subpath ${quoteProfilePath(root)})`) + .join(' '); + const network = policy.network.mode === 'none' ? '(deny network*)' : '(allow network*)'; + return `(version 1) +(deny default) +(allow process*) +(allow file-read*) +(allow file-write* ${writable}) +${network}`; +} + +async function executable(name: string): Promise { + try { + await execFileAsync(process.platform === 'win32' ? 'where.exe' : 'which', [name]); + return true; + } catch { + return false; + } +} + +export interface SandboxProvider { + confine( + argv: readonly string[], + policy: SandboxPolicy + ): Effect.Effect; +} + +export const localSandboxProvider: SandboxProvider = { + confine: (argv, policy) => { + if (policy.mode === 'danger-full-access' || policy.mode === 'unrestricted') { + return Effect.succeed({ argv: [...argv], enforcement: 'disabled', runner: 'none' }); + } + + if (policy.network.mode === 'allowlist') { + return Effect.fail( + new AgentError( + 'SANDBOX_UNAVAILABLE', + 'The local process sandbox cannot enforce network host allowlists' + ) + ); + } + + return Effect.tryPromise({ + try: async (): Promise => { + if (process.platform === 'linux') { + if (!(await executable('bwrap'))) { + throw new AgentError( + 'SANDBOX_UNAVAILABLE', + 'bubblewrap is required for restricted command execution' + ); + } + const args = [ + 'bwrap', + '--die-with-parent', + '--unshare-user-try', + '--unshare-pid', + ...(policy.network.mode === 'none' ? ['--unshare-net'] : []), + '--dev', + '/dev', + '--proc', + '/proc', + '--tmpfs', + '/tmp', + ]; + for (const root of ['/usr', '/bin', '/lib', '/lib64', '/etc']) { + try { + await import('node:fs/promises').then(({ access }) => access(root)); + args.push('--ro-bind', root, root); + } catch { + // Optional platform paths are omitted. + } + } + args.push('--bind', policy.workspaceRoot, policy.workspaceRoot, '--chdir', policy.workspaceRoot); + for (const root of policy.additionalWritableRoots) args.push('--bind', root, root); + return { argv: [...args, '--', ...argv], enforcement: 'full', runner: 'bwrap' }; + } + + if (process.platform === 'darwin') { + if (!(await executable('sandbox-exec'))) { + throw new AgentError( + 'SANDBOX_UNAVAILABLE', + 'sandbox-exec is required for restricted command execution' + ); + } + return { + argv: ['sandbox-exec', '-p', seatbeltProfile(policy), ...argv], + enforcement: 'full', + runner: 'seatbelt', + }; + } + + throw new AgentError( + 'SANDBOX_UNAVAILABLE', + `No OS sandbox provider is available for ${process.platform}` + ); + }, + catch: (error) => + error instanceof AgentError + ? error + : new AgentError('SANDBOX_UNAVAILABLE', String(error), error), + }); + }, +}; diff --git a/packages/codingcode/src/sandbox/types.ts b/packages/codingcode/src/sandbox/types.ts new file mode 100644 index 00000000..be4caa45 --- /dev/null +++ b/packages/codingcode/src/sandbox/types.ts @@ -0,0 +1,68 @@ +export type SandboxMode = 'read-only' | 'workspace-write' | 'danger-full-access' | 'unrestricted'; + +export type SandboxNetworkMode = 'none' | 'allowlist' | 'unrestricted'; + +export type DangerousOperation = + | 'workspace_escape' + | 'destructive_delete' + | 'permission_change' + | 'process_control' + | 'credential_access' + | 'network_unrestricted' + | 'remote_code_fetch' + | 'repository_history_write' + | 'system_configuration'; + +export interface SandboxPolicy { + readonly mode: SandboxMode; + readonly workspaceRoot: string; + readonly additionalWritableRoots: readonly string[]; + readonly network: { + readonly mode: SandboxNetworkMode; + readonly hosts: readonly string[]; + readonly ports: readonly number[]; + }; + readonly sessionId: string; + readonly enforcement: 'required' | 'best-effort' | 'disabled'; + readonly fingerprint: string; +} + +export interface SandboxPolicyContext { + readonly projectPath: string; + readonly sessionId: string; + readonly permissionMode: string; + readonly requestedMode?: SandboxMode; + readonly operation?: import('../tools/types.js').ToolApprovalMetadata; + readonly parsedArgs?: unknown; + readonly parentPolicy?: SandboxPolicy; + readonly additionalWritableRoots?: readonly string[]; + readonly callId?: string; + readonly toolName?: string; + readonly argsHash?: string; +} + +export interface SandboxEscalationRequest { + readonly currentMode: SandboxMode; + readonly targetMode: SandboxMode; + readonly sessionId: string; + readonly callId: string; + readonly toolName: string; + readonly argsHash: string; + readonly justification: string; + readonly additionalWritableRoots?: readonly string[]; +} + +export type SandboxResolution = + | { readonly kind: 'ready'; readonly policy: SandboxPolicy } + | { + readonly kind: 'escalation'; + readonly request: SandboxEscalationRequest; + readonly policy: SandboxPolicy; + } + | { readonly kind: 'deny'; readonly reason: string }; + +export interface ConfinedCommand { + readonly argv: readonly string[]; + readonly enforcement: 'full' | 'partial' | 'disabled'; + readonly runner: 'bwrap' | 'seatbelt' | 'windows' | 'none'; +} diff --git a/packages/codingcode/src/scheduler/scheduler.ts b/packages/codingcode/src/scheduler/scheduler.ts index 3c4e42d8..61e7a547 100644 --- a/packages/codingcode/src/scheduler/scheduler.ts +++ b/packages/codingcode/src/scheduler/scheduler.ts @@ -12,7 +12,7 @@ import { AgentService } from '../agent/port.js'; import { activeModelId } from '../infra/models.js'; import { textPart } from '../llm/types.js'; import { SchedulerService } from './port.js'; -import { BYPASS_PERMISSION_MODE, BUILD_PROFILE_NAME } from '../util/enums.js'; +import { BYPASS_PERMISSION_MODE } from '../util/enums.js'; const logger = createLogger(); @@ -56,8 +56,8 @@ export const SchedulerLayer = Layer.effect( signal: controller.signal, // 自动化没有独立的模型配置,统一用 config.yaml 的活动模型 model: activeModelId(), - activeProfile: BUILD_PROFILE_NAME, permissionMode: BYPASS_PERMISSION_MODE, + sandboxMode: auto.sandbox === 'readonly' ? 'read-only' : 'workspace-write', }); }) ); @@ -191,8 +191,8 @@ export const SchedulerLayer = Layer.effect( cwd: auto.projectCwd, signal: controller.signal, model: activeModelId(), - activeProfile: BUILD_PROFILE_NAME, permissionMode: BYPASS_PERMISSION_MODE, + sandboxMode: auto.sandbox === 'readonly' ? 'read-only' : 'workspace-write', }); }) ); diff --git a/packages/codingcode/src/server/http-error.ts b/packages/codingcode/src/server/http-error.ts index 6be2d8cb..4997e461 100644 --- a/packages/codingcode/src/server/http-error.ts +++ b/packages/codingcode/src/server/http-error.ts @@ -22,6 +22,10 @@ const DOMAIN_STATUS: Record = { SESSION_IO_ERROR: 500, INVALID_INPUT: 400, TURN_CONFLICT: 409, + SANDBOX_UNAVAILABLE: 403, + SANDBOX_PATH_DENIED: 403, + SANDBOX_NETWORK_DENIED: 403, + SANDBOX_POLICY_DENIED: 403, }; export class NotFoundError extends Error { diff --git a/packages/codingcode/src/server/routes/agent.ts b/packages/codingcode/src/server/routes/agent.ts index a9a85c5e..a37af7e3 100644 --- a/packages/codingcode/src/server/routes/agent.ts +++ b/packages/codingcode/src/server/routes/agent.ts @@ -5,21 +5,18 @@ import { updateMaxSteps, updateMaxStopContinuations, updateContextCompactionModel, - updateActiveProfile, updatePermissionMode, } from '../../infra/config.js'; -import { isAgentProfileName } from '../../agent/profile.js'; import { isPermissionMode } from '../../approval/types.js'; import { AgentError } from '../../util/error.js'; import { json, readJson, type Handler, type Router } from '../handler.js'; -import { ASK_BEFORE_EXEC_PERMISSION_MODE, BUILD_PROFILE_NAME } from '../../util/enums.js'; +import { ASK_BEFORE_EXEC_PERMISSION_MODE } from '../../util/enums.js'; function readAgentConfig() { const cfg = loadConfig(); return { maxSteps: cfg.maxSteps, maxStopContinuations: cfg.maxStopContinuations, - activeProfile: isAgentProfileName(cfg.activeProfile) ? cfg.activeProfile : BUILD_PROFILE_NAME, permissionMode: isPermissionMode(cfg.permissionMode) ? cfg.permissionMode : ASK_BEFORE_EXEC_PERMISSION_MODE, @@ -32,15 +29,9 @@ const putConfig: Handler = Effect.gen(function* () { const body = yield* readJson<{ maxSteps?: number; maxStopContinuations?: number; - activeProfile?: string; permissionMode?: string; }>(); - if (body.activeProfile !== undefined && !isAgentProfileName(body.activeProfile)) { - return yield* Effect.fail( - new AgentError('CONFIG_INVALID', `Invalid activeProfile: ${body.activeProfile}`) - ); - } if (body.permissionMode !== undefined && !isPermissionMode(body.permissionMode)) { return yield* Effect.fail( new AgentError('CONFIG_INVALID', `Invalid permissionMode: ${body.permissionMode}`) @@ -49,7 +40,6 @@ const putConfig: Handler = Effect.gen(function* () { if (body.maxSteps !== undefined) updateMaxSteps(body.maxSteps); if (body.maxStopContinuations !== undefined) updateMaxStopContinuations(body.maxStopContinuations); - if (body.activeProfile !== undefined) updateActiveProfile(body.activeProfile); if (body.permissionMode !== undefined) updatePermissionMode(body.permissionMode); return json(readAgentConfig()); }); diff --git a/packages/codingcode/src/server/routes/messages.ts b/packages/codingcode/src/server/routes/messages.ts index 7560f79c..77f384d0 100644 --- a/packages/codingcode/src/server/routes/messages.ts +++ b/packages/codingcode/src/server/routes/messages.ts @@ -2,11 +2,10 @@ import * as HttpRouter from '@effect/platform/HttpRouter'; import { Effect } from 'effect'; import { AgentService } from '../../agent/port.js'; import { resolveWorkspaceCwd } from '../cwd.js'; -import { isAgentProfileName } from '../../agent/profile.js'; import { isPermissionMode } from '../../approval/types.js'; import { loadConfig } from '../../infra/config.js'; import { AgentError } from '../../util/error.js'; -import { ASK_BEFORE_EXEC_PERMISSION_MODE, BUILD_PROFILE_NAME } from '../../util/enums.js'; +import { ASK_BEFORE_EXEC_PERMISSION_MODE } from '../../util/enums.js'; import type { IncomingMedia, IncomingPart } from '../../llm/types.js'; import { frameStream, @@ -102,9 +101,6 @@ const sendMessage: Handler = Effect.gen(function* () { }; if (isNew) { const cfg = loadConfig(); - runOpts.activeProfile = isAgentProfileName(cfg.activeProfile) - ? cfg.activeProfile - : BUILD_PROFILE_NAME; runOpts.permissionMode = isPermissionMode(cfg.permissionMode) ? cfg.permissionMode : ASK_BEFORE_EXEC_PERMISSION_MODE; diff --git a/packages/codingcode/src/server/routes/sessions.ts b/packages/codingcode/src/server/routes/sessions.ts index 8b0ba284..2832ccd4 100644 --- a/packages/codingcode/src/server/routes/sessions.ts +++ b/packages/codingcode/src/server/routes/sessions.ts @@ -1,12 +1,9 @@ import * as HttpRouter from '@effect/platform/HttpRouter'; import { Effect } from 'effect'; -import { existsSync, readFileSync, readdirSync, statSync } from 'fs'; -import { join } from 'path'; import type { SessionStoreState } from '../../session/types.js'; import { ASK_BEFORE_EXEC_PERMISSION_MODE, type PermissionMode, - type ProfileName, } from '../../util/enums.js'; import { SessionService } from '../../session/port.js'; @@ -19,8 +16,6 @@ import { estimatePromptTokensFrom } from '../../context/context.js'; import { CheckpointService } from '../../checkpoint/port.js'; import { activeModelId, setGlobalActive } from '../../infra/models.js'; import { resolveCwd, resolveWorkspaceCwd } from '../cwd.js'; -import { projectDataDir } from '../../util/path.js'; -import { isAgentProfileName } from '../../agent/profile.js'; import { isPermissionMode } from '../../approval/types.js'; import { AgentError } from '../../util/error.js'; import { json, pathParams, query, readJson, type Handler, type Router } from '../handler.js'; @@ -37,16 +32,10 @@ const listSessions: Handler = Effect.gen(function* () { const createSession: Handler = Effect.gen(function* () { const body = yield* readJson<{ cwd: string; - activeProfile: ProfileName; permissionMode: PermissionMode; model: string; }>(); - if (!isAgentProfileName(body.activeProfile)) { - return yield* Effect.fail( - new AgentError('CONFIG_INVALID', `Invalid activeProfile: ${body.activeProfile}`) - ); - } if (!isPermissionMode(body.permissionMode)) { return yield* Effect.fail( new AgentError('CONFIG_INVALID', `Invalid permissionMode: ${body.permissionMode}`) @@ -61,7 +50,6 @@ const createSession: Handler = Effect.gen(function* () { const session = yield* SessionService; const state = (yield* session.create(cwd, { model: body.model, - activeProfile: body.activeProfile, permissionMode: body.permissionMode, })) as SessionStoreState; return json({ sessionId: state.sessionId }); @@ -125,70 +113,6 @@ const sessionHistory: Handler = Effect.gen(function* () { return json(yield* session.readUITurns(id ?? '', cwd)); }); -// ---- Plan file: read the current plan document for a session ---- - -const readLatestPlan = (planDir: string): { path: string; content: string } | null => { - if (!existsSync(planDir)) return null; - let latest: { path: string; mtime: number } | null = null; - for (const name of readdirSync(planDir)) { - if (!name.endsWith('.md')) continue; - const full = join(planDir, name); - const mtime = statSync(full).mtimeMs; - if (latest === null || mtime > latest.mtime) { - latest = { path: full, mtime }; - } - } - return latest === null ? null : { path: latest.path, content: readFileSync(latest.path, 'utf8') }; -}; - -const readPlan: Handler = Effect.gen(function* () { - const { cwd: rawCwd } = yield* query; - const planDir = projectDataDir(resolveCwd(rawCwd)); - const missing = json({ content: '', path: '', directory: planDir, exists: false }); - - const latest = yield* Effect.try({ - try: () => readLatestPlan(planDir), - catch: (e) => new AgentError('SESSION_IO_ERROR', `Failed to read plan: ${String(e)}`), - }); - - if (latest === null) return missing; - return json({ content: latest.content, path: latest.path, directory: planDir, exists: true }); -}); - -// ---- Agent profile switching ---- - -const getProfile: Handler = Effect.gen(function* () { - const { id } = yield* pathParams; - const cwd = resolveCwd((yield* query).cwd); - const session = yield* SessionService; - const state = yield* session.load(cwd, id ?? ''); - return json({ - activeProfile: state.activeProfile, - permissionMode: state.permissionMode, - cwd, - }); -}); - -const setProfile: Handler = Effect.gen(function* () { - const { id } = yield* pathParams; - const body = yield* readJson<{ cwd?: string; activeProfile: ProfileName }>(); - const cwd = resolveCwd(body.cwd); - const activeProfile = body.activeProfile; - if (!isAgentProfileName(activeProfile)) { - return yield* Effect.fail( - new AgentError('CONFIG_INVALID', `Invalid activeProfile: ${activeProfile}`) - ); - } - - const session = yield* SessionService; - yield* session.setActiveProfile(cwd, id ?? '', activeProfile); - const state = yield* session.load(cwd, id ?? ''); - return json({ - activeProfile: state.activeProfile, - permissionMode: state.permissionMode, - }); -}); - const getPermissionMode: Handler = Effect.gen(function* () { const { id } = yield* pathParams; const { cwd } = yield* query; @@ -377,9 +301,6 @@ export const addSessionsRoutes = (router: Router): Router => { HttpRouter.post('/api/sessions/:id/compact', compactSession), HttpRouter.del('/api/sessions/:id', deleteSession), HttpRouter.get('/api/sessions/:id/history', sessionHistory), - HttpRouter.get('/api/sessions/:id/plan', readPlan), - HttpRouter.get('/api/sessions/:id/profile', getProfile), - HttpRouter.post('/api/sessions/:id/profile', setProfile), HttpRouter.get('/api/sessions/:id/permission-mode', getPermissionMode), HttpRouter.put('/api/sessions/:id/permission-mode', setPermissionMode) ); diff --git a/packages/codingcode/src/session/file-ops.ts b/packages/codingcode/src/session/file-ops.ts index 533f20c2..88250495 100644 --- a/packages/codingcode/src/session/file-ops.ts +++ b/packages/codingcode/src/session/file-ops.ts @@ -69,7 +69,7 @@ export function readSessionMeta(transcriptPath: string): SessionMetaEvent | null } } -/** 原子重写首行(身份字段变更:标题 / 模型 / 权限模式 / profile)。 */ +/** 原子重写首行(身份字段变更:标题 / 模型 / 权限模式)。 */ export function rewriteSessionMeta(transcriptPath: string, patch: Partial): void { const raw = readFileSync(transcriptPath, 'utf8'); const newlineAt = raw.indexOf('\n'); diff --git a/packages/codingcode/src/session/port.ts b/packages/codingcode/src/session/port.ts index a7848e28..13a71cad 100644 --- a/packages/codingcode/src/session/port.ts +++ b/packages/codingcode/src/session/port.ts @@ -13,7 +13,7 @@ import type { SessionCreateOptions, SessionSummary, SessionStoreState } from './ import type { UITurn } from './types.js'; import type { StoredPart } from './types.js'; import type { IncomingPart, TokenUsage } from '../llm/types.js'; -import type { ProfileName, PermissionMode } from '../util/enums.js'; +import type { PermissionMode } from '../util/enums.js'; export interface SessionShape { create( @@ -93,13 +93,6 @@ export interface SessionShape { parentSessionId?: string, parentChain?: readonly string[] ): Effect.Effect; - setActiveProfile( - cwd: string, - sessionId: string, - profile: ProfileName, - parentSessionId?: string, - parentChain?: readonly string[] - ): Effect.Effect; setModel( cwd: string, sessionId: string, diff --git a/packages/codingcode/src/session/session.ts b/packages/codingcode/src/session/session.ts index c55f3e9f..0fa2f4d1 100644 --- a/packages/codingcode/src/session/session.ts +++ b/packages/codingcode/src/session/session.ts @@ -39,7 +39,7 @@ import { type IncomingPart, type TokenUsage, } from '../llm/types.js'; -import type { ProfileName, PermissionMode } from '../util/enums.js'; +import type { PermissionMode } from '../util/enums.js'; import { SessionService } from './port.js'; import { @@ -202,7 +202,6 @@ export const SessionLayer = Layer.effect( options: { model: string; title?: string; - activeProfile: ProfileName; permissionMode: PermissionMode; }, opts?: { @@ -225,7 +224,6 @@ export const SessionLayer = Layer.effect( createdAt: new Date().toISOString(), model: options.model, title: options.title ? truncateTitle(options.title) : '', - activeProfile: options.activeProfile, permissionMode: options.permissionMode, ...(opts?.parentSessionId && { parentSessionId: opts.parentSessionId }), // 链随子会话落盘:续跑与路径定位都不必再依赖调用方重述 @@ -562,18 +560,6 @@ export const SessionLayer = Layer.effect( rewriteSessionMeta(paths.transcriptPath, { permissionMode: mode }); }); - const setActiveProfile = ( - cwd: string, - sessionId: string, - profile: ProfileName, - parentSessionId?: string, - parentChain?: readonly string[] - ): Effect.Effect => - Effect.sync(() => { - const paths = computePaths(cwd, sessionId, parentSessionId, parentChain); - rewriteSessionMeta(paths.transcriptPath, { activeProfile: profile }); - }); - // 会话级切模型:只写会话首行,不碰 config.yaml const setModel = ( cwd: string, @@ -626,7 +612,6 @@ export const SessionLayer = Layer.effect( Effect.sync(() => readUIHistory(sessionId, cwd)), setPermissionMode: setPermissionModeByAddress, - setActiveProfile, setModel, }; }) diff --git a/packages/codingcode/src/session/types.ts b/packages/codingcode/src/session/types.ts index 10206fb5..35230489 100644 --- a/packages/codingcode/src/session/types.ts +++ b/packages/codingcode/src/session/types.ts @@ -1,5 +1,5 @@ import type { MediaPart, ReasoningData, TextPart, TokenUsage, ToolCall } from '../llm/types.js'; -import type { ProfileName, PermissionMode } from '../util/enums.js'; +import type { PermissionMode } from '../util/enums.js'; /** * 落盘形态的媒体块:MediaPart 之上附物化时解析出的元数据。 @@ -25,7 +25,6 @@ export interface SessionMetaEvent { createdAt: string; model: string; title: string; - activeProfile: ProfileName; permissionMode: PermissionMode; parentSessionId?: string; agentName?: string; @@ -36,7 +35,7 @@ export interface SessionMetaEvent { parentChain?: string[]; /** 子智能体用途描述;首次派发时给出,供 list_agents 展示 */ description?: string; - /** 子会话自定义 system prompt 中间段;仅子会话写入,续跑时回读,缺省回落 profile */ + /** 子会话自定义 system prompt 中间段;仅子会话写入,续跑时回读 */ systemPrompt?: string; } @@ -132,7 +131,6 @@ export interface SessionStoreState extends SessionMetaEvent { export interface SessionCreateOptions { model: string; title?: string; - activeProfile: ProfileName; permissionMode: PermissionMode; } diff --git a/packages/codingcode/src/sink/types.ts b/packages/codingcode/src/sink/types.ts index eedc95f6..2c7920c2 100644 --- a/packages/codingcode/src/sink/types.ts +++ b/packages/codingcode/src/sink/types.ts @@ -1,6 +1,7 @@ import type { TodoItem } from '../todo/types.js'; import type { TokenUsage } from '../llm/types.js'; import type { StoredPart } from '../session/types.js'; +import type { ApprovalAction } from '../approval/types.js'; export interface FrameError { readonly message: string; @@ -47,6 +48,7 @@ export type RuntimeEvent = readonly type: 'approval_request'; readonly id: string; readonly tool: string; + readonly action: ApprovalAction; readonly args: Readonly>; } | { diff --git a/packages/codingcode/src/subagent/port.ts b/packages/codingcode/src/subagent/port.ts index ce6582b6..b7e03582 100644 --- a/packages/codingcode/src/subagent/port.ts +++ b/packages/codingcode/src/subagent/port.ts @@ -3,14 +3,15 @@ import type { Effect } from 'effect'; import type { FrameBody } from '../sink/types.js'; import type { AgentError } from '../util/error.js'; import type { Result } from '../util/result.js'; -import type { ProfileName, PermissionMode } from '../util/enums.js'; +import type { PermissionMode } from '../util/enums.js'; +import type { SandboxPolicy } from '../sandbox/types.js'; import type { IncomingPart } from '../llm/types.js'; export interface RunSubagentOptions { sessionId?: string; cwd: string; - activeProfile?: ProfileName; permissionMode?: PermissionMode; + sandboxPolicy?: SandboxPolicy; model: string; /** 首次派发时的自定义 system prompt;续跑(传 sessionId)时忽略,改由会话头回读 */ systemPrompt?: string; diff --git a/packages/codingcode/src/subagent/registry.ts b/packages/codingcode/src/subagent/registry.ts index 0ff3fbc7..eb738785 100644 --- a/packages/codingcode/src/subagent/registry.ts +++ b/packages/codingcode/src/subagent/registry.ts @@ -3,7 +3,8 @@ import { randomUUID } from 'crypto'; import { AgentError } from '../util/error.js'; import { isTurnEnd } from '../sink/types.js'; import type { EndTransition, FrameBody } from '../sink/types.js'; -import { BYPASS_PERMISSION_MODE, type ProfileName } from '../util/enums.js'; +import type { PermissionMode } from '../util/enums.js'; +import type { SandboxPolicy } from '../sandbox/types.js'; import { SUBAGENT_RESULT_PREFIX } from '../session/types.js'; import type { SubagentResultEvent } from '../session/types.js'; import { transcriptPathOf } from '../session/paths.js'; @@ -23,7 +24,8 @@ export interface SpawnOptions { agentName: string; parentSessionId: string; parentCwd: string; - parentProfile: ProfileName; + parentPermissionMode?: PermissionMode; + parentPolicy?: SandboxPolicy; /** 已由调用方解析过的模型 id(含清单校验与父模型回退) */ model: string; systemPrompt?: string; @@ -219,8 +221,8 @@ export const SubagentRunRegistryLayer = Layer.scoped( const { stream, sessionId } = yield* runner.runSubagent([textPart(opts.prompt)], { sessionId: opts.resumeSessionId, // 续跑:复用既有子会话与历史上下文 cwd: opts.parentCwd, - activeProfile: opts.parentProfile, - permissionMode: BYPASS_PERMISSION_MODE, + permissionMode: opts.parentPermissionMode ?? 'askBeforeExec', + sandboxPolicy: opts.parentPolicy, parentSessionId: opts.parentSessionId, agentName: opts.agentName, description: opts.description, diff --git a/packages/codingcode/src/subagent/subagent.ts b/packages/codingcode/src/subagent/subagent.ts index 4f63c14c..f0ea6bed 100644 --- a/packages/codingcode/src/subagent/subagent.ts +++ b/packages/codingcode/src/subagent/subagent.ts @@ -29,9 +29,9 @@ export const SubagentRunnerLayer = Layer.effect( const result = yield* agent.runTurn(input, { sessionId: opts.sessionId, cwd: opts.cwd, - activeProfile: opts.activeProfile, // 子代理不经审批:调用点未给定时固定 bypass,避免继承父会话的审批链路 permissionMode: opts.permissionMode ?? BYPASS_PERMISSION_MODE, + sandboxPolicy: opts.sandboxPolicy, model: opts.model, parentSessionId: opts.parentSessionId, agentName: opts.agentName, diff --git a/packages/codingcode/src/tools/catalog.ts b/packages/codingcode/src/tools/catalog.ts index 771db568..08ddc856 100644 --- a/packages/codingcode/src/tools/catalog.ts +++ b/packages/codingcode/src/tools/catalog.ts @@ -1,8 +1,9 @@ import { z } from 'zod'; -import type { Effect } from 'effect'; +import { Effect } from 'effect'; import type { ToolDefinition, ToolExecCtx, ToolCatalog } from './types.js'; +import type { ToolApprovalMetadata } from './types.js'; import type { McpToolSpec } from '../mcp/types.js'; -import type { AgentError } from '../util/error.js'; +import { AgentError } from '../util/error.js'; import { ToolRegistry } from './registry.js'; import { readFileTool } from './domains/fs/read.js'; import { writeFileTool } from './domains/fs/write.js'; @@ -17,7 +18,6 @@ import { todoReadTool } from './domains/self/todo-read.js'; import { askUserTool } from './domains/self/ask-user.js'; import { spawnAgentTool } from './domains/subagent/spawn.js'; import { waitAgentTool } from './domains/subagent/wait.js'; -import { submitPlanTool } from './domains/subagent/submit-plan.js'; import { resumeAgentTool } from './domains/subagent/resume.js'; import { sendMessageTool } from './domains/subagent/message.js'; import { interruptAgentTool } from './domains/subagent/interrupt.js'; @@ -37,7 +37,6 @@ const ALL_TOOLS: ToolDefinition[] = [ askUserTool, spawnAgentTool, waitAgentTool, - submitPlanTool, resumeAgentTool, sendMessageTool, interruptAgentTool, @@ -52,22 +51,33 @@ function specToDefinition(spec: McpToolSpec): ToolDefinition { description: `[MCP:${spec.server}] ${spec.description || spec.name}`, parameters: z.fromJSONSchema(spec.inputSchema), concurrencySafe: spec.readOnlyHint, - // MCP 工具一律算写:无法静态判定其副作用,漏打的代价是丢改动 - mutatesWorkspace: true, - execute: (args) => spec.execute(args as Record), + approval: { action: 'mcp', requiresConfirmation: true }, + execute: (args, ctx) => { + if (!ctx?.sandboxPolicy) { + return Effect.fail( + new AgentError('SANDBOX_POLICY_DENIED', 'MCP tool requires a sandbox policy') + ); + } + if ( + ctx.sandboxPolicy.mode !== 'danger-full-access' && + ctx.sandboxPolicy.mode !== 'unrestricted' && + !spec.readOnlyHint + ) { + return Effect.fail( + new AgentError( + 'SANDBOX_POLICY_DENIED', + 'MCP tool is not read-only under the current sandbox' + ) + ); + } + return spec.execute(args as Record); + }, }; } -export function createToolCatalog( - toolNames: readonly string[], - mcpTools: McpToolSpec[] = [] -): ToolCatalog { +export function createToolCatalog(mcpTools: McpToolSpec[] = []): ToolCatalog { const registry = new ToolRegistry(); - for (const name of toolNames) { - const definition = TOOLS_BY_NAME.get(name); - if (!definition) throw new Error(`Unknown tool: ${name}`); - registry.register(definition); - } + registry.register(...TOOLS_BY_NAME.values()); registry.register(...mcpTools.map(specToDefinition)); return { tools: registry.describe(), @@ -77,7 +87,8 @@ export function createToolCatalog( return { name: definition.name, concurrencySafe: definition.concurrencySafe ?? false, - mutatesWorkspace: definition.mutatesWorkspace ?? false, + approval: definition.approval ?? { action: 'other' }, + describeOperation: definition.describeOperation ?? (() => definition.approval ?? { action: 'other' }), parse: (args: unknown) => definition.parameters.parse(args), execute: (args: unknown, ctx?: ToolExecCtx) => definition.execute(args, ctx) as Effect.Effect, diff --git a/packages/codingcode/src/tools/domains/bash/exec.ts b/packages/codingcode/src/tools/domains/bash/exec.ts index e41b5a5a..046010ac 100644 --- a/packages/codingcode/src/tools/domains/bash/exec.ts +++ b/packages/codingcode/src/tools/domains/bash/exec.ts @@ -4,12 +4,24 @@ import { Effect } from 'effect'; import type { ToolDefinition } from '../../types.js'; import { AgentError } from '../../../util/error.js'; +import { localSandboxProvider } from '../../../sandbox/provider.js'; +import { resolveFileTarget } from '../../../sandbox/file-boundary.js'; export const bashTool: ToolDefinition = { name: 'execute_command', concurrencySafe: false, - // 无法静态判定命令是否改工作区,一律算写 - mutatesWorkspace: true, + approval: { action: 'exec', requiresConfirmation: true, dangerous: ['process_control'] }, + describeOperation: (args) => { + const command = typeof (args as { command?: unknown }).command === 'string' ? (args as { command: string }).command : ''; + const dangerous = [] as ('destructive_delete' | 'permission_change' | 'process_control' | 'credential_access' | 'network_unrestricted' | 'remote_code_fetch' | 'repository_history_write' | 'system_configuration')[]; + if (/\b(rm|del|rd|rmdir)\b.*(?:-rf|\/s)/i.test(command) || /\b(find .* -delete|git\s+clean .*-[df]|git\s+reset\s+--hard)\b/i.test(command)) dangerous.push('destructive_delete'); + if (/\b(chmod|chown|icacls)\b/i.test(command)) dangerous.push('permission_change'); + if (/\b(kill|pkill|shutdown|reboot|systemctl|sc\.exe)\b/i.test(command)) dangerous.push('process_control'); + if (/(curl|wget|Invoke-WebRequest)[^\n]*(\||;|&&)[^\n]*(sh|bash|powershell|iex)\b/i.test(command)) dangerous.push('remote_code_fetch'); + if (/\b(curl|wget|Invoke-WebRequest|npm|pnpm|yarn|pip|git\s+clone)\b/i.test(command)) dangerous.push('network_unrestricted'); + if (/\b(git\s+(reset|rebase|push\s+--force)|git\s+clean)\b/i.test(command)) dangerous.push('repository_history_write'); + return { action: 'exec', requiresConfirmation: true, dangerous }; + }, description: 'Execute a shell command and return its output. Use for running tests, git, npm, build, and other CLI operations.', parameters: z.object({ @@ -19,70 +31,101 @@ export const bashTool: ToolDefinition = { }), execute: (args, ctx) => { const { command, cwd, timeout_ms } = args as any; - const workDir = cwd || ctx?.projectPath || process.cwd(); - return Effect.async((resume) => { - const proc = spawn(command, { - shell: true, - cwd: workDir, - env: process.env, - stdio: ['pipe', 'pipe', 'pipe'], + return Effect.gen(function* () { + if (!ctx?.projectPath || !ctx.sandboxPolicy) { + return yield* Effect.fail( + new AgentError('SANDBOX_UNAVAILABLE', 'execute_command requires a sandbox policy') + ); + } + const workDir = yield* Effect.tryPromise({ + try: () => resolveFileTarget(ctx.sandboxPolicy!, cwd || '.', 'read'), + catch: (error) => + error instanceof AgentError + ? error + : AgentError.toolExecutionFailed('execute_command', error), }); + const shellArgv = + process.platform === 'win32' + ? ['cmd.exe', '/d', '/s', '/c', command] + : ['/bin/sh', '-lc', command]; + const confined = yield* localSandboxProvider.confine(shellArgv, ctx.sandboxPolicy); + if (ctx.sandboxPolicy.enforcement === 'required' && confined.enforcement !== 'full') { + return yield* Effect.fail( + new AgentError( + 'SANDBOX_UNAVAILABLE', + 'The command sandbox did not provide full enforcement' + ) + ); + } + return yield* Effect.async((resume) => { + const [program, ...argv] = confined.argv; + const proc = spawn(program!, argv, { + shell: false, + cwd: workDir, + env: process.env, + stdio: ['pipe', 'pipe', 'pipe'], + }); - let stdout = ''; - let stderr = ''; - - // Kill process when abort signal fires (e.g. user clicks stop) - const onAbort = () => { - proc.kill(); - }; - ctx?.signal?.addEventListener('abort', onAbort, { once: true }); + let stdout = ''; + let stderr = ''; - proc.stdout?.on('data', (data: Buffer) => { - stdout += data.toString(); - if (stdout.length > 100_000) { - stdout = stdout.slice(0, 100_000) + '\n... (truncated)'; + // Kill process when abort signal fires (e.g. user clicks stop) + const onAbort = () => { proc.kill(); - } - }); + }; + ctx.signal?.addEventListener('abort', onAbort, { once: true }); - proc.stderr?.on('data', (data: Buffer) => { - stderr += data.toString(); - if (stderr.length > 50_000) stderr = stderr.slice(0, 50_000); - }); + proc.stdout?.on('data', (data: Buffer) => { + stdout += data.toString(); + if (stdout.length > 100_000) { + stdout = stdout.slice(0, 100_000) + '\n... (truncated)'; + proc.kill(); + } + }); - const timer = setTimeout(() => { - proc.kill(); - resume( - Effect.succeed( - `Command timed out after ${timeout_ms}ms\nStdout:\n${stdout}\nStderr:\n${stderr}` - ) - ); - }, timeout_ms); + proc.stderr?.on('data', (data: Buffer) => { + stderr += data.toString(); + if (stderr.length > 50_000) stderr = stderr.slice(0, 50_000); + }); - proc.on('close', (code) => { - clearTimeout(timer); - ctx?.signal?.removeEventListener('abort', onAbort); - resume( - Effect.succeed( - [ - `Exit code: ${code ?? 'null'}`, - stdout ? `Stdout:\n${stdout}` : '', - stderr ? `Stderr:\n${stderr}` : '', - ] - .filter(Boolean) - .join('\n') || '(no output)' - ) - ); - }); + const timer = setTimeout(() => { + proc.kill(); + resume( + Effect.succeed( + `Command timed out after ${timeout_ms}ms\nStdout:\n${stdout}\nStderr:\n${stderr}` + ) + ); + }, timeout_ms); - proc.on('error', (err) => { - clearTimeout(timer); - ctx?.signal?.removeEventListener('abort', onAbort); - resume( - Effect.fail( - new AgentError('TOOL_EXECUTION_FAILED', `Command failed to start: ${err.message}`, err) - ) - ); + proc.on('close', (code) => { + clearTimeout(timer); + ctx.signal?.removeEventListener('abort', onAbort); + resume( + Effect.succeed( + [ + `Exit code: ${code ?? 'null'}`, + stdout ? `Stdout:\n${stdout}` : '', + stderr ? `Stderr:\n${stderr}` : '', + ] + .filter(Boolean) + .join('\n') || '(no output)' + ) + ); + }); + + proc.on('error', (err) => { + clearTimeout(timer); + ctx.signal?.removeEventListener('abort', onAbort); + resume( + Effect.fail( + new AgentError( + 'TOOL_EXECUTION_FAILED', + `Command failed to start: ${err.message}`, + err + ) + ) + ); + }); }); }); }, diff --git a/packages/codingcode/src/tools/domains/fs/edit.ts b/packages/codingcode/src/tools/domains/fs/edit.ts index 7543a580..daccb216 100644 --- a/packages/codingcode/src/tools/domains/fs/edit.ts +++ b/packages/codingcode/src/tools/domains/fs/edit.ts @@ -1,14 +1,19 @@ import { z } from 'zod'; import { readFile, writeFile } from 'fs/promises'; -import { resolve } from 'path'; import { Effect } from 'effect'; import { AgentError } from '../../../util/error.js'; import type { ToolDefinition } from '../../types.js'; +import { resolveFileTarget } from '../../../sandbox/file-boundary.js'; export const editFileTool: ToolDefinition = { name: 'edit_file', concurrencySafe: false, - mutatesWorkspace: true, + approval: { action: 'file', requiresConfirmation: true }, + describeOperation: (args) => ({ + action: 'file', + requiresConfirmation: true, + workspace: { paths: [String((args as { path?: unknown }).path ?? '')], write: true }, + }), description: 'Perform exact string replacement in a file. Provide the exact text to replace (old_string) and the new text (new_string). If old_string is not unique in the file, the edit will fail — narrow the match to make it unique.', parameters: z.object({ @@ -26,7 +31,16 @@ export const editFileTool: ToolDefinition = { old_string: string; new_string: string; }; - const filePath = resolve(ctx?.projectPath ?? process.cwd(), path); + if (!ctx?.projectPath || !ctx.sandboxPolicy) { + return yield* Effect.fail( + new AgentError('SANDBOX_PATH_DENIED', 'edit_file requires a sandbox project path') + ); + } + const filePath = yield* Effect.tryPromise({ + try: () => resolveFileTarget(ctx.sandboxPolicy!, path, 'write'), + catch: (error) => + error instanceof AgentError ? error : AgentError.toolExecutionFailed('edit_file', error), + }); const content = yield* Effect.tryPromise({ try: () => readFile(filePath, 'utf-8'), catch: (e) => AgentError.toolExecutionFailed('edit_file', e), diff --git a/packages/codingcode/src/tools/domains/fs/glob.ts b/packages/codingcode/src/tools/domains/fs/glob.ts index 6d7dc098..8af08078 100644 --- a/packages/codingcode/src/tools/domains/fs/glob.ts +++ b/packages/codingcode/src/tools/domains/fs/glob.ts @@ -1,9 +1,10 @@ import { z } from 'zod'; import { globby } from 'globby'; -import { relative, resolve } from 'path'; +import { relative } from 'path'; import { Effect } from 'effect'; import { AgentError } from '../../../util/error.js'; import type { ToolDefinition } from '../../types.js'; +import { resolveFileTarget } from '../../../sandbox/file-boundary.js'; export const globTool: ToolDefinition = { name: 'search_files', @@ -31,8 +32,19 @@ export const globTool: ToolDefinition = { path: string; max_results: number; }; - const base = ctx?.projectPath ?? process.cwd(); - const basePath = resolve(base, path); + if (!ctx?.projectPath || !ctx.sandboxPolicy) { + return yield* Effect.fail( + new AgentError('SANDBOX_PATH_DENIED', 'search_files requires a sandbox project path') + ); + } + const base = ctx.projectPath; + const basePath = yield* Effect.tryPromise({ + try: () => resolveFileTarget(ctx.sandboxPolicy!, path, 'read'), + catch: (error) => + error instanceof AgentError + ? error + : AgentError.toolExecutionFailed('search_files', error), + }); const files = yield* Effect.tryPromise({ try: () => @@ -46,15 +58,29 @@ export const globTool: ToolDefinition = { catch: (e) => AgentError.toolExecutionFailed('search_files', e), }); - const truncated = files.slice(0, max_results); + const safeFiles = yield* Effect.tryPromise({ + try: async () => { + const checked: string[] = []; + for (const file of files) { + try { + checked.push(await resolveFileTarget(ctx.sandboxPolicy!, file, 'read')); + } catch { + // A glob result outside the sandbox is omitted. + } + } + return checked; + }, + catch: (e) => AgentError.toolExecutionFailed('search_files', e), + }); + const truncated = safeFiles.slice(0, max_results); const lines = truncated.map((f) => relative(base, f)); - if (files.length === 0) { + if (safeFiles.length === 0) { return `No files matching "${pattern}" in ${relative(base, basePath) || '.'}`; } - let out = `Found ${files.length} file(s) matching "${pattern}"`; - if (files.length > max_results) { + let out = `Found ${safeFiles.length} file(s) matching "${pattern}"`; + if (safeFiles.length > max_results) { out += ` (showing first ${max_results})`; } return out + '\n' + lines.join('\n'); diff --git a/packages/codingcode/src/tools/domains/fs/grep.ts b/packages/codingcode/src/tools/domains/fs/grep.ts index 1345d606..c6ea1881 100644 --- a/packages/codingcode/src/tools/domains/fs/grep.ts +++ b/packages/codingcode/src/tools/domains/fs/grep.ts @@ -5,6 +5,7 @@ import { relative } from 'path'; import { Effect } from 'effect'; import { AgentError } from '../../../util/error.js'; import type { ToolDefinition } from '../../types.js'; +import { resolveFileTarget } from '../../../sandbox/file-boundary.js'; export const searchTool: ToolDefinition = { name: 'search_code', @@ -28,7 +29,19 @@ export const searchTool: ToolDefinition = { execute: (args, ctx) => Effect.gen(function* () { const { pattern, glob, max_results } = args as any; - const base = ctx?.projectPath ?? process.cwd(); + if (!ctx?.projectPath || !ctx.sandboxPolicy) { + return yield* Effect.fail( + new AgentError('SANDBOX_PATH_DENIED', 'search_code requires a sandbox project path') + ); + } + const base = ctx.projectPath; + yield* Effect.tryPromise({ + try: () => resolveFileTarget(ctx.sandboxPolicy!, '.', 'read'), + catch: (error) => + error instanceof AgentError + ? error + : AgentError.toolExecutionFailed('search_code', error), + }); const files = yield* Effect.tryPromise({ try: () => globby(glob, { @@ -40,7 +53,21 @@ export const searchTool: ToolDefinition = { catch: (e) => AgentError.toolExecutionFailed('search_code', e), }); - const filesToScan = files.slice(0, 200); + const safeFiles = yield* Effect.tryPromise({ + try: async () => { + const checked: string[] = []; + for (const file of files) { + try { + checked.push(await resolveFileTarget(ctx.sandboxPolicy!, file, 'read')); + } catch { + // A glob result outside the sandbox is omitted. + } + } + return checked; + }, + catch: (e) => AgentError.toolExecutionFailed('search_code', e), + }); + const filesToScan = safeFiles.slice(0, 200); const results: string[] = []; const regex = new RegExp(pattern, 'gi'); diff --git a/packages/codingcode/src/tools/domains/fs/read.ts b/packages/codingcode/src/tools/domains/fs/read.ts index 3fd8c0fe..623ca1fa 100644 --- a/packages/codingcode/src/tools/domains/fs/read.ts +++ b/packages/codingcode/src/tools/domains/fs/read.ts @@ -1,9 +1,9 @@ import { z } from 'zod'; import { readFile } from 'fs/promises'; -import { resolve } from 'path'; import { Effect } from 'effect'; import { AgentError } from '../../../util/error.js'; import type { ToolDefinition } from '../../types.js'; +import { resolveFileTarget } from '../../../sandbox/file-boundary.js'; export const readFileTool: ToolDefinition = { name: 'read_file', @@ -23,7 +23,16 @@ export const readFileTool: ToolDefinition = { execute: (args, ctx) => Effect.gen(function* () { const { path, offset, limit } = args as any; - const filePath = resolve(ctx?.projectPath ?? process.cwd(), path); + if (!ctx?.projectPath || !ctx.sandboxPolicy) { + return yield* Effect.fail( + new AgentError('SANDBOX_PATH_DENIED', 'read_file requires a sandbox project path') + ); + } + const filePath = yield* Effect.tryPromise({ + try: () => resolveFileTarget(ctx.sandboxPolicy!, path, 'read'), + catch: (error) => + error instanceof AgentError ? error : AgentError.toolExecutionFailed('read_file', error), + }); const content = yield* Effect.tryPromise({ try: () => readFile(filePath, 'utf-8'), catch: (e) => AgentError.toolExecutionFailed('read_file', e), diff --git a/packages/codingcode/src/tools/domains/fs/write.ts b/packages/codingcode/src/tools/domains/fs/write.ts index 377bca87..56510993 100644 --- a/packages/codingcode/src/tools/domains/fs/write.ts +++ b/packages/codingcode/src/tools/domains/fs/write.ts @@ -1,14 +1,20 @@ import { z } from 'zod'; import { writeFile, mkdir } from 'fs/promises'; -import { dirname, relative, resolve } from 'path'; +import { dirname, relative } from 'path'; import { Effect } from 'effect'; import { AgentError } from '../../../util/error.js'; import type { ToolDefinition } from '../../types.js'; +import { resolveFileTarget } from '../../../sandbox/file-boundary.js'; export const writeFileTool: ToolDefinition = { name: 'write_file', concurrencySafe: false, - mutatesWorkspace: true, + approval: { action: 'file', requiresConfirmation: true }, + describeOperation: (args) => ({ + action: 'file', + requiresConfirmation: true, + workspace: { paths: [String((args as { path?: unknown }).path ?? '')], write: true }, + }), description: 'Write content to a file, creating parent directories if needed. Overwrites existing files.', parameters: z.object({ @@ -18,8 +24,17 @@ export const writeFileTool: ToolDefinition = { execute: (args, ctx) => Effect.gen(function* () { const { path, content } = args as any; - const base = ctx?.projectPath ?? process.cwd(); - const filePath = resolve(base, path); + if (!ctx?.projectPath || !ctx.sandboxPolicy) { + return yield* Effect.fail( + new AgentError('SANDBOX_PATH_DENIED', 'write_file requires a sandbox project path') + ); + } + const base = ctx.projectPath; + const filePath = yield* Effect.tryPromise({ + try: () => resolveFileTarget(ctx.sandboxPolicy!, path, 'write'), + catch: (error) => + error instanceof AgentError ? error : AgentError.toolExecutionFailed('write_file', error), + }); yield* Effect.tryPromise({ try: () => mkdir(dirname(filePath), { recursive: true }), catch: (e) => AgentError.toolExecutionFailed('write_file', e), diff --git a/packages/codingcode/src/tools/domains/subagent/message.ts b/packages/codingcode/src/tools/domains/subagent/message.ts index bef3ae9e..5de3e0b5 100644 --- a/packages/codingcode/src/tools/domains/subagent/message.ts +++ b/packages/codingcode/src/tools/domains/subagent/message.ts @@ -26,7 +26,12 @@ export const sendMessageTool: ToolDefinition = const mailbox = yield* MailboxService; const session = yield* SessionService; const { sessionId, message } = args as { sessionId: string; message: string }; - const projectPath = ctx?.projectPath || process.cwd(); + if (!ctx?.projectPath || !ctx.sandboxPolicy) { + return yield* Effect.fail( + new AgentError('SANDBOX_POLICY_DENIED', 'send_message requires a sandbox policy') + ); + } + const projectPath = ctx.projectPath; const selfSessionId = ctx?.sessionId; if (!selfSessionId) { diff --git a/packages/codingcode/src/tools/domains/subagent/resume.ts b/packages/codingcode/src/tools/domains/subagent/resume.ts index 1153ecd4..e3913fa0 100644 --- a/packages/codingcode/src/tools/domains/subagent/resume.ts +++ b/packages/codingcode/src/tools/domains/subagent/resume.ts @@ -11,8 +11,8 @@ import { SubagentRunRegistryService } from '../../../subagent/registry.js'; export const resumeAgentTool: ToolDefinition = { name: 'resume_agent', concurrencySafe: true, + approval: { action: 'subagent', requiresConfirmation: true }, // 续跑的子代理共享工作区并异步写入,父回合须有快照兜底 - mutatesWorkspace: true, description: 'Continue a previously spawned subagent by session id. The subagent keeps its full prior ' + 'context. Use this after interrupt_agent, or to hand a finished subagent a follow-up task ' + @@ -34,13 +34,18 @@ export const resumeAgentTool: ToolDefinition = { name: 'spawn_agent', concurrencySafe: true, + approval: { action: 'subagent', requiresConfirmation: true }, // 子代理共享工作区并异步写入,父回合须有快照兜底 - mutatesWorkspace: true, description: 'Start a subagent and return its session id immediately. The subagent runs in the same working directory ' + 'and shares your file system: keep the delegated write set disjoint from your own. Its result is appended ' + @@ -51,11 +51,16 @@ export const spawnAgentTool: ToolDefinition re.test(content); - const missing: string[] = []; - if (!has(/^#{1,3}\s*(Verification|验证)/im)) missing.push('Verification'); - if (!has(/^#{1,3}\s*(Out of scope|不在范围内|范围外)/im)) missing.push('Out of scope'); - if (missing.length > 0) { - logger.warn( - `submit_plan: plan is missing recommended section(s): ${missing.join(', ')}. ` + - `See PLAN_PROFILE.systemPrompt for the required format.` - ); - } -} - -export const submitPlanTool: ToolDefinition = { - name: 'submit_plan', - concurrencySafe: false, - description: - 'Submit (or update) the implementation plan for the current session. The only write operation allowed in the plan profile. The file is written immediately and the tool returns synchronously; the user is then shown a plan approval modal in the UI. The user’s next message will contain their decision (implement / revised content / cancel).', - parameters: z.object({ - title: z - .string() - .min(1) - .max(80) - .describe( - 'Short, human-readable title (max 80 chars). Becomes the filename. Must be in English. State the outcome, e.g. "Add OAuth login flow".' - ), - plan_content: z - .string() - .min(1) - .describe( - 'Full Markdown implementation plan. Must contain the sections: Goal, Current state, Out of scope, Approach, Key files, Dependencies and risks, Verification. Phases is optional.' - ), - }), - execute: (args, ctx) => - Effect.gen(function* () { - const { title, plan_content: rawContent } = args as { - title: string; - plan_content: string; - }; - const projectPath = ctx?.projectPath; - const sessionId = ctx?.sessionId; - if (!projectPath || !sessionId) { - return yield* Effect.fail( - new AgentError( - 'TOOL_EXECUTION_FAILED', - 'submit_plan requires projectPath, sessionId in tool context' - ) - ); - } - - warnMissingSections(rawContent); - const initialContent = ensureH1(rawContent, title); - const planDir = projectDataDir(projectPath); - const initialPath = join(planDir, `${slug(title)}.md`); - - mkdirSync(planDir, { recursive: true }); - writeFileSync(initialPath, initialContent, 'utf8'); - - return `Plan written to ${initialPath}`; - }) as Effect.Effect, -}; diff --git a/packages/codingcode/src/tools/domains/web/fetch.ts b/packages/codingcode/src/tools/domains/web/fetch.ts index 62633f5a..e8f8fcc3 100644 --- a/packages/codingcode/src/tools/domains/web/fetch.ts +++ b/packages/codingcode/src/tools/domains/web/fetch.ts @@ -2,10 +2,21 @@ import { z } from 'zod'; import { Effect } from 'effect'; import { AgentError } from '../../../util/error.js'; import type { ToolDefinition } from '../../types.js'; +import { assertNetworkTarget } from '../../../sandbox/network.js'; export const webFetchTool: ToolDefinition = { name: 'fetch_url', concurrencySafe: true, + approval: { action: 'network', requiresConfirmation: true }, + describeOperation: (args) => { + const url = typeof (args as { url?: unknown }).url === 'string' ? (args as { url: string }).url : ''; + try { + const parsed = new URL(url); + return { action: 'network', requiresConfirmation: true, network: { hosts: [parsed.hostname], ports: [parsed.port ? Number(parsed.port) : parsed.protocol === 'https:' ? 443 : 80] } }; + } catch { + return { action: 'network', requiresConfirmation: true, dangerous: ['network_unrestricted'] }; + } + }, description: 'Fetch content from a URL and return its text. Supports GET requests only.', parameters: z.object({ url: z.string().url().describe('The URL to fetch (must be a valid absolute URL)'), @@ -17,9 +28,19 @@ export const webFetchTool: ToolDefinition = { .default(100_000) .describe('Maximum characters to return (default 100k, max 500k)'), }), - execute: (args) => + execute: (args, ctx) => Effect.gen(function* () { const { url, max_length } = args as any; + if (!ctx?.sandboxPolicy) { + return yield* Effect.fail( + new AgentError('SANDBOX_NETWORK_DENIED', 'fetch_url requires a sandbox policy') + ); + } + yield* Effect.try({ + try: () => assertNetworkTarget(ctx.sandboxPolicy!, url), + catch: (e) => + e instanceof AgentError ? e : AgentError.toolExecutionFailed('fetch_url', e), + }); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 15_000); @@ -37,6 +58,12 @@ export const webFetchTool: ToolDefinition = { catch: (e) => AgentError.toolExecutionFailed('fetch_url', e), }); + yield* Effect.try({ + try: () => assertNetworkTarget(ctx.sandboxPolicy!, response.url), + catch: (e) => + e instanceof AgentError ? e : AgentError.toolExecutionFailed('fetch_url', e), + }); + if (!response.ok) { return `HTTP ${response.status} ${response.statusText}: Failed to fetch ${url}`; } @@ -62,9 +89,11 @@ export const webFetchTool: ToolDefinition = { ].join('\n'); }).pipe( Effect.catchAll((e: AgentError) => - Effect.succeed( - `Error fetching ${url}: ${e.cause instanceof Error ? e.cause.message : String(e.cause ?? e.message)}` - ) + e.code.startsWith('SANDBOX_') + ? Effect.fail(e) + : Effect.succeed( + `Error fetching ${url}: ${e.cause instanceof Error ? e.cause.message : String(e.cause ?? e.message)}` + ) ) ); diff --git a/packages/codingcode/src/tools/domains/web/search.ts b/packages/codingcode/src/tools/domains/web/search.ts index 4665f66b..bf960d99 100644 --- a/packages/codingcode/src/tools/domains/web/search.ts +++ b/packages/codingcode/src/tools/domains/web/search.ts @@ -2,6 +2,7 @@ import { z } from 'zod'; import { Effect } from 'effect'; import { AgentError } from '../../../util/error.js'; import type { ToolDefinition } from '../../types.js'; +import { assertNetworkTarget } from '../../../sandbox/network.js'; interface SearchResult { title: string; @@ -145,6 +146,7 @@ export function parseBaiduHtml(html: string, maxResults: number): SearchResult[] export const webSearchTool: ToolDefinition = { name: 'web_search', concurrencySafe: true, + approval: { action: 'network', requiresConfirmation: true, network: { hosts: ['cn.bing.com', 'www.baidu.com'], ports: [80, 443] } }, description: 'Search the web and return results with titles, URLs, and snippets. Use this when you need up-to-date information or to find documentation, references, or answers beyond your knowledge cutoff.', parameters: z.object({ @@ -157,9 +159,22 @@ export const webSearchTool: ToolDefinition = { .default(8) .describe('Maximum number of results to return'), }), - execute: (args) => + execute: (args, ctx) => Effect.gen(function* () { const { query, max_results } = args as { query: string; max_results: number }; + if (!ctx?.sandboxPolicy) { + return yield* Effect.fail( + new AgentError('SANDBOX_NETWORK_DENIED', 'web_search requires a sandbox policy') + ); + } + yield* Effect.try({ + try: () => { + assertNetworkTarget(ctx.sandboxPolicy!, 'https://cn.bing.com/'); + assertNetworkTarget(ctx.sandboxPolicy!, 'https://www.baidu.com/'); + }, + catch: (e) => + e instanceof AgentError ? e : AgentError.toolExecutionFailed('web_search', e), + }); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 15_000); diff --git a/packages/codingcode/src/tools/port.ts b/packages/codingcode/src/tools/port.ts index dbf6e621..9daebaed 100644 --- a/packages/codingcode/src/tools/port.ts +++ b/packages/codingcode/src/tools/port.ts @@ -1,19 +1,37 @@ import { Context } from 'effect'; import type { Effect } from 'effect'; +import type { AgentError } from '../util/error.js'; import type { McpToolSpec } from '../mcp/types.js'; import type { ToolCall } from '../llm/types.js'; -import type { ToolCatalog, ToolExecOpts, ToolLookup, ToolResult } from './types.js'; +import type { + ParsedToolCall, + PreparedToolBatch, + PreparedToolCall, + ToolCatalog, + ToolExecOpts, + ToolLookup, + ToolResult, +} from './types.js'; export interface ToolExecutorShape { - /** 按工具名 + 调用方提供的 MCP 工具装配出本轮可用的工具集 */ - prepare(toolNames: readonly string[], mcpTools?: McpToolSpec[]): Effect.Effect; + /** 装配完整的内置工具集,并合并调用方提供的 MCP 工具 */ + prepare(mcpTools?: McpToolSpec[]): Effect.Effect; - executeBatch( - toolCalls: ToolCall[], + parseCall(toolCall: ToolCall, toolLookup: ToolLookup): Effect.Effect; + + prepareBatch( + toolCalls: readonly ToolCall[], sessionId: string | undefined, opts: ToolExecOpts, toolLookup: ToolLookup - ): Effect.Effect; + ): Effect.Effect; + + executeBatch( + toolCalls: readonly (PreparedToolCall | ToolCall)[], + sessionId: string | undefined, + opts: ToolExecOpts, + toolLookup?: ToolLookup + ): Effect.Effect; } export class ToolExecutorService extends Context.Tag('ToolExecutor')< diff --git a/packages/codingcode/src/tools/tools.ts b/packages/codingcode/src/tools/tools.ts index b62d0387..53ffa8a5 100644 --- a/packages/codingcode/src/tools/tools.ts +++ b/packages/codingcode/src/tools/tools.ts @@ -1,61 +1,163 @@ import { Layer, Effect } from 'effect'; +import { createHash } from 'node:crypto'; import { AgentError } from '../util/error.js'; import { HookService } from '../hooks/port.js'; import type { ToolCall } from '../llm/types.js'; import type { McpToolSpec } from '../mcp/types.js'; import type { + ParsedToolCall, + PreparedToolBatch, + PreparedToolCall, ToolCatalog, ToolExecCall, ToolExecCtx, ToolExecOpts, ToolLookup, ToolResult, - ToolRunner, } from './types.js'; +import { resolveSandboxPolicy } from '../sandbox/policy.js'; +import type { SandboxPolicy } from '../sandbox/types.js'; import { ToolExecutorService } from './port.js'; import { createToolCatalog } from './catalog.js'; -type Lookup = (name: string) => ToolRunner | undefined; - function toToolCtx(opts: ToolExecCall): ToolExecCtx { const { turnId: _turnId, ...ctx } = opts; return ctx; } +function stableSerialize(value: unknown): string { + if (value === null || typeof value !== 'object') return JSON.stringify(value); + if (Array.isArray(value)) return `[${value.map(stableSerialize).join(',')}]`; + return `{${Object.keys(value as Record) + .sort() + .map( + (key) => `${JSON.stringify(key)}:${stableSerialize((value as Record)[key])}` + ) + .join(',')}}`; +} + +function argsHash(value: unknown): string { + return createHash('sha256').update(stableSerialize(value)).digest('hex'); +} + +function compatibilityPolicy(projectPath: string | undefined, sessionId: string | undefined): SandboxPolicy { + if (!projectPath) throw new AgentError('SANDBOX_PATH_DENIED', 'projectPath is required for tool execution'); + return { + mode: 'unrestricted', + workspaceRoot: projectPath, + additionalWritableRoots: [], + network: { mode: 'unrestricted', hosts: [], ports: [] }, + sessionId: sessionId ?? 'compatibility', + enforcement: 'disabled', + fingerprint: 'compatibility', + }; +} + export const ToolExecutorLayer = Layer.effect( ToolExecutorService, Effect.gen(function* () { const hooks = yield* HookService; - function execute( - name: string, - args: unknown, - opts: ToolExecCall, - lookup: Lookup - ): Effect.Effect<{ output: string }, AgentError> { + function parseCall( + toolCall: ToolCall, + toolLookup: ToolLookup + ): Effect.Effect { return Effect.gen(function* () { - const tool = lookup(name); - if (!tool) return yield* Effect.fail(AgentError.toolNotFound(name)); + const runner = toolLookup(toolCall.name); + if (!runner) return yield* Effect.fail(AgentError.toolNotFound(toolCall.name)); + const parsedArgs = yield* Effect.try({ + try: () => runner.parse(toolCall.arguments ?? {}), + catch: (error) => AgentError.toolExecutionFailed(toolCall.name, error), + }); + return { + call: toolCall, + runner, + parsedArgs, + argsHash: argsHash(parsedArgs), + operation: runner.describeOperation(parsedArgs), + }; + }); + } - const finalArgs = args as Record; + function prepareBatch( + toolCalls: readonly ToolCall[], + sessionId: string | undefined, + opts: ToolExecOpts, + toolLookup: ToolLookup + ): Effect.Effect { + return Effect.gen(function* () { + const prepared: PreparedToolCall[] = []; + const denied: ToolResult[] = []; + const escalations: PreparedToolBatch['escalations'] = []; + if (!opts.projectPath) { + return { + prepared, + denied: toolCalls.map((call) => ({ + status: 'denied' as const, + id: call.id, + name: call.name, + reason: 'projectPath is required for sandboxed execution', + })), + escalations, + }; + } + for (const call of toolCalls) { + const parsed = yield* Effect.either(parseCall(call, toolLookup)); + if (parsed._tag === 'Left') { + denied.push({ status: 'denied', id: call.id, name: call.name, reason: parsed.left.message }); + continue; + } + const resolution = resolveSandboxPolicy({ + projectPath: opts.projectPath, + sessionId: sessionId ?? '', + permissionMode: opts.permissionMode ?? 'askBeforeExec', + requestedMode: opts.sandboxMode, + parentPolicy: opts.parentPolicy, + operation: parsed.right.operation, + parsedArgs: parsed.right.parsedArgs, + callId: call.id, + toolName: call.name, + argsHash: parsed.right.argsHash, + }); + if (resolution.kind === 'deny') { + denied.push({ status: 'denied', id: call.id, name: call.name, reason: resolution.reason }); + continue; + } + if (resolution.kind === 'escalation') { + escalations.push({ + prepared: { ...parsed.right, sandboxPolicy: resolution.policy }, + request: resolution.request, + }); + continue; + } + prepared.push({ ...parsed.right, sandboxPolicy: resolution.policy }); + } + return { prepared, denied, escalations }; + }); + } - const callId = opts.callId; + function executePrepared( + prepared: PreparedToolCall, + opts: ToolExecCall + ): Effect.Effect<{ output: string }, AgentError> { + return Effect.gen(function* () { + const { call, runner, parsedArgs } = prepared; + const finalArgs = parsedArgs as Record; yield* hooks.emit('tool.execute.before', { - toolName: name, + toolName: call.name, args: finalArgs, sessionId: opts.sessionId, turnId: opts.turnId, projectPath: opts.projectPath, - callId, + callId: call.id, }); - const parsedArgs = yield* Effect.sync(() => tool.parse(finalArgs)); const start = Date.now(); - - // Execute tool — now returns Effect directly - const ctx = toToolCtx(opts); - - let toolEffect = tool.execute(parsedArgs, ctx); + const ctx: ToolExecCtx = { + ...toToolCtx(opts), + sandboxPolicy: prepared.sandboxPolicy, + }; + let toolEffect = runner.execute(parsedArgs, ctx); if (opts.signal) { if (opts.signal.aborted) { @@ -73,24 +175,22 @@ export const ToolExecutorLayer = Layer.effect( } const result = yield* toolEffect; - yield* hooks.emit('tool.execute.after', { - toolName: name, + toolName: call.name, args: finalArgs, result, durationMs: Date.now() - start, sessionId: opts.sessionId, turnId: opts.turnId, projectPath: opts.projectPath, - callId, + callId: call.id, }); - return { output: result }; }).pipe( Effect.tapError((error) => hooks.emit('tool.execute.error', { - toolName: name, - args: args as Record, + toolName: prepared.call.name, + args: prepared.parsedArgs as Record, error, projectPath: opts.projectPath, }) @@ -98,63 +198,65 @@ export const ToolExecutorLayer = Layer.effect( ); } - function execSingle( - tc: ToolCall, + function executePreparedCall( + prepared: PreparedToolCall, sessionId: string | undefined, - opts: ToolExecOpts, - lookup: Lookup + opts: ToolExecOpts ): Effect.Effect { - return execute(tc.name, tc.arguments ?? {}, { sessionId, callId: tc.id, ...opts }, lookup).pipe( + return executePrepared(prepared, { sessionId, callId: prepared.call.id, ...opts }).pipe( Effect.matchEffect({ - onSuccess: (result: any): Effect.Effect => + onSuccess: (result): Effect.Effect => Effect.succeed({ - status: 'ok' as const, - id: tc.id, - name: tc.name, + status: 'ok', + id: prepared.call.id, + name: prepared.call.name, output: result.output, }), - onFailure: (err): Effect.Effect => { - if (err instanceof AgentError && err.code === 'TOOL_NOT_ALLOWED') { + onFailure: (error): Effect.Effect => { + if ( + error instanceof AgentError && + (error.code === 'TOOL_NOT_ALLOWED' || error.code.startsWith('SANDBOX_')) + ) { return Effect.succeed({ - status: 'denied' as const, - id: tc.id, - name: tc.name, - reason: err.message, + status: 'denied', + id: prepared.call.id, + name: prepared.call.name, + reason: error.message, }); } - const code = err instanceof AgentError ? err.code : 'TOOL_EXECUTION_FAILED'; - const msg = err instanceof AgentError ? err.message : String(err); + const code = error instanceof AgentError ? error.code : 'TOOL_EXECUTION_FAILED'; + const message = error instanceof AgentError ? error.message : String(error); return Effect.succeed({ - status: 'error' as const, - id: tc.id, - name: tc.name, - output: `[Error: ${code}] ${msg}`, + status: 'error', + id: prepared.call.id, + name: prepared.call.name, + output: `[Error: ${code}] ${message}`, }); }, }), Effect.catchAllDefect((defect) => Effect.succeed({ status: 'error' as const, - id: tc.id, - name: tc.name, + id: prepared.call.id, + name: prepared.call.name, output: `[Unexpected] ${String(defect)}`, }) ) ); } - function splitWaves(toolCalls: ToolCall[], lookup: Lookup): ToolCall[][] { - const waves: ToolCall[][] = []; - let current: ToolCall[] | undefined; - for (const tc of toolCalls) { - if (lookup(tc.name)?.concurrencySafe) { + function splitWaves(toolCalls: readonly PreparedToolCall[]): PreparedToolCall[][] { + const waves: PreparedToolCall[][] = []; + let current: PreparedToolCall[] | undefined; + for (const prepared of toolCalls) { + if (prepared.runner.concurrencySafe) { if (!current) { current = []; waves.push(current); } - current.push(tc); + current.push(prepared); } else { - waves.push([tc]); + waves.push([prepared]); current = undefined; } } @@ -162,51 +264,55 @@ export const ToolExecutorLayer = Layer.effect( } function executeBatch( - toolCalls: ToolCall[], + toolCalls: readonly (PreparedToolCall | ToolCall)[], sessionId: string | undefined, opts: ToolExecOpts, - toolLookup: ToolLookup - ): Effect.Effect { - const lookup: Lookup = toolLookup; + toolLookup?: ToolLookup + ): Effect.Effect { return Effect.gen(function* () { - const runTool = (tc: ToolCall): Effect.Effect => + const preparedCalls: PreparedToolCall[] = []; + for (const call of toolCalls) { + if ('runner' in call) { + preparedCalls.push(call); + continue; + } + if (!toolLookup) { + return yield* Effect.fail(AgentError.toolNotFound(call.name)); + } + const parsed = yield* parseCall(call, toolLookup); + preparedCalls.push({ + ...parsed, + sandboxPolicy: compatibilityPolicy(opts.projectPath, sessionId), + }); + } + const runTool = (prepared: PreparedToolCall): Effect.Effect => Effect.suspend(() => opts.signal?.aborted ? Effect.succeed({ - status: 'denied' as const, - id: tc.id, - name: tc.name, + status: 'denied', + id: prepared.call.id, + name: prepared.call.name, reason: 'aborted', }) - : execSingle(tc, sessionId, opts, lookup) + : executePreparedCall(prepared, sessionId, opts) ); const waveResults = yield* Effect.forEach( - splitWaves(toolCalls, lookup), - (wave) => - Effect.gen(function* () { - // 写类工具独占 wave 且 wave 间串行,故此处等价于"首次写之前"且无竞态 - if (opts.onBeforeMutation && wave.some((tc) => lookup(tc.name)?.mutatesWorkspace)) { - yield* opts.onBeforeMutation; - } - return yield* Effect.forEach(wave, runTool, { concurrency: 'unbounded' }); - }), + splitWaves(preparedCalls), + (wave) => Effect.forEach(wave, runTool, { concurrency: 'unbounded' }), { concurrency: 1 } ); const byId = new Map(); - for (const wave of waveResults) for (const r of wave) byId.set(r.id, r); - return toolCalls.map((tc) => byId.get(tc.id)!); + for (const wave of waveResults) for (const result of wave) byId.set(result.id, result); + return preparedCalls.map((prepared) => byId.get(prepared.call.id)!); }); } - function prepare( - toolNames: readonly string[], - mcpTools: McpToolSpec[] = [] - ): Effect.Effect { - return Effect.sync(() => createToolCatalog(toolNames, mcpTools)); + function prepare(mcpTools: McpToolSpec[] = []): Effect.Effect { + return Effect.sync(() => createToolCatalog(mcpTools)); } - return { prepare, executeBatch }; + return { prepare, parseCall, prepareBatch, executeBatch }; }) ); diff --git a/packages/codingcode/src/tools/types.ts b/packages/codingcode/src/tools/types.ts index 668e3c7a..070088d7 100644 --- a/packages/codingcode/src/tools/types.ts +++ b/packages/codingcode/src/tools/types.ts @@ -2,15 +2,40 @@ import { z } from 'zod'; import { Effect } from 'effect'; import type { AgentError } from '../util/error.js'; import type { ToolDescription } from '../llm/types.js'; -import type { ProfileName } from '../util/enums.js'; +import type { PermissionMode } from '../util/enums.js'; import type { ToolOutcome } from '../sink/types.js'; +import type { + DangerousOperation, + SandboxEscalationRequest, + SandboxMode, + SandboxPolicy, +} from '../sandbox/types.js'; + +export type ToolApprovalAction = + | 'file' + | 'exec' + | 'network' + | 'mcp' + | 'subagent' + | 'sandbox' + | 'other'; + +export interface ToolApprovalMetadata { + readonly action: ToolApprovalAction; + readonly requiresConfirmation?: boolean; + readonly dangerous?: readonly DangerousOperation[]; + readonly network?: { readonly hosts: readonly string[]; readonly ports: readonly number[] }; + readonly workspace?: { readonly paths: readonly string[]; readonly write: boolean }; +} export interface ToolDefinition { name: string; /** 是否可与同批其它工具并发;省略即 false(fail-closed) */ concurrencySafe?: boolean; - /** 执行后会改动工作区(写文件 / bash / 派生子代理 / MCP);触发惰性 baseline 快照 */ - mutatesWorkspace?: boolean; + /** 工具固有的审批动作描述,不由工具名推断。 */ + approval?: ToolApprovalMetadata; + /** 解析参数后的动态危险操作描述。 */ + describeOperation?: (args: unknown) => ToolApprovalMetadata; description: string; parameters: z.ZodTypeAny; execute: (args: unknown, ctx?: ToolExecCtx) => Effect.Effect; @@ -28,7 +53,10 @@ export interface ToolExecCtx { /** 本次调用的 tool_call id(由 execSingle 以 tc.id 注入);ask_user 用作等待键 */ callId?: string; projectPath?: string; - activeProfile?: ProfileName; + sandboxPolicy?: SandboxPolicy; + permissionMode?: PermissionMode; + sandboxMode?: SandboxMode; + parentPolicy?: SandboxPolicy; model: string; } @@ -37,7 +65,8 @@ export type ToolResult = { readonly id: string; readonly name: string } & ToolOu export interface ToolRunner { readonly name: string; readonly concurrencySafe: boolean; - readonly mutatesWorkspace: boolean; + readonly approval: ToolApprovalMetadata; + readonly describeOperation: (args: unknown) => ToolApprovalMetadata; parse(args: unknown): unknown; execute(args: unknown, ctx?: ToolExecCtx): Effect.Effect; } @@ -46,7 +75,6 @@ export type ToolLookup = (name: string) => ToolRunner | undefined; export type ToolExecOpts = Omit & { turnId?: number; - onBeforeMutation?: Effect.Effect; }; export type ToolExecCall = ToolExecOpts & { sessionId?: string; callId?: string }; @@ -55,3 +83,26 @@ export interface ToolCatalog { tools: ToolDescription[]; lookup: ToolLookup; } + +export interface ParsedToolCall { + readonly call: import('../llm/types.js').ToolCall; + readonly runner: ToolRunner; + readonly parsedArgs: unknown; + readonly argsHash: string; + readonly operation: ToolApprovalMetadata; +} + +export interface PreparedToolCall extends ParsedToolCall { + readonly sandboxPolicy: SandboxPolicy; +} + +export interface PreparedToolEscalation { + readonly prepared: PreparedToolCall; + readonly request: SandboxEscalationRequest; +} + +export interface PreparedToolBatch { + readonly prepared: PreparedToolCall[]; + readonly denied: ToolResult[]; + readonly escalations: PreparedToolEscalation[]; +} diff --git a/packages/codingcode/src/util/enums.ts b/packages/codingcode/src/util/enums.ts index 567ad8fc..b22e69ac 100644 --- a/packages/codingcode/src/util/enums.ts +++ b/packages/codingcode/src/util/enums.ts @@ -1,17 +1,11 @@ -export const PLAN_PROFILE_NAME = 'plan' as const; -export const BUILD_PROFILE_NAME = 'build' as const; - -export const PROFILE_NAMES = [PLAN_PROFILE_NAME, BUILD_PROFILE_NAME] as const; - -export type ProfileName = (typeof PROFILE_NAMES)[number]; - -export function isPlanProfile(name: string | null | undefined): boolean { - return name === PLAN_PROFILE_NAME; -} - export const ASK_BEFORE_EXEC_PERMISSION_MODE = 'askBeforeExec' as const; export const BYPASS_PERMISSION_MODE = 'bypass' as const; +export const UNRESTRICTED_PERMISSION_MODE = 'unrestricted' as const; -export const PERMISSION_MODES = [ASK_BEFORE_EXEC_PERMISSION_MODE, BYPASS_PERMISSION_MODE] as const; +export const PERMISSION_MODES = [ + ASK_BEFORE_EXEC_PERMISSION_MODE, + BYPASS_PERMISSION_MODE, + UNRESTRICTED_PERMISSION_MODE, +] as const; export type PermissionMode = (typeof PERMISSION_MODES)[number]; diff --git a/packages/codingcode/src/util/error.ts b/packages/codingcode/src/util/error.ts index 04891923..87fe74bd 100644 --- a/packages/codingcode/src/util/error.ts +++ b/packages/codingcode/src/util/error.ts @@ -17,7 +17,11 @@ export type ErrorCode = | 'EMPTY_RESPONSE' | 'SESSION_IO_ERROR' | 'INVALID_INPUT' - | 'TURN_CONFLICT'; + | 'TURN_CONFLICT' + | 'SANDBOX_UNAVAILABLE' + | 'SANDBOX_PATH_DENIED' + | 'SANDBOX_NETWORK_DENIED' + | 'SANDBOX_POLICY_DENIED'; export class AgentError extends Error { readonly _tag = 'AgentError'; diff --git a/packages/codingcode/test/agent/skill-mention-persist.test.ts b/packages/codingcode/test/agent/skill-mention-persist.test.ts index 8188ae3d..8919cd45 100644 --- a/packages/codingcode/test/agent/skill-mention-persist.test.ts +++ b/packages/codingcode/test/agent/skill-mention-persist.test.ts @@ -72,7 +72,7 @@ describe('agent runTurn with an explicit @ skill', () => { { cwd: projectDir, input, - activeProfile: 'build', + permissionMode: 'askBeforeExec', skills: [{ name: SKILL_NAME, path: skillPath }], } diff --git a/packages/codingcode/test/agent/submit-plan-turn-end.test.ts b/packages/codingcode/test/agent/submit-plan-turn-end.test.ts deleted file mode 100644 index f4e460f3..00000000 --- a/packages/codingcode/test/agent/submit-plan-turn-end.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { describe, it, expect, vi } from 'vitest'; -import { Effect } from 'effect'; -import { - makeState, - runAgentTurn, - llmStream, - pText, - pToolCall, - pEnd, - endReason, -} from '../helpers/agent-harness.js'; - -vi.mock('../../src/infra/config.js', () => ({ - loadConfig: () => ({ - maxSteps: 5, - maxStopContinuations: 2, - context: { compactionModel: '' }, - memory: { - enabled: false, - model: '', - maxBytes: 16384, - promptMaxBytes: 8192, - }, - }), -})); - -const mockState = makeState({ sessionId: 'test-session', cwd: '/tmp', title: 'test' }); - -/** LLM 先调用一次 submit_plan,再以纯文本收尾。 */ -function makeSubmitPlanLlm() { - let callCount = 0; - const llm = { - completeStream: vi.fn(() => { - callCount++; - if (callCount === 1) { - return llmStream( - pToolCall('tc-1', 'submit_plan', { - title: 'My Plan', - plan_content: '## Goal\nfix bug', - }), - pEnd() - ); - } - return llmStream(pText('Plan is ready for your review.'), pEnd()); - }), - modelInfo: { maxTokens: 1000 }, - } as any; - return llm; -} - -function makeOkExecutor() { - return { - prepare: () => Effect.succeed({ tools: [], lookup: () => undefined }), - executeBatch: (calls: any[]) => - Effect.succeed( - calls.map((tc: any) => ({ - status: 'ok' as const, - id: tc.id, - name: tc.name, - output: 'Plan written to /tmp/plans/my-plan.md', - })) - ), - } as any; -} - -function makeCapturingHooks() { - const emittedPoints: string[] = []; - const hooks = { - emit: vi.fn((point: string, _payload: any) => { - emittedPoints.push(point); - return Effect.succeed(undefined); - }), - emitDecision: vi.fn(() => Effect.succeed(null)), - } as any; - return { hooks, emittedPoints }; -} - -describe('agent treats submit_plan as an ordinary tool', () => { - it('runs submit_plan and ends the turn without any plan-specific hook events', async () => { - const { hooks, emittedPoints } = makeCapturingHooks(); - const { events } = await runAgentTurn( - { llm: makeSubmitPlanLlm(), state: mockState, hooks, executor: makeOkExecutor() }, - { sessionId: 'test-session', cwd: '/tmp' } - ); - - expect(endReason(events)).toBe('done'); - // plan.ready hook point has been removed — the agent no longer announces submit_plan. - expect(emittedPoints.includes('plan.ready')).toBe(false); - expect(emittedPoints.filter((p) => p.startsWith('plan.'))).toHaveLength(0); - }); - - it('does NOT switch profile after submit_plan (profile change is UI responsibility)', async () => { - const setActiveProfile = vi.fn(() => Effect.void); - const { hooks } = makeCapturingHooks(); - - const { events } = await runAgentTurn( - { - llm: makeSubmitPlanLlm(), - state: mockState, - hooks, - executor: makeOkExecutor(), - session: { setActiveProfile }, - }, - { sessionId: 'test-session', cwd: '/tmp' } - ); - - expect(endReason(events)).toBe('done'); - expect(setActiveProfile).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/codingcode/test/approval/pipeline.test.ts b/packages/codingcode/test/approval/pipeline.test.ts deleted file mode 100644 index 1dfc0b92..00000000 --- a/packages/codingcode/test/approval/pipeline.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { Effect, Layer } from 'effect'; -import { runPipeline } from '../../src/approval/approval.js'; -import { createRuleEngine } from '../../src/approval/rule-engine.js'; -import type { PermissionRule } from '../../src/approval/types.js'; -import { ApprovalWaitService } from '../../src/approval/wait-port.js'; -import { EventSinkService } from '../../src/sink/port.js'; -import { HookService } from '../../src/hooks/port.js'; - -const mockHookService = { - emit: () => Effect.succeed(undefined), - emitDecision: () => Effect.succeed(null), - reloadUserHooks: () => Effect.succeed(undefined), -}; - -const mockApprovalWaitService = { - waitForConfirm: () => Effect.succeed({ type: 'deny' } as const), - resolveConfirm: () => Effect.succeed(false), - cancelPendingFor: () => Effect.succeed(0), -}; - -const mockEventSink = { - attach: () => Effect.succeed({} as any), - detach: () => Effect.void, - emit: () => Effect.void, -}; - -const HookTestLayer = Layer.succeed(HookService, mockHookService as any); -const WaitTestLayer = Layer.succeed(ApprovalWaitService, mockApprovalWaitService); -const SinkTestLayer = Layer.succeed(EventSinkService, mockEventSink as any); -const TestLayer = Layer.mergeAll(HookTestLayer, WaitTestLayer, SinkTestLayer); - -type PipelineEnv = HookService | ApprovalWaitService | EventSinkService; - -function runWithLayer(eff: Effect.Effect): Promise { - return Effect.runPromise(Effect.provide(eff, TestLayer)); -} - -describe('Approval Pipeline — PermissionMode auto-allow', () => { - it('Rule Engine deny short-circuits regardless of mode', async () => { - const rules: PermissionRule[] = [ - { id: 'deny', action: 'deny', toolPattern: '*', argPattern: 'rm -rf *', reason: 'Blocked' }, - ]; - const decision = await runWithLayer( - runPipeline( - { tool: 'Bash', input: { command: 'rm -rf /var' } }, - { - ruleEngine: createRuleEngine(rules), - destructiveTools: new Set(), - permissionMode: 'askBeforeExec', - sessionId: 'test', - } - ) - ); - expect((decision as any).type).toBe('deny'); - expect((decision as any).source).toContain('rule:'); - }); - - it('askBeforeExec allows non-destructive tools without user confirmation', async () => { - const decision = await runWithLayer( - runPipeline( - { tool: 'read_file', input: { path: '/safe/file.txt' } }, - { - ruleEngine: createRuleEngine(), - destructiveTools: new Set(['execute_command']), - permissionMode: 'askBeforeExec', - sessionId: 'test', - } - ) - ); - expect((decision as any).type).toBe('allow'); - expect((decision as any).source).toBe('permission-mode'); - }); - - it('askBeforeExec routes execute_command to user confirmation', async () => { - const decision = await runWithLayer( - runPipeline( - { tool: 'execute_command', input: { command: 'ls' } }, - { - ruleEngine: createRuleEngine(), - destructiveTools: new Set(['execute_command']), - permissionMode: 'askBeforeExec', - sessionId: 'test', - } - ) - ); - expect((decision as any).type).toBe('deny'); - expect((decision as any).source).toBe('user-confirm'); - }); - - it('bypass allows even destructive tools without confirmation', async () => { - const decision = await runWithLayer( - runPipeline( - { tool: 'execute_command', input: { command: 'ls' } }, - { - ruleEngine: createRuleEngine(), - destructiveTools: new Set(['execute_command']), - permissionMode: 'bypass', - sessionId: 'test', - } - ) - ); - expect((decision as any).type).toBe('allow'); - expect((decision as any).source).toBe('permission-mode'); - }); -}); diff --git a/packages/codingcode/test/approval/response.test.ts b/packages/codingcode/test/approval/response.test.ts index 49c9e8c9..5d0cb808 100644 --- a/packages/codingcode/test/approval/response.test.ts +++ b/packages/codingcode/test/approval/response.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest'; +import { describe, expect, it } from 'vitest'; import { parseApprovalResponse } from '../../src/approval/confirmation.js'; describe('parseApprovalResponse', () => { @@ -8,31 +8,8 @@ describe('parseApprovalResponse', () => { expect(parseApprovalResponse('unknown')).toEqual({ type: 'deny' }); }); - it('creates persistent allow and deny rules', () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date('2026-05-20T12:00:00Z')); - - expect(parseApprovalResponse('always')).toEqual({ - type: 'always', - rule: { - id: 'user-allow-1779278400000', - action: 'allow', - toolPattern: '*', - reason: 'User always allows', - source: 'user', - }, - }); - expect(parseApprovalResponse('never')).toEqual({ - type: 'never', - rule: { - id: 'user-deny-1779278400000', - action: 'deny', - toolPattern: '*', - reason: 'User never allows', - source: 'user', - }, - }); - - vi.useRealTimers(); + it('fails closed for responses outside the current contract', () => { + expect(parseApprovalResponse('always')).toEqual({ type: 'deny' }); + expect(parseApprovalResponse('never')).toEqual({ type: 'deny' }); }); }); diff --git a/packages/codingcode/test/context/budget-integration.test.ts b/packages/codingcode/test/context/budget-integration.test.ts index 3dc6d2b1..c38fb3fb 100644 --- a/packages/codingcode/test/context/budget-integration.test.ts +++ b/packages/codingcode/test/context/budget-integration.test.ts @@ -54,7 +54,6 @@ describe('getHistory integration', () => { createdAt: new Date().toISOString(), model: 'test-model', title: 'fixture', - activeProfile: 'build', permissionMode: 'askBeforeExec', }, { type: 'user', turnId: 1, content: [{ type: 'text', text: 'q1' }] }, diff --git a/packages/codingcode/test/context/compressor/behavior.test.ts b/packages/codingcode/test/context/compressor/behavior.test.ts index 2a00fb78..4fed9175 100644 --- a/packages/codingcode/test/context/compressor/behavior.test.ts +++ b/packages/codingcode/test/context/compressor/behavior.test.ts @@ -52,7 +52,7 @@ function makeFixture(opts: FixtureOptions) { createdAt: new Date().toISOString(), model: 'test-model', title: 'fixture', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, ]; diff --git a/packages/codingcode/test/context/get-history-media.test.ts b/packages/codingcode/test/context/get-history-media.test.ts index c4f91ccd..ff174c7d 100644 --- a/packages/codingcode/test/context/get-history-media.test.ts +++ b/packages/codingcode/test/context/get-history-media.test.ts @@ -54,7 +54,7 @@ function writeTranscript(ref: SessionRef, asset: string, onDisk: boolean): strin createdAt: new Date().toISOString(), model: 'test-model', title: 'media-fixture', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { diff --git a/packages/codingcode/test/context/memory-buffer.test.ts b/packages/codingcode/test/context/memory-buffer.test.ts index 9e5f9139..5d5d34d3 100644 --- a/packages/codingcode/test/context/memory-buffer.test.ts +++ b/packages/codingcode/test/context/memory-buffer.test.ts @@ -76,7 +76,7 @@ function seedEvents(): SessionEvent[] { createdAt: new Date().toISOString(), model: 'test-model', title: 't', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { type: 'user', turnId: 1, content: text('q1') }, diff --git a/packages/codingcode/test/helpers/agent-harness.ts b/packages/codingcode/test/helpers/agent-harness.ts index 2cf1e173..15e891c7 100644 --- a/packages/codingcode/test/helpers/agent-harness.ts +++ b/packages/codingcode/test/helpers/agent-harness.ts @@ -138,6 +138,12 @@ export interface HarnessMocks { }; executor?: { executeBatch: (calls: any[], sessionId?: string, opts?: any) => Effect.Effect; + prepareBatch?: ( + calls: readonly any[], + sessionId: string | undefined, + opts: any, + lookup: any + ) => Effect.Effect; }; todo?: Map>; memorySnapshot?: string; @@ -172,7 +178,7 @@ export function makeState(partial: Partial = {}): SessionStor createdAt: new Date().toISOString(), model: 'test-model', title: 'test', - activeProfile: 'build', + permissionMode: 'askBeforeExec', currentTurnId: 1, memorySnapshot: '', @@ -209,7 +215,6 @@ export interface RunAgentOptions { sessionId?: string; cwd?: string; signal?: AbortSignal; - activeProfile?: 'plan' | 'build'; permissionMode?: string; model?: string; /** 随请求下发的显式 @ skill;缺省时 agent 不应产生任何 skill 提示块。 */ @@ -234,14 +239,56 @@ export function makeAgentLayer(mocks: HarnessMocks): Layer.Layer { output: '', })) )); + const testSandboxPolicy = (projectPath: string, sessionId: string) => ({ + mode: 'unrestricted' as const, + workspaceRoot: projectPath, + additionalWritableRoots: [], + network: { mode: 'unrestricted' as const, hosts: [], ports: [] }, + sessionId, + enforcement: 'disabled' as const, + fingerprint: 'test', + }); const executor = { - prepare: (names: readonly string[], mcpTools: any[] = []) => + prepare: (mcpTools: any[] = []) => Effect.sync(() => { - const { tools, lookup } = createToolCatalog(names, mcpTools); + const { tools, lookup } = createToolCatalog(mcpTools); return { tools, lookup }; }), + prepareBatch: + mocks.executor?.prepareBatch ?? + ((calls: readonly any[], sessionId: string | undefined, opts: any, lookup: any) => + Effect.sync(() => { + const prepared: any[] = []; + for (const call of calls) { + const runner = lookup(call.name) ?? { + name: call.name, + concurrencySafe: true, + approval: { action: 'other' }, + describeOperation: () => ({ action: 'other' }), + parse: (args: unknown) => args ?? {}, + }; + const parsedArgs = runner.parse(call.arguments ?? {}); + prepared.push({ + call, + runner, + parsedArgs, + argsHash: 'test', + operation: runner.describeOperation(parsedArgs), + sandboxPolicy: testSandboxPolicy(opts.projectPath, sessionId ?? 'test'), + }); + } + return { prepared, denied: [], escalations: [] }; + })), executeBatch: (calls: any[], sessionId?: string, opts?: any) => - batch(calls, sessionId, opts), + batch( + calls.map((call) => + 'call' in call + ? { ...call.call, arguments: call.parsedArgs } + : call + ), + sessionId, + opts + ), } as any; const session: Record = { @@ -250,7 +297,7 @@ export function makeAgentLayer(mocks: HarnessMocks): Layer.Layer { Effect.succeed({ ...state, sessionId: opts.sessionId ?? 'created-sid', - activeProfile: opts.activeProfile ?? 'build', + }), materializeInput: (_state: any, input: any[]) => Effect.succeed( @@ -330,9 +377,15 @@ export function makeAgentLayer(mocks: HarnessMocks): Layer.Layer { Layer.succeed(ToolExecutorService, executor as any), Layer.succeed(CheckpointService, { snapshotBeforeWrite: () => Effect.void, + ensureBaseline: () => Effect.void, } as any), Layer.succeed(ApprovalService, { evaluate: () => Effect.succeed({ type: 'allow', source: 'test' }), + evaluateBatch: (requests: readonly unknown[]) => + Effect.succeed(requests.map(() => ({ type: 'allow' as const, source: 'test' }))), + evaluateEscalation: () => Effect.succeed({ type: 'allow', source: 'test' }), + evaluateEscalationBatch: (requests: readonly unknown[]) => + Effect.succeed(requests.map(() => ({ type: 'allow' as const, source: 'test' }))), } as any), mocks.skillLayer ?? Layer.succeed(SkillService, skills as any), ContextMockLayer, @@ -406,7 +459,6 @@ export async function runAgentTurn( const runOpts: any = { cwd: opts.cwd ?? '/tmp', model: opts.model ?? 'test-model' }; if (opts.sessionId) runOpts.sessionId = opts.sessionId; if (opts.signal) runOpts.signal = opts.signal; - if (opts.activeProfile) runOpts.activeProfile = opts.activeProfile; if (opts.permissionMode) runOpts.permissionMode = opts.permissionMode; if (opts.skills) runOpts.skills = opts.skills; return yield* agent.runTurn(opts.input ?? incomingText('test'), runOpts); diff --git a/packages/codingcode/test/helpers/sandbox.ts b/packages/codingcode/test/helpers/sandbox.ts new file mode 100644 index 00000000..fb05b870 --- /dev/null +++ b/packages/codingcode/test/helpers/sandbox.ts @@ -0,0 +1,21 @@ +import { resolve } from 'node:path'; +import type { SandboxMode, SandboxPolicy } from '../../src/sandbox/types.js'; + +export function testSandboxPolicy( + workspaceRoot: string, + mode: SandboxMode = 'unrestricted' +): SandboxPolicy { + return { + mode, + workspaceRoot: resolve(workspaceRoot), + additionalWritableRoots: [], + network: { + mode: mode === 'read-only' || mode === 'workspace-write' ? 'none' : 'unrestricted', + hosts: [], + ports: [], + }, + sessionId: 'test-session', + enforcement: mode === 'read-only' || mode === 'workspace-write' ? 'required' : 'disabled', + fingerprint: 'test', + }; +} diff --git a/packages/codingcode/test/plan/allowed-tools.test.ts b/packages/codingcode/test/plan/allowed-tools.test.ts deleted file mode 100644 index a386173c..00000000 --- a/packages/codingcode/test/plan/allowed-tools.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { - BUILD_TOOL_NAMES, - PLAN_TOOL_NAMES, - getToolNames, -} from '../../src/approval/tool-policy.js'; - -describe('getToolNames (profile tool name list)', () => { - it('plan profile includes submit_plan and excludes write tools', () => { - const names = getToolNames('plan'); - expect(names).toContain('submit_plan'); - expect(names).toContain('read_file'); - expect(names).not.toContain('write_file'); - expect(names).not.toContain('execute_command'); - }); - - it('build profile includes write tools and excludes submit_plan', () => { - const names = getToolNames('build'); - expect(names).toContain('write_file'); - expect(names).toContain('execute_command'); - expect(names).not.toContain('submit_plan'); - }); - - it('undefined profile falls back to the build tool list', () => { - expect(getToolNames(undefined)).toEqual(BUILD_TOOL_NAMES); - }); - - it('plan and build lists differ on the write/submit_plan axis', () => { - expect(PLAN_TOOL_NAMES).not.toContain('write_file'); - expect(BUILD_TOOL_NAMES).not.toContain('submit_plan'); - }); -}); diff --git a/packages/codingcode/test/plan/gate-pipeline.test.ts b/packages/codingcode/test/plan/gate-pipeline.test.ts deleted file mode 100644 index 6657a702..00000000 --- a/packages/codingcode/test/plan/gate-pipeline.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { Effect, Layer } from 'effect'; -import { mkdtempSync, rmSync } from 'fs'; -import { tmpdir } from 'os'; -import { join } from 'path'; -import { runPipeline } from '../../src/approval/approval.js'; -import { createRuleEngine } from '../../src/approval/rule-engine.js'; -import { HookService } from '../../src/hooks/port.js'; -import { ApprovalWaitService } from '../../src/approval/wait-port.js'; -import { EventSinkService } from '../../src/sink/port.js'; -import type { ProfileName } from '../../src/util/enums.js'; -import { useTempProjectBase } from '../helpers/project-base.js'; - -useTempProjectBase(); - -const mockHookService = { - emit: () => Effect.succeed(undefined), - emitDecision: () => Effect.succeed(null), - reloadUserHooks: () => Effect.succeed(undefined), -}; - -let capturedApproval: any = null; - -function makeMockApprovalWait() { - return { - waitForConfirm: () => Effect.succeed({ type: 'deny' }) as any, - resolveConfirm: () => Effect.succeed(false), - cancelPendingFor: () => Effect.succeed(0), - }; -} - -// 审批请求现在经 EventSink 出站,捕获点从 wait 的 emitter 迁到 sink.emit -function makeMockEventSink() { - return { - attach: () => Effect.succeed({} as any), - detach: () => Effect.void, - emit: (sessionId: string, body: any) => - Effect.sync(() => { - if (body?.family === 'event' && body.event?.type === 'approval_request') { - capturedApproval = { - sessionId, - id: body.event.id, - tool: body.event.tool, - args: body.event.args, - }; - } - }), - }; -} - -function runPipelineWithMock(opts: { - tool: string; - input: any; - permissionMode: 'askBeforeExec' | 'bypass'; - sessionId: string; - profile: ProfileName; -}) { - capturedApproval = null; - - const mockWait = makeMockApprovalWait(); - const HookTestLayer = Layer.succeed(HookService, mockHookService as any); - const WaitTestLayer = Layer.succeed(ApprovalWaitService, mockWait as any); - const SinkTestLayer = Layer.succeed(EventSinkService, makeMockEventSink() as any); - const TestLayer = Layer.mergeAll(HookTestLayer, WaitTestLayer, SinkTestLayer); - return Effect.runPromise( - runPipeline( - { tool: opts.tool, input: opts.input }, - { - ruleEngine: createRuleEngine([]), - destructiveTools: new Set(['execute_command']), - permissionMode: opts.permissionMode, - profile: opts.profile, - sessionId: opts.sessionId, - } - ).pipe(Effect.provide(TestLayer) as any) - ); -} - -describe('plan profile permission mode (Layer 2)', () => { - let cwd: string; - beforeEach(() => { - cwd = mkdtempSync(join(tmpdir(), 'codingcode-gate-pipeline-')); - capturedApproval = null; - }); - afterEach(() => { - rmSync(cwd, { recursive: true, force: true }); - }); - - it('plan profile + write_file: denied before reaching user confirmation', async () => { - const decision: any = await runPipelineWithMock({ - tool: 'write_file', - input: { path: '/tmp/x', content: 'foo' }, - permissionMode: 'askBeforeExec', - sessionId: 's2', - profile: 'plan', - }); - expect(decision.type).toBe('deny'); - expect(decision.source).toBe('permission-mode'); - expect(decision.reason).toMatch(/plan profile/i); - expect(capturedApproval).toBeNull(); - }); - - it('plan profile + execute_command: denied with plan-profile reason', async () => { - const decision: any = await runPipelineWithMock({ - tool: 'execute_command', - input: { command: 'rm -rf /' }, - permissionMode: 'askBeforeExec', - sessionId: 's3', - profile: 'plan', - }); - expect(decision.type).toBe('deny'); - expect(decision.source).toBe('permission-mode'); - expect(decision.reason).toMatch(/plan profile/i); - expect(capturedApproval).toBeNull(); - }); - - it('plan profile + spawn_agent: denied by plan mode', async () => { - const decision: any = await runPipelineWithMock({ - tool: 'spawn_agent', - input: { agentName: 'build', prompt: 'do something' }, - permissionMode: 'askBeforeExec', - sessionId: 's4', - profile: 'plan', - }); - expect(decision.type).toBe('deny'); - expect(decision.source).toBe('permission-mode'); - expect(decision.reason).toMatch(/plan profile/i); - expect(capturedApproval).toBeNull(); - }); - - it('build profile + write_file: auto-allowed, never reaches confirmation', async () => { - const decision: any = await runPipelineWithMock({ - tool: 'write_file', - input: { path: '/tmp/x', content: 'foo' }, - permissionMode: 'askBeforeExec', - sessionId: 's5', - profile: 'build', - }); - expect(decision.type).toBe('allow'); - expect(decision.source).toBe('permission-mode'); - expect(capturedApproval).toBeNull(); - }); - - it('build profile + execute_command: falls through to user confirmation', async () => { - const decision: any = await runPipelineWithMock({ - tool: 'execute_command', - input: { command: 'ls' }, - permissionMode: 'askBeforeExec', - sessionId: 's7', - profile: 'build', - }); - expect(capturedApproval).not.toBeNull(); - expect(decision.source).toBe('user-confirm'); - }); - - it('plan profile + submit_plan: allowed by plan allow-list', async () => { - const decision: any = await runPipelineWithMock({ - tool: 'submit_plan', - input: { plan_content: '# plan' }, - permissionMode: 'askBeforeExec', - sessionId: 's6', - profile: 'plan', - }); - expect(decision.type).toBe('allow'); - expect(decision.source).toBe('permission-mode'); - expect(capturedApproval).toBeNull(); - }); -}); diff --git a/packages/codingcode/test/plan/is-plan-profile.test.ts b/packages/codingcode/test/plan/is-plan-profile.test.ts deleted file mode 100644 index 3e48c77b..00000000 --- a/packages/codingcode/test/plan/is-plan-profile.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { isPlanProfile } from '../../src/util/enums.js'; - -describe('isPlanProfile', () => { - it('returns true for "plan"', () => { - expect(isPlanProfile('plan')).toBe(true); - }); - - it('returns false for "build"', () => { - expect(isPlanProfile('build')).toBe(false); - }); - - it('returns false for an arbitrary profile name', () => { - expect(isPlanProfile('custom')).toBe(false); - }); - - it('returns false for null/undefined', () => { - expect(isPlanProfile(null)).toBe(false); - expect(isPlanProfile(undefined)).toBe(false); - }); -}); diff --git a/packages/codingcode/test/plan/policy.test.ts b/packages/codingcode/test/plan/policy.test.ts deleted file mode 100644 index a2b52b08..00000000 --- a/packages/codingcode/test/plan/policy.test.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { PLAN_ALLOWED_TOOLS } from '../../src/approval/tool-policy.js'; - -describe('PLAN_ALLOWED_TOOLS', () => { - it('does not expose write tools', () => { - expect(PLAN_ALLOWED_TOOLS.has('write_file')).toBe(false); - expect(PLAN_ALLOWED_TOOLS.has('edit_file')).toBe(false); - expect(PLAN_ALLOWED_TOOLS.has('execute_command')).toBe(false); - }); -}); diff --git a/packages/codingcode/test/security/plan-profile-restart.test.ts b/packages/codingcode/test/security/plan-profile-restart.test.ts deleted file mode 100644 index 6bd8bc72..00000000 --- a/packages/codingcode/test/security/plan-profile-restart.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { Effect, Layer, ManagedRuntime } from 'effect'; -import { mkdtempSync, rmSync } from 'fs'; -import { tmpdir } from 'os'; -import { join } from 'path'; -import { SessionService } from '../../src/session/port.js'; -import { SessionLayer } from '../../src/session/session.js'; -import { HookService } from '../../src/hooks/port.js'; -import { ApprovalService } from '../../src/approval/port.js'; -import { ApprovalWaitService } from '../../src/approval/wait-port.js'; -import { EventSinkLayer } from '../../src/sink/sink.js'; -import type { ProfileName } from '../../src/util/enums.js'; -import { useTempProjectBase } from '../helpers/project-base.js'; -import { ApprovalLayer } from '../../src/approval/approval.js'; - -useTempProjectBase(); - -const mockHookService = { - emit: () => Effect.succeed(undefined), - emitDecision: () => Effect.succeed(null), - reloadUserHooks: () => Effect.succeed(undefined), -}; - -const mockApprovalWaitService = { - waitForConfirm: () => Effect.succeed({ type: 'deny' } as const), - resolveConfirm: () => Effect.succeed(false), - cancelPendingFor: () => Effect.succeed(0), -}; - -function makeLayer() { - const HookTestLayer = Layer.succeed(HookService, mockHookService as any); - const ApprovalTestLayer = ApprovalLayer.pipe( - Layer.provide( - Layer.mergeAll( - HookTestLayer, - EventSinkLayer, - Layer.succeed(ApprovalWaitService, mockApprovalWaitService as any) - ) - ) - ); - return Layer.mergeAll( - SessionLayer, - HookTestLayer, - EventSinkLayer, - ApprovalTestLayer, - Layer.succeed(ApprovalWaitService, mockApprovalWaitService as any) - ); -} - -function setProfileEffect(cwd: string, sessionId: string, profile: 'plan' | 'build') { - return Effect.gen(function* () { - const session = yield* SessionService; - yield* session.setActiveProfile(cwd, sessionId, profile); - }); -} - -describe('plan profile security boundary (permission-mode, disk-persisted profile)', () => { - let cwd: string; - let sessionId: string; - let rt: ManagedRuntime.ManagedRuntime; - - beforeEach(async () => { - cwd = mkdtempSync(join(tmpdir(), 'codingcode-security-test-')); - rt = ManagedRuntime.make(makeLayer() as any); - const result = await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - const state = yield* session.create(cwd, { - model: 'test-model', - activeProfile: 'build', - permissionMode: 'askBeforeExec', - }); - return { sessionId: state.sessionId }; - }) - ); - sessionId = result.sessionId; - }); - - afterEach(async () => { - await rt.dispose(); - rmSync(cwd, { recursive: true, force: true }); - }); - - async function evaluateAsProfile(tool: string, input: any, profile: ProfileName): Promise { - return rt.runPromise( - Effect.gen(function* () { - const approval = yield* ApprovalService; - return yield* approval.evaluate({ - tool, - input, - sessionId, - projectPath: cwd, - permissionMode: 'askBeforeExec', - profile, - }); - }) - ); - } - - it('plan profile: write_file is denied by permission-mode', async () => { - const decision = await evaluateAsProfile( - 'write_file', - { path: '/tmp/x', content: 'foo' }, - 'plan' - ); - expect(decision.type).toBe('deny'); - expect(decision.reason).toMatch(/plan profile/i); - expect(decision.source).toBe('permission-mode'); - }); - - it('plan profile: execute_command is denied by permission-mode', async () => { - const decision = await evaluateAsProfile('execute_command', { command: 'echo hello' }, 'plan'); - expect(decision.type).toBe('deny'); - expect(decision.reason).toMatch(/plan profile/i); - expect(decision.source).toBe('permission-mode'); - }); - - it('plan profile: submit_plan is allowed by the plan allow-list', async () => { - const decision: any = await evaluateAsProfile( - 'submit_plan', - { plan_content: 'do things' }, - 'plan' - ); - expect(decision.type).toBe('allow'); - expect(decision.source).toBe('permission-mode'); - }); - - it('after restart (state reloaded from disk), plan profile persists', async () => { - await rt.runPromise(setProfileEffect(cwd, sessionId, 'plan')); - - await rt.dispose(); - rt = ManagedRuntime.make(makeLayer() as any); - await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - const state = yield* session.load(cwd, sessionId); - expect(state.activeProfile).toBe('plan'); - }) - ); - }); - - it('build profile: write_file is not denied by plan permission-mode', async () => { - const decision: any = await evaluateAsProfile( - 'write_file', - { path: '/tmp/x', content: 'foo' }, - 'build' - ); - if (decision.type === 'deny') { - expect(decision.source).not.toBe('permission-mode'); - expect(decision.reason).not.toMatch(/plan profile/i); - } - }); -}); diff --git a/packages/codingcode/test/server/compact-route.test.ts b/packages/codingcode/test/server/compact-route.test.ts index 8cf393c6..559793ee 100644 --- a/packages/codingcode/test/server/compact-route.test.ts +++ b/packages/codingcode/test/server/compact-route.test.ts @@ -23,14 +23,14 @@ const MockSessionLayer = Layer.succeed(SessionService, { Effect.succeed({ sessionId: 'test-sid', cwd: '/tmp/test', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }), load: () => Effect.succeed({ sessionId: 'test-sid', cwd: '/tmp/test', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }), recordUser: () => Effect.succeed({ type: 'user', content: '', turnId: 0 }), diff --git a/packages/codingcode/test/server/create-session-active-profile.test.ts b/packages/codingcode/test/server/create-session-active-profile.test.ts deleted file mode 100644 index b1d8ed46..00000000 --- a/packages/codingcode/test/server/create-session-active-profile.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { Effect, ManagedRuntime } from 'effect'; -import { mkdirSync } from 'fs'; -import { join } from 'path'; -import { SessionService } from '../../src/session/port.js'; -import { SessionLayer } from '../../src/session/session.js'; -import { createServer, type ServerApp } from '../../src/server/index.js'; -import { useTempProjectBase } from '../helpers/project-base.js'; - -const base = useTempProjectBase(); - -describe('POST /api/sessions — atomic mode + permissionMode + model', () => { - let cwd: string; - let rt: ManagedRuntime.ManagedRuntime; - let app: ServerApp; - - beforeEach(async () => { - cwd = join(base.dir, 'create-session-active-profile'); - mkdirSync(cwd, { recursive: true }); - rt = ManagedRuntime.make(SessionLayer as any); - app = await createServer(rt); - }); - - afterEach(async () => { - await rt.dispose(); - }); - - it('persists activeProfile=plan and permissionMode=ask when activeProfile=plan', async () => { - const res = await app.request('/api/sessions', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ - cwd, - activeProfile: 'plan', - permissionMode: 'askBeforeExec', - model: 'gpt-4', - }), - }); - expect(res.status).toBe(200); - const { sessionId } = await res.json(); - - await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - const state = yield* session.load(cwd, sessionId); - expect(state.activeProfile).toBe('plan'); - expect(state).not.toHaveProperty('mode'); - expect(state.permissionMode).toBe('askBeforeExec'); - }) - ); - }); - - it('persists activeProfile=build and permissionMode=bypass when activeProfile=build+bypass', async () => { - const res = await app.request('/api/sessions', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ - cwd, - activeProfile: 'build', - permissionMode: 'bypass', - model: 'gpt-4', - }), - }); - expect(res.status).toBe(200); - const { sessionId } = await res.json(); - - await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - const state = yield* session.load(cwd, sessionId); - expect(state.activeProfile).toBe('build'); - expect(state).not.toHaveProperty('mode'); - expect(state.permissionMode).toBe('bypass'); - }) - ); - }); - - it('allows plan profile with any permissionMode (plan no longer overrides perm)', async () => { - const res = await app.request('/api/sessions', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ - cwd, - activeProfile: 'plan', - permissionMode: 'bypass', - model: 'gpt-4', - }), - }); - expect(res.status).toBe(200); - const { sessionId } = await res.json(); - await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - const state = yield* session.load(cwd, sessionId); - expect(state.activeProfile).toBe('plan'); - expect(state).not.toHaveProperty('mode'); - expect(state.permissionMode).toBe('bypass'); - }) - ); - }); - - it('rejects missing model', async () => { - const res = await app.request('/api/sessions', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ cwd, activeProfile: 'build', permissionMode: 'askBeforeExec' }), - }); - expect(res.status).toBe(400); - }); - - it('rejects missing mode', async () => { - const res = await app.request('/api/sessions', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ cwd, permissionMode: 'askBeforeExec', model: 'gpt-4' }), - }); - expect(res.status).toBe(400); - }); - - it('new session persists activeProfile and permissionMode', async () => { - const res = await app.request('/api/sessions', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ - cwd, - activeProfile: 'plan', - permissionMode: 'askBeforeExec', - model: 'gpt-4', - }), - }); - expect(res.status).toBe(200); - const { sessionId } = await res.json(); - - await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - const state = yield* session.load(cwd, sessionId); - expect(state.activeProfile).toBe('plan'); - expect(state).not.toHaveProperty('mode'); - expect(state.permissionMode).toBe('askBeforeExec'); - expect(state.activeProfile).toBe('plan'); - }) - ); - }); -}); diff --git a/packages/codingcode/test/server/messages-fork-permission-mode.test.ts b/packages/codingcode/test/server/messages-fork-permission-mode.test.ts index b215b82f..cee84ee7 100644 --- a/packages/codingcode/test/server/messages-fork-permission-mode.test.ts +++ b/packages/codingcode/test/server/messages-fork-permission-mode.test.ts @@ -68,7 +68,7 @@ describe('POST /api/sessions/:id/messages — reads permissionMode from disk', ( const session = yield* SessionService; return yield* session.create(cwd, { model: 'm', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) diff --git a/packages/codingcode/test/server/plan-file-route.test.ts b/packages/codingcode/test/server/plan-file-route.test.ts deleted file mode 100644 index 56ec8f37..00000000 --- a/packages/codingcode/test/server/plan-file-route.test.ts +++ /dev/null @@ -1,196 +0,0 @@ -/** - * @vitest-environment node - */ -import { describe, it, expect, beforeEach } from 'vitest'; -import { Effect, Layer, ManagedRuntime } from 'effect'; -import { mkdirSync, writeFileSync, utimesSync } from 'fs'; -import { join, resolve } from 'path'; -import { createServer } from '../../src/server/index.js'; -import { SessionService } from '../../src/session/port.js'; -import { LLMService } from '../../src/llm/port.js'; -import { ApprovalService } from '../../src/approval/port.js'; -import { ApprovalWaitService } from '../../src/approval/wait-port.js'; -import { HookService } from '../../src/hooks/port.js'; -import { SkillService } from '../../src/skills/port.js'; -import { McpService } from '../../src/mcp/port.js'; -import { MemoryService } from '../../src/memory/port.js'; -import { SchedulerService } from '../../src/scheduler/port.js'; -import { ContextService } from '../../src/context/port.js'; -import { CheckpointService } from '../../src/checkpoint/port.js'; -import { encodeProjectPath } from '../../src/util/path.js'; -import { useTempHome } from '../helpers/temp-home.js'; -import { projectBaseDir } from '../helpers/project-base.js'; -import { HookLayer } from '../../src/hooks/hooks.js'; -import { ApprovalWaitLayer } from '../../src/approval/wait.js'; -import { ApprovalLayer } from '../../src/approval/approval.js'; -import { EventSinkLayer } from '../../src/sink/sink.js'; - -const MockSessionLayer = Layer.succeed(SessionService, { - create: () => - Effect.succeed({ - sessionId: 'test-sid', - cwd: '/tmp/test', - model: 'deepseek-chat', - activeProfile: 'build', - permissionMode: 'askBeforeExec', - }), - load: () => - Effect.succeed({ - sessionId: 'test-sid', - cwd: '/tmp/test', - model: 'deepseek-chat', - activeProfile: 'build', - permissionMode: 'askBeforeExec', - }), - recordUser: () => Effect.succeed({ type: 'user', content: '', turnId: 0 }), - recordAssistant: () => - Effect.succeed({ type: 'assistant', content: '', toolCalls: [], turnId: 0 }), - recordToolResult: () => - Effect.succeed({ - type: 'tool_result', - toolName: 'test', - toolCallId: 'tc1', - output: '', - turnId: 0, - }), -} as any); - -const MockLLMLayer = Layer.succeed(LLMService, { - complete: () => Effect.fail(new Error('LLM not available in test')), - completeStream: () => (async function* () {})(), -} as any); - -const MockApprovalLayer = ApprovalLayer.pipe( - Layer.provide(Layer.mergeAll(HookLayer, EventSinkLayer, ApprovalWaitLayer)) -); - -const MockSkillLayer = Layer.succeed(SkillService, { - _tag: 'Skill' as const, - getAll: () => Effect.succeed([]), - readContent: () => Effect.succeed(''), -} as any); - -const MockMcpLayer = Layer.succeed(McpService, { - syncConnections: () => Effect.void, - listProjectMcpTools: () => [], - status: () => Effect.succeed([]), -} as any); - -const MockMemoryLayer = Layer.succeed(MemoryService, { - getMemoryEnabled: () => Effect.succeed(true), - setMemoryEnabled: () => Effect.void, - loadMemoryForPrompt: () => Effect.succeed(''), - flushSessionToMemory: () => Effect.succeed({ written: false, bytes: 0 }), -} as any); - -const MockSchedulerLayer = Layer.succeed(SchedulerService, { - list: () => [], - add: () => ({}), - update: () => null, - remove: () => false, - runOnce: () => Promise.resolve('session-id'), -} as any); - -const MockContextLayer = Layer.succeed(ContextService, { - getHistory: () => Effect.succeed([]), - absorb: () => Effect.void, - compact: () => Effect.succeed({ didCompress: false, released: 0, promptEstimate: 0 }), - dispose: () => Effect.void, -} as any); - -const MockCheckpointLayer = Layer.succeed(CheckpointService, { - _tag: 'Checkpoint' as const, - snapshotBeforeWrite: () => Effect.void, - getCheckpointDiff: () => Effect.succeed({ turnId: 0, files: [] }), - revertCheckpointFiles: () => - Effect.succeed({ - reverted: false, - throughTurnId: 0, - affectedTurns: [], - selectedFiles: [], - }), - previewRollbackDiff: () => Effect.succeed({ throughTurnId: 0, affectedTurns: [], diff: '' }), -} as any); - -const TestLayer = Layer.mergeAll( - MockSessionLayer, - MockLLMLayer, - MockApprovalLayer, - HookLayer, - EventSinkLayer, - ApprovalWaitLayer, - MockSkillLayer, - MockMcpLayer, - MockMemoryLayer, - MockSchedulerLayer, - MockContextLayer, - MockCheckpointLayer -); - -// home 指向临时目录 ⇒ projectBaseDir() = /.codingcode/project -useTempHome('codingcode-plan-route-'); - -let plansDir = ''; - -beforeEach(() => { - // The route resolves the query cwd to an absolute path first - // (server/cwd.resolveCwd -> path.resolve), then encodes it. - plansDir = join(projectBaseDir(), encodeProjectPath(resolve('/tmp/test'))); - mkdirSync(plansDir, { recursive: true }); -}); - -describe('GET /api/sessions/:id/plan', () => { - it('returns exists:false with empty content when no .md file is present', async () => { - const rt = ManagedRuntime.make(TestLayer as any); - const app = await createServer(rt); - const res = await app.request('/api/sessions/s-1/plan?cwd=/tmp/test'); - expect(res.status).toBe(200); - const body = (await res.json()) as { - content: string; - path: string; - directory: string; - exists: boolean; - }; - expect(body.exists).toBe(false); - expect(body.content).toBe(''); - expect(body.path).toBe(''); - }); - - it('returns the most-recently-modified .md file in the plan directory', async () => { - const oldPath = join(plansDir, 'old-plan.md'); - const newPath = join(plansDir, 'new-plan.md'); - writeFileSync(oldPath, '# OLD', 'utf8'); - writeFileSync(newPath, '# NEW', 'utf8'); - // Make `oldPlan` newer so that we can verify the route picks by mtime, not by name - const newerDate = new Date(); - const olderDate = new Date(newerDate.getTime() - 60_000); - utimesSync(oldPath, olderDate, olderDate); - utimesSync(newPath, newerDate, newerDate); - - const rt = ManagedRuntime.make(TestLayer as any); - const app = await createServer(rt); - const res = await app.request('/api/sessions/s-1/plan?cwd=/tmp/test'); - expect(res.status).toBe(200); - const body = (await res.json()) as { - content: string; - path: string; - exists: boolean; - }; - expect(body.exists).toBe(true); - expect(body.path).toBe(newPath); - expect(body.content).toBe('# NEW'); - }); - - it('ignores non-md files in the plan directory', async () => { - const mdPath = join(plansDir, 'plan.md'); - writeFileSync(mdPath, '# ONLY-MD', 'utf8'); - writeFileSync(join(plansDir, 'notes.txt'), 'should be ignored', 'utf8'); - - const rt = ManagedRuntime.make(TestLayer as any); - const app = await createServer(rt); - const res = await app.request('/api/sessions/s-1/plan?cwd=/tmp/test'); - const body = (await res.json()) as { content: string; exists: boolean }; - expect(body.exists).toBe(true); - expect(body.content).toBe('# ONLY-MD'); - }); -}); diff --git a/packages/codingcode/test/server/session-title-route.test.ts b/packages/codingcode/test/server/session-title-route.test.ts index 099efbe6..65fec6fe 100644 --- a/packages/codingcode/test/server/session-title-route.test.ts +++ b/packages/codingcode/test/server/session-title-route.test.ts @@ -34,7 +34,7 @@ describe('PUT /api/sessions/:id/title', () => { headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cwd, - activeProfile: 'build', + permissionMode: 'askBeforeExec', model: 'gpt-4', }), diff --git a/packages/codingcode/test/session/compute-paths.test.ts b/packages/codingcode/test/session/compute-paths.test.ts index 0e4f1fd8..3b1b3bb3 100644 --- a/packages/codingcode/test/session/compute-paths.test.ts +++ b/packages/codingcode/test/session/compute-paths.test.ts @@ -47,7 +47,7 @@ describe('computePaths', () => { const svc = yield* SessionService; return yield* svc.create(cwd, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -80,7 +80,7 @@ describe('computePaths', () => { const svc = yield* SessionService; return yield* svc.create(cwd, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -94,7 +94,7 @@ describe('computePaths', () => { cwd, { model: 'subagent-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { diff --git a/packages/codingcode/test/session/create-active-profile.test.ts b/packages/codingcode/test/session/create-active-profile.test.ts deleted file mode 100644 index 89d708f0..00000000 --- a/packages/codingcode/test/session/create-active-profile.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { Effect } from 'effect'; -import { computePaths } from '../../src/session/paths.js'; -import { SessionService } from '../../src/session/port.js'; -import { SessionLayer } from '../../src/session/session.js'; -import { readSessionMeta } from '../../src/session/file-ops.js'; -import { useTempProjectBase } from '../helpers/project-base.js'; -import { text } from '../helpers/parts.js'; - -useTempProjectBase(); - -function run(effect: Effect.Effect): Promise { - return Effect.runPromise(effect.pipe(Effect.provide(SessionLayer) as any)); -} - -describe('session activeProfile persistence', () => { - it('persists the profile supplied at creation without a mode field', async () => { - const cwd = '/tmp/test-active-profile-create'; - const state = await run( - Effect.gen(function* () { - const session = yield* SessionService; - return yield* session.create(cwd, { - model: 'gpt-4o', - activeProfile: 'plan', - permissionMode: 'askBeforeExec', - }); - }) - ); - - const paths = computePaths(state.cwd, state.sessionId, state.parentSessionId); - const meta = readSessionMeta(paths.transcriptPath); - - expect(state.activeProfile).toBe('plan'); - expect(meta?.activeProfile).toBe('plan'); - expect(state).not.toHaveProperty('mode'); - expect(meta).not.toHaveProperty('mode'); - }); - - it('keeps an updated profile when later events rewrite the session head', async () => { - const cwd = '/tmp/test-active-profile-update'; - const state = await run( - Effect.gen(function* () { - const session = yield* SessionService; - return yield* session.create(cwd, { - model: 'gpt-4o', - activeProfile: 'build', - permissionMode: 'askBeforeExec', - }); - }) - ); - - await run( - Effect.gen(function* () { - const session = yield* SessionService; - yield* session.setActiveProfile(state.cwd, state.sessionId, 'plan'); - const reloaded = yield* session.load(state.cwd, state.sessionId); - yield* session.recordUser(reloaded, text('hello')); - }) - ); - - const paths = computePaths(state.cwd, state.sessionId, state.parentSessionId); - const meta = readSessionMeta(paths.transcriptPath); - - expect(meta?.activeProfile).toBe('plan'); - expect(meta).not.toHaveProperty('mode'); - }); -}); diff --git a/packages/codingcode/test/session/create-session-profile.test.ts b/packages/codingcode/test/session/create-session-profile.test.ts deleted file mode 100644 index 64c2c953..00000000 --- a/packages/codingcode/test/session/create-session-profile.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { Effect } from 'effect'; -import { SessionService } from '../../src/session/port.js'; -import { SessionLayer } from '../../src/session/session.js'; -import { useTempProjectBase } from '../helpers/project-base.js'; - -useTempProjectBase(); - -function run(effect: Effect.Effect): Promise { - return Effect.runPromise(effect.pipe(Effect.provide(SessionLayer) as any)); -} - -describe('SessionService.create profile', () => { - it('uses activeProfile as the only agent profile field', async () => { - const state = await run( - Effect.gen(function* () { - const session = yield* SessionService; - return yield* session.create('/tmp/test-session-profile', { - model: 'gpt-4o', - activeProfile: 'build', - permissionMode: 'askBeforeExec', - }); - }) - ); - - expect(state.activeProfile).toBe('build'); - expect(state).not.toHaveProperty('mode'); - }); -}); diff --git a/packages/codingcode/test/session/disk-setters.test.ts b/packages/codingcode/test/session/disk-setters.test.ts index ee3406dd..f1556ef1 100644 --- a/packages/codingcode/test/session/disk-setters.test.ts +++ b/packages/codingcode/test/session/disk-setters.test.ts @@ -4,8 +4,6 @@ import { mkdirSync } from 'fs'; import { join } from 'path'; import { SessionService } from '../../src/session/port.js'; import { SessionLayer } from '../../src/session/session.js'; -import { computePaths } from '../../src/session/paths.js'; -import { readSessionMeta } from '../../src/session/file-ops.js'; import { HookService } from '../../src/hooks/port.js'; import { McpService } from '../../src/mcp/port.js'; import { RulesService } from '../../src/rules/port.js'; @@ -56,7 +54,6 @@ describe('SessionService disk setter/getter consistency', () => { const session = yield* SessionService; return yield* session.create(cwd, { model: 'm', - activeProfile: 'build', permissionMode: 'askBeforeExec', }); }) @@ -84,74 +81,4 @@ describe('SessionService disk setter/getter consistency', () => { expect(state.permissionMode).toBe('bypass'); }); - it('setActiveProfile persists to loaded state', async () => { - await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - yield* session.setActiveProfile(cwd, sessionId, 'plan'); - }) - ); - const state = await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - return yield* session.load(cwd, sessionId); - }) - ); - expect(state.activeProfile).toBe('plan'); - }); - - it('setActiveProfile to plan leaves permissionMode untouched', async () => { - await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - yield* session.setActiveProfile(cwd, sessionId, 'plan'); - }) - ); - const state = await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - return yield* session.load(cwd, sessionId); - }) - ); - expect(state.activeProfile).toBe('plan'); - expect(state.permissionMode).toBe('askBeforeExec'); - }); - - it('setActiveProfile to build leaves permissionMode untouched', async () => { - await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - yield* session.setActiveProfile(cwd, sessionId, 'plan'); - yield* session.setActiveProfile(cwd, sessionId, 'build'); - }) - ); - const state = await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - return yield* session.load(cwd, sessionId); - }) - ); - expect(state.activeProfile).toBe('build'); - expect(state.permissionMode).toBe('askBeforeExec'); - }); - - it('setActiveProfile is durable across reload (session head on disk)', async () => { - await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - yield* session.setActiveProfile(cwd, sessionId, 'plan'); - }) - ); - const state = await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - return yield* session.load(cwd, sessionId); - }) - ); - const meta = readSessionMeta( - computePaths(state.cwd, state.sessionId, state.parentSessionId).transcriptPath - ); - expect(meta?.activeProfile).toBe('plan'); - expect(meta).not.toHaveProperty('mode'); - }); }); diff --git a/packages/codingcode/test/session/filter-ui.test.ts b/packages/codingcode/test/session/filter-ui.test.ts index 901e3432..79470f5d 100644 --- a/packages/codingcode/test/session/filter-ui.test.ts +++ b/packages/codingcode/test/session/filter-ui.test.ts @@ -12,7 +12,7 @@ function makeBaseEvents(extra: SessionEvent[] = []): SessionEvent[] { createdAt: new Date().toISOString(), model: 'deepseek-chat', title: '', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { type: 'user', turnId: 1, content: text('hello') }, @@ -131,7 +131,7 @@ describe('sessionEventsToTurns with summary', () => { createdAt: new Date().toISOString(), model: 'deepseek-chat', title: '', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { type: 'user', turnId: 1, content: text('hello') }, diff --git a/packages/codingcode/test/session/fork.test.ts b/packages/codingcode/test/session/fork.test.ts index 6c22bbcc..f418930f 100644 --- a/packages/codingcode/test/session/fork.test.ts +++ b/packages/codingcode/test/session/fork.test.ts @@ -28,7 +28,7 @@ function makeFixture(sessionId: string, slug: string) { createdAt: new Date().toISOString(), model: 'test', title: 'fixture', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { type: 'user', turnId: 1, content: 'first' }, @@ -74,7 +74,7 @@ function makeState(sessionId: string, cwd: string, title: string, currentTurnId: createdAt: new Date().toISOString(), model: 'test', title, - activeProfile: 'build' as const, + permissionMode: 'askBeforeExec' as const, currentTurnId, usage: undefined, @@ -278,7 +278,7 @@ describe('forkSession', () => { createdAt: new Date().toISOString(), model: 'test', title: 'uuid-fixture', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { type: 'user', turnId: 1, content: 'q1' }, diff --git a/packages/codingcode/test/session/io-error.test.ts b/packages/codingcode/test/session/io-error.test.ts index 5cb87287..fdecb678 100644 --- a/packages/codingcode/test/session/io-error.test.ts +++ b/packages/codingcode/test/session/io-error.test.ts @@ -22,7 +22,7 @@ describe('SessionService — SESSION_IO_ERROR', () => { createdAt: new Date().toISOString(), model: 'test', title: 'io-err-s', - activeProfile: 'build', + permissionMode: 'askBeforeExec', currentTurnId: 1, usage: undefined, @@ -52,7 +52,7 @@ describe('SessionService — SESSION_IO_ERROR', () => { createdAt: new Date().toISOString(), model: 'test', title: 'io-err-a', - activeProfile: 'build', + permissionMode: 'askBeforeExec', currentTurnId: 1, usage: undefined, @@ -81,7 +81,7 @@ describe('SessionService — SESSION_IO_ERROR', () => { createdAt: new Date().toISOString(), model: 'test', title: 'io-err-e', - activeProfile: 'build', + permissionMode: 'askBeforeExec', currentTurnId: 1, usage: undefined, diff --git a/packages/codingcode/test/session/load-create.test.ts b/packages/codingcode/test/session/load-create.test.ts index 30115fa6..0d33ea0c 100644 --- a/packages/codingcode/test/session/load-create.test.ts +++ b/packages/codingcode/test/session/load-create.test.ts @@ -34,7 +34,7 @@ describe('load — keeps the persisted model untouched', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'gpt-4o', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -70,7 +70,7 @@ describe('load — keeps the persisted model untouched', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'claude-3-5-sonnet', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -142,7 +142,7 @@ describe('load — keeps the persisted model untouched', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'gpt-4o', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -179,7 +179,7 @@ describe('create — generates sessionId internally', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -204,7 +204,7 @@ describe('create — generates sessionId internally', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'my-special-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -230,7 +230,7 @@ describe('create — generates sessionId internally', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -257,7 +257,7 @@ describe('load restores persisted fields', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -303,7 +303,7 @@ describe('load restores persisted fields', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) diff --git a/packages/codingcode/test/session/load-restore-profile.test.ts b/packages/codingcode/test/session/load-restore-profile.test.ts deleted file mode 100644 index 9d08402e..00000000 --- a/packages/codingcode/test/session/load-restore-profile.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { Effect, ManagedRuntime } from 'effect'; -import { mkdirSync } from 'fs'; -import { join } from 'path'; -import { SessionService } from '../../src/session/port.js'; -import { SessionLayer } from '../../src/session/session.js'; -import { computePaths } from '../../src/session/paths.js'; -import { readSessionMeta, rewriteSessionMeta } from '../../src/session/file-ops.js'; -import { useTempProjectBase } from '../helpers/project-base.js'; - -const base = useTempProjectBase(); - -describe('SessionStoreState.activeProfile persistence (disk only)', () => { - let cwd: string; - let sessionId: string; - let transcriptPath: string; - let rt: ManagedRuntime.ManagedRuntime; - - function loadState() { - return rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - return yield* session.load(cwd, sessionId); - }) - ); - } - - beforeEach(async () => { - cwd = join(base.dir, 'load-restore-profile'); - mkdirSync(cwd, { recursive: true }); - rt = ManagedRuntime.make(SessionLayer as any); - const result = await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - const state = yield* session.create(cwd, { - model: 'test-model', - activeProfile: 'build', - permissionMode: 'askBeforeExec', - }); - return { - sessionId: state.sessionId, - transcriptPath: computePaths(state.cwd, state.sessionId, state.parentSessionId) - .transcriptPath, - }; - }) - ); - sessionId = result.sessionId; - transcriptPath = result.transcriptPath; - }); - - afterEach(async () => { - await rt.dispose(); - }); - - it('state.activeProfile is restored for new sessions', async () => { - const stateBefore = await loadState(); - expect(stateBefore.activeProfile).toBe('build'); - }); - - it('state.activeProfile is set when setActiveProfile writes to disk', async () => { - await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - yield* session.setActiveProfile(cwd, sessionId, 'plan'); - }) - ); - - const stateAfter = await loadState(); - expect(stateAfter.activeProfile).toBe('plan'); - }); - - it('state.activeProfile is set when the session head carries activeProfile', async () => { - rewriteSessionMeta(transcriptPath, { activeProfile: 'plan', permissionMode: 'askBeforeExec' }); - - const state = await loadState(); - expect(state.activeProfile).toBe('plan'); - }); - - it('setActiveProfile writes the profile to disk', async () => { - await rt.runPromise( - Effect.gen(function* () { - const session = yield* SessionService; - yield* session.setActiveProfile(cwd, sessionId, 'plan'); - }) - ); - const meta = readSessionMeta(transcriptPath); - expect(meta?.activeProfile).toBe('plan'); - }); -}); diff --git a/packages/codingcode/test/session/materialize-input.test.ts b/packages/codingcode/test/session/materialize-input.test.ts index 22502203..a67da6fc 100644 --- a/packages/codingcode/test/session/materialize-input.test.ts +++ b/packages/codingcode/test/session/materialize-input.test.ts @@ -42,7 +42,7 @@ async function newSession( const svc = yield* SessionService; return yield* svc.create( dir, - { model: 'test-model', activeProfile: 'build', permissionMode: 'askBeforeExec' }, + { model: 'test-model', permissionMode: 'askBeforeExec' }, opts ); }) @@ -278,7 +278,7 @@ describe('SessionService.resolveAssets', () => { const svc = yield* SessionService; const state = yield* svc.create( dir, - { model: 'test-model', activeProfile: 'build', permissionMode: 'askBeforeExec' } + { model: 'test-model', permissionMode: 'askBeforeExec' } ); const png = mediaBytes('png'); const parts = yield* svc.materializeInput(state, [{ type: 'media', bytes: png }]); diff --git a/packages/codingcode/test/session/parent-session-id.test.ts b/packages/codingcode/test/session/parent-session-id.test.ts index ddcf8242..7303b993 100644 --- a/packages/codingcode/test/session/parent-session-id.test.ts +++ b/packages/codingcode/test/session/parent-session-id.test.ts @@ -21,7 +21,7 @@ describe('parentSessionId in session head', () => { const svc = yield* SessionService; return yield* svc.create( cwd, - { model: 'gpt-4o', activeProfile: 'build', permissionMode: 'askBeforeExec' }, + { model: 'gpt-4o', permissionMode: 'askBeforeExec' }, { parentSessionId: parentId } ); }) diff --git a/packages/codingcode/test/session/prompt-estimate.test.ts b/packages/codingcode/test/session/prompt-estimate.test.ts index 2cd7d101..bc1d68bf 100644 --- a/packages/codingcode/test/session/prompt-estimate.test.ts +++ b/packages/codingcode/test/session/prompt-estimate.test.ts @@ -36,7 +36,7 @@ function makeFixture( createdAt: new Date().toISOString(), model: 'test-model', title: 'fixture', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { @@ -88,7 +88,7 @@ function makeState( createdAt: new Date().toISOString(), model: 'test-model', title: 'fixture', - activeProfile: 'build', + permissionMode: 'askBeforeExec', currentTurnId: 2, memorySnapshot: '', @@ -160,7 +160,7 @@ describe('SessionService create sets model', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'my-test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) diff --git a/packages/codingcode/test/session/record-tool-result-persist.test.ts b/packages/codingcode/test/session/record-tool-result-persist.test.ts index 1cd2b351..9dac1616 100644 --- a/packages/codingcode/test/session/record-tool-result-persist.test.ts +++ b/packages/codingcode/test/session/record-tool-result-persist.test.ts @@ -18,7 +18,7 @@ describe('recordToolResult', () => { const svc = yield* SessionService; return yield* svc.create('/tmp/persist-test', { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -51,7 +51,7 @@ describe('recordToolResult', () => { const svc = yield* SessionService; return yield* svc.create('/tmp/persist-test-small', { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) diff --git a/packages/codingcode/test/session/record-user-input.test.ts b/packages/codingcode/test/session/record-user-input.test.ts index 47efc515..502099de 100644 --- a/packages/codingcode/test/session/record-user-input.test.ts +++ b/packages/codingcode/test/session/record-user-input.test.ts @@ -33,7 +33,7 @@ const create = (dir: string) => const svc = yield* SessionService; return yield* svc.create(dir, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }); diff --git a/packages/codingcode/test/session/record-user-title.test.ts b/packages/codingcode/test/session/record-user-title.test.ts index 7a6fdc4e..ea5e9db4 100644 --- a/packages/codingcode/test/session/record-user-title.test.ts +++ b/packages/codingcode/test/session/record-user-title.test.ts @@ -41,7 +41,7 @@ describe('title persistence — backfilled from the first user message', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -62,7 +62,7 @@ describe('title persistence — backfilled from the first user message', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -90,7 +90,7 @@ describe('title persistence — backfilled from the first user message', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -118,7 +118,7 @@ describe('title persistence — backfilled from the first user message', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -154,7 +154,7 @@ describe('title persistence — backfilled from the first user message', () => { return yield* svc.create(dir, { model: 'test-model', title: 'explicit title', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -182,7 +182,7 @@ describe('title persistence — backfilled from the first user message', () => { const svc = yield* SessionService; return yield* svc.create(dir, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) diff --git a/packages/codingcode/test/session/rollback.test.ts b/packages/codingcode/test/session/rollback.test.ts index 76d90100..0b0120ca 100644 --- a/packages/codingcode/test/session/rollback.test.ts +++ b/packages/codingcode/test/session/rollback.test.ts @@ -21,7 +21,7 @@ function makeFixture(sessionId: string, slug: string) { createdAt: new Date().toISOString(), model: 'test-model', title: 'fixture', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { type: 'user', turnId: 1, content: 'hello' }, diff --git a/packages/codingcode/test/session/session-jsonl-path.test.ts b/packages/codingcode/test/session/session-jsonl-path.test.ts index 6bce3c2c..fa6d5340 100644 --- a/packages/codingcode/test/session/session-jsonl-path.test.ts +++ b/packages/codingcode/test/session/session-jsonl-path.test.ts @@ -23,7 +23,7 @@ describe('sessionJsonlPathFromCwd', () => { const svc = yield* SessionService; return yield* svc.create(cwd, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) @@ -50,7 +50,7 @@ describe('sessionJsonlPathFromCwd', () => { const svc = yield* SessionService; return yield* svc.create(cwd, { model: 'test-model', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); }) diff --git a/packages/codingcode/test/session/store-compact-usage.test.ts b/packages/codingcode/test/session/store-compact-usage.test.ts index 9d40948a..ba4064b8 100644 --- a/packages/codingcode/test/session/store-compact-usage.test.ts +++ b/packages/codingcode/test/session/store-compact-usage.test.ts @@ -38,7 +38,7 @@ function makeFixture( createdAt: new Date().toISOString(), model: 'test-model', title: 'fixture', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, ]; @@ -72,7 +72,7 @@ function buildState( createdAt: new Date().toISOString(), model: 'test-model', title: 'fixture', - activeProfile: 'build', + permissionMode: 'askBeforeExec', currentTurnId, memorySnapshot: '', diff --git a/packages/codingcode/test/session/store-diff-rebuild.test.ts b/packages/codingcode/test/session/store-diff-rebuild.test.ts index 13e2c821..c1d2de35 100644 --- a/packages/codingcode/test/session/store-diff-rebuild.test.ts +++ b/packages/codingcode/test/session/store-diff-rebuild.test.ts @@ -13,7 +13,7 @@ describe('sessionEventsToTurns', () => { createdAt: new Date().toISOString(), model: 'deepseek-chat', title: '', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { @@ -65,7 +65,7 @@ describe('sessionEventsToTurns', () => { createdAt: new Date().toISOString(), model: 'deepseek-chat', title: '', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { @@ -115,7 +115,7 @@ describe('sessionEventsToTurns', () => { createdAt: new Date().toISOString(), model: 'deepseek-chat', title: '', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { diff --git a/packages/codingcode/test/session/store-rollback-usage.test.ts b/packages/codingcode/test/session/store-rollback-usage.test.ts index d8f247b3..0a1e0b57 100644 --- a/packages/codingcode/test/session/store-rollback-usage.test.ts +++ b/packages/codingcode/test/session/store-rollback-usage.test.ts @@ -38,7 +38,7 @@ function makeFixture( createdAt: new Date().toISOString(), model: 'test-model', title: 'fixture', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, ]; @@ -72,7 +72,7 @@ function buildState( createdAt: new Date().toISOString(), model: 'test-model', title: 'fixture', - activeProfile: 'build', + permissionMode: 'askBeforeExec', currentTurnId, memorySnapshot: '', diff --git a/packages/codingcode/test/session/subagent-lifecycle-meta.test.ts b/packages/codingcode/test/session/subagent-lifecycle-meta.test.ts index 3a70bea1..9ea06fbe 100644 --- a/packages/codingcode/test/session/subagent-lifecycle-meta.test.ts +++ b/packages/codingcode/test/session/subagent-lifecycle-meta.test.ts @@ -16,7 +16,7 @@ function run(eff: Effect.Effect): Promise { const childOpts = { model: 'gpt-4o', - activeProfile: 'build' as const, + permissionMode: 'askBeforeExec' as const, }; diff --git a/packages/codingcode/test/session/subagent-owner-path.test.ts b/packages/codingcode/test/session/subagent-owner-path.test.ts index 3157de49..6f953f52 100644 --- a/packages/codingcode/test/session/subagent-owner-path.test.ts +++ b/packages/codingcode/test/session/subagent-owner-path.test.ts @@ -22,7 +22,7 @@ function run(eff: Effect.Effect): Promise { const createOpts = { model: 'test-model', - activeProfile: 'build' as const, + permissionMode: 'askBeforeExec' as const, }; diff --git a/packages/codingcode/test/session/ui-history-rollback.test.ts b/packages/codingcode/test/session/ui-history-rollback.test.ts index 4a35e9b2..46a74432 100644 --- a/packages/codingcode/test/session/ui-history-rollback.test.ts +++ b/packages/codingcode/test/session/ui-history-rollback.test.ts @@ -24,7 +24,7 @@ function makeFixture(sessionId: string, slug: string, extraEvents?: object[]) { createdAt: new Date().toISOString(), model: 'test-model', title: 'fixture', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { type: 'user', turnId: 1, content: 'hello' }, @@ -66,7 +66,7 @@ describe('filterForContext', () => { createdAt: new Date().toISOString(), model: 'test-model', title: 'test', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { type: 'user', turnId: 1, content: text('hello') }, @@ -115,7 +115,7 @@ describe('readUIHistory with visibility filtering', () => { createdAt: new Date().toISOString(), model: 'test-model', title: 'test', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { type: 'user', turnId: 1, content: 'hello' }, diff --git a/packages/codingcode/test/session/view-assembly.test.ts b/packages/codingcode/test/session/view-assembly.test.ts index 9413195d..c686a55d 100644 --- a/packages/codingcode/test/session/view-assembly.test.ts +++ b/packages/codingcode/test/session/view-assembly.test.ts @@ -22,7 +22,7 @@ function makeEvents(extra: SessionEvent[] = []): SessionEvent[] { createdAt: new Date().toISOString(), model: 'deepseek-chat', title: '', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { type: 'user', turnId: 1, content: text('hello') }, @@ -118,7 +118,7 @@ describe('buildContextMessages', () => { createdAt: new Date().toISOString(), model: 'deepseek-chat', title: '', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { @@ -147,7 +147,7 @@ describe('buildContextMessages', () => { createdAt: new Date().toISOString(), model: 'deepseek-chat', title: '', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { @@ -198,7 +198,7 @@ describe('buildContextMessages', () => { createdAt: new Date().toISOString(), model: 'deepseek-chat', title: '', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { @@ -254,7 +254,7 @@ describe('buildContextMessages', () => { createdAt: new Date().toISOString(), model: 'deepseek-chat', title: '', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { @@ -300,7 +300,7 @@ describe('buildContextMessages', () => { createdAt: new Date().toISOString(), model: 'deepseek-chat', title: '', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { @@ -345,7 +345,7 @@ describe('buildContextMessages', () => { createdAt: new Date().toISOString(), model: 'deepseek-chat', title: '', - activeProfile: 'build', + permissionMode: 'askBeforeExec', }, { type: 'user', turnId: 1, content: text('q1') }, diff --git a/packages/codingcode/test/subagent/lifecycle-integration.test.ts b/packages/codingcode/test/subagent/lifecycle-integration.test.ts index 703a4086..92efcd4b 100644 --- a/packages/codingcode/test/subagent/lifecycle-integration.test.ts +++ b/packages/codingcode/test/subagent/lifecycle-integration.test.ts @@ -30,7 +30,6 @@ import { SessionLayer } from '../../src/session/session.js'; import { HookService } from '../../src/hooks/port.js'; import { McpService } from '../../src/mcp/port.js'; import { TodoService } from '../../src/todo/port.js'; -import { BUILD_TOOL_NAMES } from '../../src/approval/tool-policy.js'; import { readHistory } from '../../src/session/file-ops.js'; import { encodeProjectPath, normalizePath } from '../../src/util/path.js'; import { transcriptPathFor } from '../../src/context/context.js'; @@ -55,12 +54,9 @@ const probeTool: ToolDefinition = { }, }; -// 探针必须进 build profile 的工具白名单,否则 catalog 装配即抛错 -const buildNamesMutable = BUILD_TOOL_NAMES as unknown as string[]; -buildNamesMutable.push(PROBE); +TOOLS_BY_NAME.set(PROBE, probeTool); afterAll(() => { - const idx = buildNamesMutable.indexOf(PROBE); - if (idx >= 0) buildNamesMutable.splice(idx, 1); + TOOLS_BY_NAME.delete(PROBE); }); // ---- LLM 脚本:按模型排队,逐次取一段响应;'hang' 表示永不收尾 ---- @@ -104,7 +100,14 @@ const Deps = Layer.mergeAll( SessionLayer, ToolExecutorLayer.pipe(Layer.provide(HookMock)), Layer.succeed(CheckpointService, { snapshotBeforeWrite: () => Effect.void } as any), - Layer.succeed(ApprovalService, { evaluate: () => Effect.succeed({ type: 'allow' }) } as any), + Layer.succeed(ApprovalService, { + evaluate: () => Effect.succeed({ type: 'allow', source: 'test' }), + evaluateBatch: (requests: readonly unknown[]) => + Effect.succeed(requests.map(() => ({ type: 'allow' as const, source: 'test' }))), + evaluateEscalation: () => Effect.succeed({ type: 'allow', source: 'test' }), + evaluateEscalationBatch: (requests: readonly unknown[]) => + Effect.succeed(requests.map(() => ({ type: 'allow' as const, source: 'test' }))), + } as any), Layer.succeed(SkillService, { getAll: () => Effect.succeed([]), readContent: () => Effect.succeed(''), diff --git a/packages/codingcode/test/subagent/runner-wiring.test.ts b/packages/codingcode/test/subagent/runner-wiring.test.ts index 81c3dc5f..0632037a 100644 --- a/packages/codingcode/test/subagent/runner-wiring.test.ts +++ b/packages/codingcode/test/subagent/runner-wiring.test.ts @@ -139,7 +139,12 @@ const AgentDeps = Layer.mergeAll( snapshotBeforeWrite: () => Effect.void, } as any), Layer.succeed(ApprovalService, { - evaluate: () => Effect.succeed({ type: 'allow' }), + evaluate: () => Effect.succeed({ type: 'allow', source: 'test' }), + evaluateBatch: (requests: readonly unknown[]) => + Effect.succeed(requests.map(() => ({ type: 'allow' as const, source: 'test' }))), + evaluateEscalation: () => Effect.succeed({ type: 'allow', source: 'test' }), + evaluateEscalationBatch: (requests: readonly unknown[]) => + Effect.succeed(requests.map(() => ({ type: 'allow' as const, source: 'test' }))), } as any), Layer.succeed(SkillService, { getAll: () => Effect.succeed([]), @@ -216,12 +221,12 @@ describe('subagent runner wiring (child session mounts under the parent)', () => const runner = yield* SubagentRunnerService; const parent = yield* session.create(cwd, { model: PARENT_MODEL, - activeProfile: 'build', + permissionMode: 'askBeforeExec', }); const { stream, sessionId } = yield* runner.runSubagent(incomingText('do the thing'), { cwd, - activeProfile: 'build', + parentSessionId: parent.sessionId, agentName: opts.agentName ?? 'reviewer', ...(opts.description ? { description: opts.description } : {}), @@ -246,7 +251,7 @@ describe('subagent runner wiring (child session mounts under the parent)', () => const { stream, sessionId } = yield* runner.runSubagent(incomingText(text), { sessionId: childId, cwd, - activeProfile: 'build', + parentSessionId: parentId, agentName: 'reviewer', model: CHILD_MODEL, diff --git a/packages/codingcode/test/tools/catalog.test.ts b/packages/codingcode/test/tools/catalog.test.ts index 803d3988..5bca7b6c 100644 --- a/packages/codingcode/test/tools/catalog.test.ts +++ b/packages/codingcode/test/tools/catalog.test.ts @@ -1,44 +1,18 @@ import { describe, it, expect } from 'vitest'; import { Effect } from 'effect'; -import { createToolCatalog } from '../../src/tools/catalog.js'; +import { createToolCatalog, TOOLS_BY_NAME } from '../../src/tools/catalog.js'; import type { McpToolSpec } from '../../src/mcp/types.js'; -const BUILD_NAMES = [ - 'read_file', - 'write_file', - 'edit_file', - 'execute_command', - 'search_code', - 'search_files', - 'fetch_url', - 'web_search', - 'todo_write', - 'spawn_agent', - 'wait_agent', -]; - describe('createToolCatalog', () => { - it('assembles tools by name in the order given', () => { - const { tools } = createToolCatalog(BUILD_NAMES); - expect(tools.map((t) => t.name)).toEqual(BUILD_NAMES); - }); - - it('excludes tools not present in the name list', () => { - const { tools } = createToolCatalog(['read_file', 'submit_plan']); - const names = tools.map((t) => t.name); - expect(names).toEqual(['read_file', 'submit_plan']); - expect(names).not.toContain('write_file'); - expect(names).not.toContain('execute_command'); - }); - - it('throws on an unknown tool name', () => { - expect(() => createToolCatalog(['nope'])).toThrow(/Unknown tool/); + it('assembles the complete built-in catalog', () => { + const { tools } = createToolCatalog(); + expect(tools.map((t) => t.name)).toEqual([...TOOLS_BY_NAME.keys()]); }); it('lookup resolves registered tools by name only', () => { - const { lookup } = createToolCatalog(BUILD_NAMES); + const { lookup } = createToolCatalog(); expect(lookup('write_file')?.name).toBe('write_file'); - expect(lookup('submit_plan')).toBeUndefined(); + expect(lookup('unknown_tool')).toBeUndefined(); }); it('merges dynamic MCP tools into the catalog', () => { @@ -50,8 +24,8 @@ describe('createToolCatalog', () => { readOnlyHint: false, execute: () => Effect.succeed('ok'), }; - const { tools, lookup } = createToolCatalog(['read_file'], [spec]); - expect(tools.map((t) => t.name)).toEqual(['read_file', 'srv:thing']); + const { tools, lookup } = createToolCatalog([spec]); + expect(tools.map((t) => t.name)).toEqual([...TOOLS_BY_NAME.keys(), 'srv:thing']); expect(lookup('srv:thing')?.name).toBe('srv:thing'); }); @@ -68,13 +42,29 @@ describe('createToolCatalog', () => { readOnlyHint: false, execute: () => Effect.succeed('ok'), }; - const { lookup } = createToolCatalog([], [spec]); + const { lookup } = createToolCatalog([spec]); const tool = lookup('srv:thing')!; expect(() => tool.parse({})).toThrow(); expect(tool.parse({ text: 'hello' })).toEqual({ text: 'hello' }); }); - it('forwards MCP spec execute into the tool runner', async () => { + it('rejects direct MCP execution without a sandbox policy', async () => { + const spec: McpToolSpec = { + server: 'srv', + name: 'thing', + description: '', + inputSchema: {}, + readOnlyHint: false, + execute: (args) => Effect.succeed(`called:${String(args.n)}`), + }; + const { lookup } = createToolCatalog([spec]); + const tool = lookup('srv:thing')!; + await expect( + Effect.runPromise(tool.execute({ n: 1 }, { model: 'test-model' }) as Effect.Effect) + ).rejects.toThrow(/SANDBOX_POLICY_DENIED/); + }); + + it('forwards MCP execution when a sandbox policy is supplied', async () => { const spec: McpToolSpec = { server: 'srv', name: 'thing', @@ -83,9 +73,25 @@ describe('createToolCatalog', () => { readOnlyHint: false, execute: (args) => Effect.succeed(`called:${String(args.n)}`), }; - const { lookup } = createToolCatalog([], [spec]); + const { lookup } = createToolCatalog([spec]); const tool = lookup('srv:thing')!; - const out = await Effect.runPromise(tool.execute({ n: 1 }) as Effect.Effect); + const out = await Effect.runPromise( + tool.execute( + { n: 1 }, + { + model: 'test-model', + sandboxPolicy: { + mode: 'unrestricted', + workspaceRoot: process.cwd(), + additionalWritableRoots: [], + network: { mode: 'unrestricted', hosts: [], ports: [] }, + sessionId: 'test-session', + enforcement: 'disabled', + fingerprint: 'test', + }, + } + ) as Effect.Effect + ); expect(out).toBe('called:1'); }); }); diff --git a/packages/codingcode/test/tools/domains/bash/bash-project-path.test.ts b/packages/codingcode/test/tools/domains/bash/bash-project-path.test.ts index 5210cbae..79bf0bb4 100644 --- a/packages/codingcode/test/tools/domains/bash/bash-project-path.test.ts +++ b/packages/codingcode/test/tools/domains/bash/bash-project-path.test.ts @@ -5,6 +5,7 @@ import { join } from 'path'; import { tmpdir } from 'os'; import { randomUUID } from 'crypto'; import { bashTool } from '../../../../src/tools/domains/bash/exec.js'; +import { testSandboxPolicy } from '../../../helpers/sandbox.js'; describe('tools/domains/bash projectPath isolation', () => { let globalDir: string; @@ -36,14 +37,10 @@ describe('tools/domains/bash projectPath isolation', () => { } }); - const ctx = (cwd: string) => ({ projectPath: cwd, model: 'test-model' }); + const ctx = (cwd: string) => ({ projectPath: cwd, model: 'test-model', sandboxPolicy: testSandboxPolicy(cwd) }); it('executes command in ctx.projectPath when cwd arg is absent', async () => { - // On Windows, use PowerShell to write a file in the current directory - const isWin = process.platform === 'win32'; - const cmd = isWin - ? `powershell -Command "'hello' | Out-File -Encoding utf8 test-bash.txt"` - : `echo hello > test-bash.txt`; + const cmd = 'echo hello > test-bash.txt'; await Effect.runPromise(bashTool.execute({ command: cmd, timeout_ms: 10000 }, ctx(projectDir))); @@ -54,14 +51,11 @@ describe('tools/domains/bash projectPath isolation', () => { }, 15000); it('falls back to process.cwd() when ctx.projectPath is absent and cwd arg is absent', async () => { - const isWin = process.platform === 'win32'; - const cmd = isWin - ? `powershell -Command "'fallback' | Out-File -Encoding utf8 test-fallback.txt"` - : `echo fallback > test-fallback.txt`; + const cmd = 'echo fallback > test-fallback.txt'; try { await Effect.runPromise( - bashTool.execute({ command: cmd, timeout_ms: 10000 }, undefined) as any + bashTool.execute({ command: cmd, timeout_ms: 10000 }, { projectPath: process.cwd(), model: 'test-model', sandboxPolicy: testSandboxPolicy(process.cwd()) }) as any ); const cwd = process.cwd(); @@ -80,10 +74,7 @@ describe('tools/domains/bash projectPath isolation', () => { const otherDir = join(tmpdir(), `other-${randomUUID().slice(0, 8)}`); mkdirSync(otherDir, { recursive: true }); try { - const isWin = process.platform === 'win32'; - const cmd = isWin - ? `powershell -Command "'other' | Out-File -Encoding utf8 test-other.txt"` - : `echo other > test-other.txt`; + const cmd = 'echo other > test-other.txt'; await Effect.runPromise( bashTool.execute({ command: cmd, cwd: otherDir, timeout_ms: 10000 }, ctx(projectDir)) diff --git a/packages/codingcode/test/tools/domains/bash/exec-error.test.ts b/packages/codingcode/test/tools/domains/bash/exec-error.test.ts index 2558e6d3..a01a21bc 100644 --- a/packages/codingcode/test/tools/domains/bash/exec-error.test.ts +++ b/packages/codingcode/test/tools/domains/bash/exec-error.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect, vi } from 'vitest'; import { Effect } from 'effect'; import { EventEmitter } from 'events'; +import { testSandboxPolicy } from '../../../helpers/sandbox.js'; const mockProc = Object.assign(new EventEmitter(), { stdout: Object.assign(new EventEmitter(), { on: vi.fn() }), @@ -12,6 +13,7 @@ const spawnMock = vi.fn(() => mockProc); vi.mock('child_process', () => ({ spawn: spawnMock, + execFile: vi.fn(), })); const { bashTool } = await import('../../../../src/tools/domains/bash/exec.js'); @@ -19,7 +21,10 @@ const { AgentError } = await import('../../../../src/util/error.js'); describe('tools/domains/bash exec error', () => { it('fails with AgentError when spawn emits error', async () => { - const effect = bashTool.execute({ command: 'echo test', timeout_ms: 5000 }); + const effect = bashTool.execute( + { command: 'echo test', timeout_ms: 5000 }, + { projectPath: process.cwd(), model: 'test-model', sandboxPolicy: testSandboxPolicy(process.cwd()) } + ); // Emit error on next tick so Effect.async callback has registered listeners setTimeout(() => mockProc.emit('error', new Error('spawn failed')), 0); const exit = await Effect.runPromiseExit(effect); @@ -27,7 +32,10 @@ describe('tools/domains/bash exec error', () => { }); it('fails with TOOL_EXECUTION_FAILED code', async () => { - const effect = bashTool.execute({ command: 'echo test', timeout_ms: 5000 }); + const effect = bashTool.execute( + { command: 'echo test', timeout_ms: 5000 }, + { projectPath: process.cwd(), model: 'test-model', sandboxPolicy: testSandboxPolicy(process.cwd()) } + ); setTimeout(() => mockProc.emit('error', new Error('spawn failed')), 0); const exit = await Effect.runPromiseExit(effect); expect(exit._tag).toBe('Failure'); diff --git a/packages/codingcode/test/tools/domains/fs/tool-project-path.test.ts b/packages/codingcode/test/tools/domains/fs/tool-project-path.test.ts index 159e6981..92b0b708 100644 --- a/packages/codingcode/test/tools/domains/fs/tool-project-path.test.ts +++ b/packages/codingcode/test/tools/domains/fs/tool-project-path.test.ts @@ -9,6 +9,7 @@ import { writeFileTool } from '../../../../src/tools/domains/fs/write.js'; import { editFileTool } from '../../../../src/tools/domains/fs/edit.js'; import { searchTool } from '../../../../src/tools/domains/fs/grep.js'; import { globTool } from '../../../../src/tools/domains/fs/glob.js'; +import { testSandboxPolicy } from '../../../helpers/sandbox.js'; describe('tools/domains/fs projectPath isolation', () => { let globalDir: string; @@ -40,7 +41,7 @@ describe('tools/domains/fs projectPath isolation', () => { } }); - const ctx = (cwd: string) => ({ projectPath: cwd, model: 'test-model' }); + const ctx = (cwd: string) => ({ projectPath: cwd, model: 'test-model', sandboxPolicy: testSandboxPolicy(cwd) }); it('read_file uses ctx.projectPath over workspaceCwd', async () => { writeFileSync(join(projectDir, 'a.txt'), 'hello', 'utf8'); @@ -99,7 +100,10 @@ describe('tools/domains/fs projectPath isolation', () => { writeFileSync(join(cwd, 'h-test.txt'), 'fallback', 'utf8'); try { const result = await Effect.runPromise( - readFileTool.execute({ path: 'h-test.txt', offset: 1, limit: 200 }, undefined) + readFileTool.execute( + { path: 'h-test.txt', offset: 1, limit: 200 }, + { projectPath: cwd, model: 'test-model', sandboxPolicy: testSandboxPolicy(cwd) } + ) ); expect(result).toContain('fallback'); } finally { diff --git a/packages/codingcode/test/tools/domains/subagent/lifecycle-tools.test.ts b/packages/codingcode/test/tools/domains/subagent/lifecycle-tools.test.ts index 5b51ce37..b1bdd1bb 100644 --- a/packages/codingcode/test/tools/domains/subagent/lifecycle-tools.test.ts +++ b/packages/codingcode/test/tools/domains/subagent/lifecycle-tools.test.ts @@ -17,6 +17,7 @@ import { listModels } from '../../../../src/infra/models.js'; import type { SessionStoreState } from '../../../../src/session/types.js'; import type { ToolExecCtx } from '../../../../src/tools/types.js'; import { useTempProjectBase } from '../../../helpers/project-base.js'; +import { testSandboxPolicy } from '../../../helpers/sandbox.js'; useTempProjectBase('codingcode-test-lifecycle-tools-'); @@ -62,7 +63,6 @@ function createSession( cwd, { model: overrides.model ?? CHILD_MODEL, - activeProfile: 'build', permissionMode: 'askBeforeExec', }, { @@ -81,7 +81,7 @@ function ctx(cwd: string, over: Partial = {}): ToolExecCtx { sessionId: PARENT, parentChain: [], projectPath: cwd, - activeProfile: 'build', + sandboxPolicy: testSandboxPolicy(cwd), model: 'parent-model', ...over, } as ToolExecCtx; @@ -247,13 +247,13 @@ describe('resume_agent', () => { expect(calls).toHaveLength(0); }); - it('缺会话身份 → CONFIG_MISSING', async () => { + it('缺少 sandbox 身份 → SANDBOX_POLICY_DENIED', async () => { const { layer } = registryLayer(); const code = await attempt( resumeAgentTool.execute({ sessionId: 'x', prompt: 'go' }, { model: 'm' } as any), Layer.merge(hooksLayer(), layer) ).then(codeOf); - expect(code).toBe('CONFIG_MISSING'); + expect(code).toBe('SANDBOX_POLICY_DENIED'); }); }); @@ -358,11 +358,11 @@ describe('send_message', () => { } }); - it('缺发送方会话 id → CONFIG_MISSING', async () => { + it('缺少 sandbox 身份 → SANDBOX_POLICY_DENIED', async () => { const { r } = await deliver(freshCwd(), { sessionId: 'x', message: 'hi' }, { model: 'm', } as any); - expect(codeOf(r)).toBe('CONFIG_MISSING'); + expect(codeOf(r)).toBe('SANDBOX_POLICY_DENIED'); }); }); diff --git a/packages/codingcode/test/tools/edit.test.ts b/packages/codingcode/test/tools/edit.test.ts index 881aba6e..2b4e63e4 100644 --- a/packages/codingcode/test/tools/edit.test.ts +++ b/packages/codingcode/test/tools/edit.test.ts @@ -4,8 +4,10 @@ import { editFileTool } from '../../src/tools/domains/fs/edit.js'; import { writeFile, readFile, rm } from 'fs/promises'; import { join } from 'path'; import { tmpdir } from 'os'; +import { testSandboxPolicy } from '../helpers/sandbox.js'; const testFile = join(tmpdir(), 'coding-agent-edit-test-' + Date.now() + '.txt'); +const ctx = { projectPath: tmpdir(), model: 'test-model', sandboxPolicy: testSandboxPolicy(tmpdir()) }; const initialContent = `line one line two @@ -28,7 +30,7 @@ describe('editFileTool', () => { path: testFile, old_string: 'line three', new_string: 'line THREE', - }) as any + }, ctx) as any ); expect(result).toContain('1 replacement made'); const content = await readFile(testFile, 'utf-8'); @@ -42,7 +44,7 @@ describe('editFileTool', () => { path: testFile, old_string: 'line one', new_string: 'LINE ONE', - }) as any + }, ctx) as any ); expect(result).toContain('1 replacement made'); const content = await readFile(testFile, 'utf-8'); @@ -55,7 +57,7 @@ describe('editFileTool', () => { path: testFile, old_string: 'line four', new_string: 'LINE FOUR', - }) as any + }, ctx) as any ); expect(result).toContain('1 replacement made'); const content = await readFile(testFile, 'utf-8'); @@ -68,7 +70,7 @@ describe('editFileTool', () => { path: testFile, old_string: 'line two', new_string: 'LINE TWO', - }) as any + }, ctx) as any ); expect(result).toContain('Error'); expect(result).toContain('appears 2 times'); @@ -80,7 +82,7 @@ describe('editFileTool', () => { path: testFile, old_string: 'nonexistent text', new_string: 'replacement', - }) + }, ctx) ); expect(result).toContain('Error'); expect(result).toContain('not found'); @@ -93,7 +95,7 @@ describe('editFileTool', () => { path: testFile, old_string: 'line one\nline two', new_string: 'LINE ONE\nLINE TWO', - }) + }, ctx) ); expect(result).toContain('1 replacement made'); const content = await readFile(testFile, 'utf-8'); diff --git a/packages/codingcode/test/tools/executor-concurrency.test.ts b/packages/codingcode/test/tools/executor-concurrency.test.ts index 05ec73d8..33d441a8 100644 --- a/packages/codingcode/test/tools/executor-concurrency.test.ts +++ b/packages/codingcode/test/tools/executor-concurrency.test.ts @@ -128,7 +128,6 @@ function runBatch( projectPath: string; sessionId?: string; signal?: AbortSignal; - activeProfile?: 'plan' | 'build'; model: string; }, h: Harness, @@ -136,16 +135,14 @@ function runBatch( ): Promise { const program = Effect.gen(function* () { const exec = yield* ToolExecutorService; - // 只把内置名交给 catalog(去重);MCP 工具名(含 `:`)由 spec 侧注册 - const builtinNames = [...new Set(calls.map((c) => c.name).filter((n) => TOOLS_BY_NAME.has(n)))]; - const catalog = yield* exec.prepare(builtinNames, mcpSpecs); + const catalog = yield* exec.prepare(mcpSpecs); return yield* exec.executeBatch( calls, ctx.sessionId, { projectPath: ctx.projectPath, signal: ctx.signal, - activeProfile: ctx.activeProfile, + model: ctx.model, }, catalog.lookup @@ -356,7 +353,7 @@ describe('executeBatch 保序波次调度', () => { tc('d1', 'spawn_agent', { agentName: 'build', description: 'delegate', prompt: 'go' }), tc('w1', 'write_file', { path: 'z.txt', content: 'z' }), ], - { projectPath: dir, sessionId: 'sid-1', activeProfile: 'build', model: 'm' }, + { projectPath: dir, sessionId: 'sid-1', model: 'm' }, h ); @@ -374,7 +371,7 @@ describe('executeBatch 保序波次调度', () => { tc('w2', 'write_file', { path: 'z2.txt', content: 'z' }), tc('d2', 'spawn_agent', { agentName: 'build', description: 'delegate', prompt: 'go' }), ], - { projectPath: dir, sessionId: 'sid-1', activeProfile: 'build', model: 'm' }, + { projectPath: dir, sessionId: 'sid-1', model: 'm' }, h ); expect(reversed.map((r) => r.id)).toEqual(['w2', 'd2']); @@ -422,7 +419,7 @@ describe('executeBatch 保序波次调度', () => { expect(h.hookPoints.filter((p) => p === 'tool.execute.before')).toHaveLength(1); }); - it('18 个内置工具的 concurrencySafe 与分类表逐项一致,且无未覆盖工具', () => { + it('内置工具的 concurrencySafe 与分类表逐项一致,且无未覆盖工具', () => { const expected: Record = { read_file: true, search_code: true, @@ -441,10 +438,9 @@ describe('executeBatch 保序波次调度', () => { write_file: false, edit_file: false, execute_command: false, - submit_plan: false, }; - const { lookup } = createToolCatalog(Object.keys(expected)); + const { lookup } = createToolCatalog(); for (const [name, safe] of Object.entries(expected)) { expect(lookup(name)?.concurrencySafe, name).toBe(safe); } diff --git a/packages/codingcode/test/tools/executor-ctx-projection.test.ts b/packages/codingcode/test/tools/executor-ctx-projection.test.ts index 2a1d7ddb..d36a0857 100644 --- a/packages/codingcode/test/tools/executor-ctx-projection.test.ts +++ b/packages/codingcode/test/tools/executor-ctx-projection.test.ts @@ -39,7 +39,7 @@ function hooksStub() { function runProbe(opts: ToolExecOpts, sessionId: string | undefined): Promise { const program = Effect.gen(function* () { const exec = yield* ToolExecutorService; - const catalog = yield* exec.prepare([PROBE]); + const catalog = yield* exec.prepare(); yield* exec.executeBatch( [{ id: 'c1', name: PROBE, arguments: {} }], sessionId, @@ -64,22 +64,21 @@ describe('工具执行上下文投影', () => { it('可见字段一个不少:sessionId 由位置参数并入,其余从 opts 流过', async () => { const signal = new AbortController().signal; - await runProbe({ turnId: 7, projectPath: '/proj', signal, activeProfile: 'plan', model: 'm-1' }, 'sess-1'); + await runProbe({ turnId: 7, projectPath: '/proj', signal, model: 'm-1' }, 'sess-1'); expect(captured).toBeDefined(); // 精确断言键集合:既防漏抄,也防多塞 expect(Object.keys(captured!).sort()).toEqual([ - 'activeProfile', 'callId', 'model', 'projectPath', + 'sandboxPolicy', 'sessionId', 'signal', ]); expect(captured!.sessionId).toBe('sess-1'); expect(captured!.callId).toBe('c1'); expect(captured!.projectPath).toBe('/proj'); - expect(captured!.activeProfile).toBe('plan'); expect(captured!.model).toBe('m-1'); expect(captured!.signal).toBe(signal); }); diff --git a/packages/codingcode/test/tools/glob.test.ts b/packages/codingcode/test/tools/glob.test.ts index 7303a486..80357292 100644 --- a/packages/codingcode/test/tools/glob.test.ts +++ b/packages/codingcode/test/tools/glob.test.ts @@ -4,8 +4,10 @@ import { globTool } from '../../src/tools/domains/fs/glob.js'; import { writeFile, mkdir, rm } from 'fs/promises'; import { resolve, join } from 'path'; import { tmpdir } from 'os'; +import { testSandboxPolicy } from '../helpers/sandbox.js'; const testDir = join(tmpdir(), 'coding-agent-glob-test-' + Date.now()); +const ctx = { projectPath: tmpdir(), model: 'test-model', sandboxPolicy: testSandboxPolicy(tmpdir()) }; async function setup() { await mkdir(testDir, { recursive: true }); @@ -33,7 +35,7 @@ describe('globTool', () => { pattern: '*.ts', path: testDir, max_results: 50, - }) + }, ctx) ); expect(result).toContain('a.ts'); expect(result).toContain('b.ts'); @@ -53,7 +55,7 @@ describe('globTool', () => { pattern: '**/*.ts', path: testDir, max_results: 50, - }) as any + }, ctx) as any ); expect(result).toContain('e.ts'); } finally { @@ -69,7 +71,7 @@ describe('globTool', () => { pattern: '*.ts', path: testDir, max_results: 1, - }) as any + }, ctx) as any ); expect(result).toContain('showing first 1'); } finally { @@ -85,7 +87,7 @@ describe('globTool', () => { pattern: '*.py', path: testDir, max_results: 50, - }) + }, ctx) ); expect(result).toContain('No files matching'); } finally { @@ -99,7 +101,7 @@ describe('globTool', () => { pattern: '*.ts', path: '/nonexistent/path/xyz123', max_results: 50, - }) as any + }, ctx) as any ); // Should not throw 鈥?globby returns empty array for nonexistent dirs expect(typeof result).toBe('string'); diff --git a/packages/codingcode/test/tools/submit-plan-slug.test.ts b/packages/codingcode/test/tools/submit-plan-slug.test.ts deleted file mode 100644 index ecc7f84b..00000000 --- a/packages/codingcode/test/tools/submit-plan-slug.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { slug } from '../../src/tools/domains/subagent/submit-plan.js'; - -describe('slug()', () => { - it('lowercases and joins with dashes', () => { - expect(slug('Add telemetry')).toBe('add-telemetry'); - }); - - it('lowercases all-caps', () => { - expect(slug('FOO')).toBe('foo'); - }); - - it('collapses runs of non-alphanumeric characters into a single dash', () => { - expect(slug('Foo!!@#Bar')).toBe('foo-bar'); - }); - - it('trims leading and trailing whitespace and dashes', () => { - expect(slug(' Foo ')).toBe('foo'); - expect(slug('---foo---')).toBe('foo'); - }); - - it('handles multi-word titles with spaces as separators', () => { - expect(slug('Foo Bar Baz')).toBe('foo-bar-baz'); - }); - - it('strips diacritics', () => { - expect(slug('Café déjà vu')).toBe('cafe-deja-vu'); - }); - - it('preserves CJK characters in the slug', () => { - expect(slug('写一篇《如果AI有了工资》幽默短文')).toBe('写一篇-如果ai有了工资-幽默短文'); - }); - - it('preserves mixed CJK + ASCII', () => { - expect(slug('添加 OAuth support')).toBe('添加-oauth-support'); - }); - - it('preserves hiragana and katakana', () => { - expect(slug('こんにちは')).toBe('こんにちは'); - expect(slug('カタカナ')).toBe('カタカナ'); - }); - - it('preserves digits', () => { - expect(slug('OAuth 2.0 support')).toBe('oauth-2-0-support'); - }); - - it('is deterministic for the same input', () => { - expect(slug('Same Title')).toBe(slug('Same Title')); - }); - - it('truncates to 80 characters', () => { - const long = 'a'.repeat(200); - expect(slug(long).length).toBe(80); - }); - - it('falls back to "plan" only when input is purely whitespace/punctuation', () => { - expect(slug('!!!')).toBe('plan'); - expect(slug(' ')).toBe('plan'); - }); -}); diff --git a/packages/codingcode/test/tools/websearch.test.ts b/packages/codingcode/test/tools/websearch.test.ts index 298245c2..91e44f16 100644 --- a/packages/codingcode/test/tools/websearch.test.ts +++ b/packages/codingcode/test/tools/websearch.test.ts @@ -5,6 +5,9 @@ import { parseBingHtml, parseBaiduHtml, } from '../../src/tools/domains/web/search.js'; +import { testSandboxPolicy } from '../helpers/sandbox.js'; + +const ctx = { projectPath: process.cwd(), model: 'test-model', sandboxPolicy: testSandboxPolicy(process.cwd()) }; describe('webSearchTool', () => { it('should have correct tool name and schema', () => { @@ -32,7 +35,7 @@ describe('webSearchTool', () => { it('should execute search and return results', async () => { const result = (await Effect.runPromise( - webSearchTool.execute({ query: 'TypeScript programming', max_results: 3 }) as any + webSearchTool.execute({ query: 'TypeScript programming', max_results: 3 }, ctx) as any )) as string; expect(typeof result).toBe('string'); expect(result.length).toBeGreaterThan(0); @@ -42,7 +45,7 @@ describe('webSearchTool', () => { it('should support Chinese query', async () => { const result = (await Effect.runPromise( - webSearchTool.execute({ query: '自主AI agent平台', max_results: 3 }) + webSearchTool.execute({ query: '自主AI agent平台', max_results: 3 }, ctx) )) as string; expect(typeof result).toBe('string'); expect(result.length).toBeGreaterThan(0); diff --git a/packages/codingcode/test/types/tool-exec-shapes.test.ts b/packages/codingcode/test/types/tool-exec-shapes.test.ts index c8bac14c..4976cb50 100644 --- a/packages/codingcode/test/types/tool-exec-shapes.test.ts +++ b/packages/codingcode/test/types/tool-exec-shapes.test.ts @@ -13,7 +13,7 @@ describe('工具执行参数的形状收口', () => { turnId: 3, projectPath: '/p', signal: new AbortController().signal, - activeProfile: 'plan', + model: 'm', }; void opts; diff --git a/packages/desktop/src/agent/AgentWorkspace.tsx b/packages/desktop/src/agent/AgentWorkspace.tsx index 8a441a15..3549eb09 100644 --- a/packages/desktop/src/agent/AgentWorkspace.tsx +++ b/packages/desktop/src/agent/AgentWorkspace.tsx @@ -5,7 +5,6 @@ import { Square, ShieldCheck, Shield, - FileText, Paperclip, X, GripVertical, @@ -26,8 +25,6 @@ import MessageStream from './MessageStream'; import TodoPanel from './TodoPanel'; import ApprovalPanel from './ApprovalPanel'; import AskUserPanel from './AskUserPanel'; -import ProfileIndicator from './ProfileIndicator'; -import PlanPanel from '../shared/PlanPanel'; import MediaView from '../shared/MediaView'; import { reachableMimes, attachmentHint, isLocalMedia, textOf, type ContentPart } from '@shared/parts'; import { MAX_MEDIA_BYTES, type PermissionMode } from '@codingcode/sdk'; @@ -48,17 +45,20 @@ function newId(): string { const MODE_LABELS: Record = { askBeforeExec: '执行前询问', - bypass: '完全放行', + bypass: '跳过审批', + unrestricted: '无限制执行', }; const MODE_NEXT: Record = { askBeforeExec: 'bypass', - bypass: 'askBeforeExec', + bypass: 'unrestricted', + unrestricted: 'askBeforeExec', }; const MODE_ICONS: Record = { askBeforeExec: , bypass: , + unrestricted: , }; // ─── ContextIndicator ────────────────────────────────────────────────────── @@ -261,13 +261,11 @@ function InputBox({ sendMessage, sendQueuedInput, abort, - onOpenPlanPanel, }: { centered?: boolean; sendMessage: (parts: ContentPart[], cwd?: string, skills?: SkillRef[]) => Promise; sendQueuedInput: (threadId: string, item: QueuedInput) => Promise; abort: () => void; - onOpenPlanPanel?: () => void; }) { const [text, setText] = useState(''); const [attachments, setAttachments] = useState([]); @@ -348,21 +346,7 @@ function InputBox({ }, [currentThreadId, abort]); // 有会话时显示该会话真实的权限模式;还没有会话时显示 config.yaml 里的值 - const sessionPermissionMode = useAgentStore((s) => - s.currentThreadId ? (s.profileByThreadId[s.currentThreadId]?.permissionMode ?? null) : null - ); - const permissionMode: PermissionMode = sessionPermissionMode ?? storePermissionMode; - - const isPlanProfile = useAgentStore((s) => { - if (!s.currentThreadId) { - return s.profile === 'plan'; - } - return s.profileByThreadId[s.currentThreadId]?.activeProfile === 'plan'; - }); - const planExists = useAgentStore((s) => { - if (!s.currentThreadId) return false; - return s.pendingPlanByThreadId[s.currentThreadId] != null; - }); + const permissionMode: PermissionMode = storePermissionMode; // Consume pendingInput when it's set useEffect(() => { @@ -791,51 +775,32 @@ function InputBox({ )} {/* Row 2: toolbar */}
- {!isPlanProfile && ( - - )} + } + }} + className="flex items-center gap-1.5 px-2.5 py-1.5 text-[13px] text-[var(--text-placeholder)] hover:text-[var(--text-secondary)] hover:bg-[var(--bg-hover)] rounded-lg transition-colors" + > + {MODE_ICONS[permissionMode]} + {MODE_LABELS[permissionMode]} + ▾ +
- {planExists && onOpenPlanPanel && ( - - )} - {currentThreadId && }
@@ -864,7 +829,6 @@ export default function AgentWorkspace({ sendMessage, sendQueuedInput, abort }: ); const isCompressing = useAgentStore((s) => s.isCompressing); const workspace = useWorkspaceStore(); - const [planPanelOpen, setPlanPanelOpen] = useState(false); if (!currentThreadId) { return ( @@ -901,18 +865,10 @@ export default function AgentWorkspace({ sendMessage, sendQueuedInput, abort }: sendMessage={sendMessage} sendQueuedInput={sendQueuedInput} abort={abort} - onOpenPlanPanel={() => setPlanPanelOpen(true)} />
)} - {planPanelOpen && ( - setPlanPanelOpen(false)} - /> - )} ); } diff --git a/packages/desktop/src/agent/ApprovalPanel.tsx b/packages/desktop/src/agent/ApprovalPanel.tsx index baf712dd..91fac0c8 100644 --- a/packages/desktop/src/agent/ApprovalPanel.tsx +++ b/packages/desktop/src/agent/ApprovalPanel.tsx @@ -1,11 +1,8 @@ -import { useState, useMemo, useCallback } from 'react'; +import { useState, useMemo } from 'react'; import type { Item } from '@shared/types'; import { useAgentStore } from '../stores/agent.store'; -import { useAgentApproval, useAgentCore, useAgentProfile } from '../hooks/useAgent'; +import { useAgentApproval } from '../hooks/useAgent'; import ToolCallCard from '../shared/ToolCallCard'; -import PlanDecisionModal from '../shared/PlanDecisionModal'; -import { useWorkspaceStore } from '../stores/workspace.store'; -import { textPart } from '@shared/parts'; import { Square } from 'lucide-react'; interface ApprovalPanelProps { @@ -17,12 +14,6 @@ interface ApprovalPanelProps { export default function ApprovalPanel({ threadId, inline = false, onStop }: ApprovalPanelProps) { const [collapsed, setCollapsed] = useState(false); const { approveTool, rejectTool } = useAgentApproval(); - const { sendMessage } = useAgentCore(); - const { switchProfile } = useAgentProfile(); - const workspace = useWorkspaceStore(); - - const pendingPlan = useAgentStore((s) => s.pendingPlanByThreadId[threadId] ?? null); - const clearPendingPlan = useAgentStore((s) => s.clearPendingPlan); const pendingKey = useAgentStore((s) => { const thread = s.threads[threadId]; @@ -45,45 +36,6 @@ export default function ApprovalPanel({ threadId, inline = false, onStop }: Appr ); }, [pendingKey, threadId]); - const handleImplement = useCallback(async () => { - if (!pendingPlan) return; - const sessionId = pendingPlan.sessionId; - clearPendingPlan(threadId); - await switchProfile(sessionId, 'build', workspace.rootPath ?? ''); - await sendMessage( - [textPart('Plan approved. Please start implementing it.')], - workspace.rootPath ?? '' - ); - }, [pendingPlan, clearPendingPlan, threadId, switchProfile, sendMessage, workspace.rootPath]); - - const handleSubmitOpinion = useCallback( - async (opinion: string) => { - if (!pendingPlan) return; - clearPendingPlan(threadId); - await sendMessage( - [textPart(`Please revise the plan based on this feedback:\n\n${opinion}`)], - workspace.rootPath ?? '' - ); - }, - [pendingPlan, clearPendingPlan, threadId, sendMessage, workspace.rootPath] - ); - - const handleCancel = useCallback(() => { - clearPendingPlan(threadId); - }, [clearPendingPlan, threadId]); - - if (pendingPlan) { - return ( - void handleImplement()} - onSubmitOpinion={(op) => void handleSubmitOpinion(op)} - onCancel={() => void handleCancel()} - /> - ); - } - if (pendingItems.length === 0) return null; if (inline) { diff --git a/packages/desktop/src/agent/ProfileIndicator.tsx b/packages/desktop/src/agent/ProfileIndicator.tsx deleted file mode 100644 index 2adff62d..00000000 --- a/packages/desktop/src/agent/ProfileIndicator.tsx +++ /dev/null @@ -1,147 +0,0 @@ -import { useState, useEffect } from 'react'; -import { Eye, Hammer, Loader2 } from 'lucide-react'; -import { useAgentProfile } from '../hooks/useAgent'; -import { useAgentStore } from '../stores/agent.store'; -import { setAgentConfig } from '../lib/core-api'; -import type { ProfileName } from '@codingcode/sdk'; - -interface ProfileIndicatorProps { - sessionId: string | null; - cwd: string; -} - -const PROFILE_META = { - plan: { - label: '计划模式', - color: 'text-[var(--accent-warning)] bg-[var(--tag-info-bg)]', - Icon: Eye, - }, - build: { - label: '构建模式', - color: 'text-[var(--accent-success)] bg-[var(--tag-action-bg)]', - Icon: Hammer, - }, -} satisfies Record; - -/** Shows and switches the active agent profile. */ -export default function ProfileIndicator({ sessionId, cwd }: ProfileIndicatorProps) { - const { fetchProfile, switchProfile } = useAgentProfile(); - const [loading, setLoading] = useState(false); - const [busy, setBusy] = useState(false); - - const profile = useAgentStore((s) => - sessionId ? (s.profileByThreadId[sessionId] ?? null) : null - ); - const storeProfile = useAgentStore((s) => s.profile); - const setProfile = useAgentStore((s) => s.setProfile); - const setProfileForThread = useAgentStore((s) => s.setProfileForThread); - const setOptimisticProfileForThread = useAgentStore((s) => s.setOptimisticProfileForThread); - - useEffect(() => { - let cancelled = false; - if (!sessionId) return; - - const existing = useAgentStore.getState().profileByThreadId[sessionId]; - if (existing && !existing.optimistic) return; - - if (!existing) { - const permissionMode = 'askBeforeExec' as const; - setOptimisticProfileForThread(sessionId, { - activeProfile: storeProfile, - permissionMode, - }); - } - - setLoading(true); - const requestedAt = Date.now(); - fetchProfile(sessionId, cwd) - .then((info) => { - if (cancelled) return; - setProfileForThread(sessionId, { - activeProfile: info.activeProfile, - permissionMode: info.permissionMode, - requestedAt, - }); - }) - .catch((e) => { - if (cancelled) return; - console.error('Failed to fetch session profile:', e); - }) - .finally(() => { - if (cancelled) return; - setLoading(false); - }); - - return () => { - cancelled = true; - }; - }, [ - sessionId, - cwd, - fetchProfile, - storeProfile, - setProfileForThread, - setOptimisticProfileForThread, - ]); - - const current: 'plan' | 'build' = - sessionId === null ? storeProfile : (profile?.activeProfile ?? 'build'); - const target: 'plan' | 'build' = current === 'plan' ? 'build' : 'plan'; - - const handleToggle = async () => { - if (busy) return; - - if (sessionId === null) { - // 还没有会话:改的是 config.yaml 里的 activeProfile - setBusy(true); - try { - const cfg = await setAgentConfig({ activeProfile: target }); - setProfile(cfg.activeProfile); - } catch (e) { - console.error('Failed to save default profile:', e); - } finally { - setBusy(false); - } - return; - } - - setBusy(true); - try { - const result = await switchProfile(sessionId, target, cwd); - setProfileForThread(sessionId, { - activeProfile: result.activeProfile, - permissionMode: result.permissionMode, - }); - } catch (e) { - console.error('Failed to switch profile:', e); - } finally { - setBusy(false); - } - }; - - const meta = PROFILE_META[current]; - const Icon = meta.Icon; - const disabled = sessionId === null ? false : loading || busy; - - return ( - - ); -} diff --git a/packages/desktop/src/hooks/useAgent.ts b/packages/desktop/src/hooks/useAgent.ts index d3af3e69..4133397c 100644 --- a/packages/desktop/src/hooks/useAgent.ts +++ b/packages/desktop/src/hooks/useAgent.ts @@ -4,7 +4,7 @@ import { useWorkspaceStore } from '../stores/workspace.store'; import { useRollbackStore, TURN_SCOPE_REVERTED } from '../stores/rollback.store'; import { agentClient } from '../lib/core-api'; import { createStreamState, reduceFrame, type StreamEffects } from '../lib/frame-reducer'; -import type { PermissionMode, ProfileName } from '@codingcode/sdk'; +import type { PermissionMode } from '@codingcode/sdk'; import { ApiError } from '../lib/api'; import { listModels, @@ -20,9 +20,6 @@ import { rollbackContext, rollbackBothToTurn, forkSession, - getSessionProfile, - setSessionProfile, - getSessionPlan, getAgentConfig as fetchAgentConfig, } from '../lib/core-api'; import type { @@ -94,8 +91,6 @@ export function useAgentCore() { const updateTurnId = useAgentStore((s) => s.updateTurnId); const completeTurn = useAgentStore((s) => s.completeTurn); const setPendingInput = useAgentStore((s) => s.setPendingInput); - const setPendingPlan = useAgentStore((s) => s.setPendingPlan); - const clearPendingPlan = useAgentStore((s) => s.clearPendingPlan); const clearRunningTurns = useAgentStore((s) => s.clearRunningTurns); const applyTodoUpdate = useAgentStore((s) => s.applyTodoUpdate); const setCurrentThread = useAgentStore((s) => s.setCurrentThread); @@ -109,9 +104,7 @@ export function useAgentCore() { const setThreadUsage = useAgentStore((s) => s.setThreadUsage); const workspace = useWorkspaceStore(); const currentThreadId = useAgentStore((s) => s.currentThreadId); - const storeProfile = useAgentStore((s) => s.profile); const storePermissionMode = useAgentStore((s) => s.permissionMode); - const setProfile = useAgentStore((s) => s.setProfile); const setPermissionMode = useAgentStore((s) => s.setPermissionMode); const modelId = useAgentStore((s) => s.model); const queueInput = useAgentStore((s) => s.queueInput); @@ -130,13 +123,12 @@ export function useAgentCore() { useEffect(() => { fetchAgentConfig() .then((cfg) => { - setProfile(cfg.activeProfile); setPermissionMode(cfg.permissionMode); }) .catch((e) => { console.error('Failed to load agent config:', e); }); - }, [setProfile, setPermissionMode]); + }, [setPermissionMode]); // Load sessions, models, and projects on mount useEffect(() => { @@ -299,9 +291,6 @@ export function useAgentCore() { } finally { flushPending(); completeTurn(threadId, activeTurnId, failed || state.hasError ? 'error' : 'completed'); - if (!failed && !state.hasError && state.planTitle !== null) { - setPendingPlan(threadId, { sessionId: threadId, title: state.planTitle }); - } abortAndClear(threadId); // 自动补发:回合结束后按顺序把仍处于 queued 的项逐条发出 void sendQueuedInputRef.current?.(threadId); @@ -313,7 +302,6 @@ export function useAgentCore() { applyChunks, applyTodoUpdate, completeTurn, - setPendingPlan, updateTurnId, setThreadUsage, setContextUsage, @@ -328,9 +316,7 @@ export function useAgentCore() { let resolvedThreadId = currentThreadId; let model = modelId; if (!resolvedThreadId) { - const activeProfile: ProfileName = storeProfile; - const permissionMode: PermissionMode = - activeProfile === 'plan' ? 'askBeforeExec' : storePermissionMode; + const permissionMode: PermissionMode = storePermissionMode; // 新会话用全局配置的模型:以服务端的 activeId 为准,顺带刷新模型列表 try { const data = await listModels(); @@ -347,13 +333,11 @@ export function useAgentCore() { throw new Error('No model selected. Please select a model first.'); } const data = await createServerSession(effectiveCwd, { - activeProfile, permissionMode, model, }); resolvedThreadId = data.sessionId; setCurrentThreadWithProfile(resolvedThreadId, { - activeProfile, permissionMode, model, optimistic: true, @@ -363,16 +347,13 @@ export function useAgentCore() { // 首次发送的防重:已有在飞流时直接忽略 if (inflightControllers.has(threadId)) return; - clearPendingPlan(threadId); await runTurnStream(threadId, parts, { cwd: effectiveCwd, model, skills }); }, [ runTurnStream, setCurrentThreadWithProfile, - clearPendingPlan, workspace.rootPath, - storeProfile, storePermissionMode, modelId, currentThreadId, @@ -416,7 +397,6 @@ export function useAgentCore() { // 无活跃回合:开新回合;乐观 Turn 用 item.parts removeQueuedInput(threadId, item.id); if (inflightControllers.has(threadId)) return; - clearPendingPlan(threadId); registerInflight(threadId, controller); await runTurnStream(threadId, item.parts, { cwd: effectiveCwd, @@ -430,7 +410,6 @@ export function useAgentCore() { markQueueSending, removeQueuedInput, applyChunk, - clearPendingPlan, workspace.rootPath, modelId, ] @@ -728,54 +707,3 @@ export function useAgent() { const rollback = useAgentRollback(); return { ...core, ...approval, ...rollback }; } - -// ---- useAgentProfile: plan/build profile switching + plan file access ---- - -export type SessionProfileSnapshot = { - activeProfile: ProfileName; - permissionMode: PermissionMode; - cwd: string; -}; - -export type PlanFileSnapshot = { - content: string; - path: string; - directory: string; - exists: boolean; -}; - -/** - * Hook for interacting with the plan/build profile of a single session, plus - * reading the persisted plan file. Each call returns a fresh API to the - * server — caching is done in the caller via useEffect / useState. - */ -export function useAgentProfile() { - const workspace = useWorkspaceStore(); - - const fetchProfile = useCallback( - async (sessionId: string, cwd?: string): Promise => { - return getSessionProfile(sessionId, cwd ?? workspace.rootPath ?? ''); - }, - [workspace.rootPath] - ); - - const switchProfile = useCallback( - async ( - sessionId: string, - activeProfile: ProfileName, - cwd?: string - ): Promise<{ activeProfile: ProfileName; permissionMode: PermissionMode }> => { - return setSessionProfile(sessionId, cwd ?? workspace.rootPath ?? '', activeProfile); - }, - [workspace.rootPath] - ); - - const fetchPlan = useCallback( - async (sessionId: string, cwd?: string): Promise => { - return getSessionPlan(sessionId, cwd ?? workspace.rootPath ?? ''); - }, - [workspace.rootPath] - ); - - return { fetchProfile, switchProfile, fetchPlan }; -} diff --git a/packages/desktop/src/lib/core-api.ts b/packages/desktop/src/lib/core-api.ts index 772848e0..317fdf9a 100644 --- a/packages/desktop/src/lib/core-api.ts +++ b/packages/desktop/src/lib/core-api.ts @@ -10,7 +10,6 @@ import { type McpServerConfig, type McpServerEntry, type PermissionMode, - type ProfileName, type RollbackPreviewDiff, type RunAutomationResult, type TokenUsage, @@ -66,7 +65,7 @@ export function listSessions(cwd?: string): Promise { export function createSession( cwd: string, - params: { activeProfile: ProfileName; permissionMode: PermissionMode; model: string } + params: { permissionMode: PermissionMode; model: string } ): Promise<{ sessionId: string }> { return clients.sessions.createSession({ cwd, ...params }); } @@ -117,35 +116,6 @@ export function sendAskUserAnswer( return clients.agent.sendAskUserAnswer({ sessionId, askId: callId, ...answer }); } -// ---- Plan file ---- - -export function getSessionPlan( - sessionId: string, - cwd: string -): Promise<{ content: string; path: string; directory: string; exists: boolean }> { - return clients.sessions.getSessionPlan({ sessionId, cwd }); -} - -// ---- Agent profile switching ---- - -export type SessionProfileInfo = { - activeProfile: ProfileName; - permissionMode: PermissionMode; - cwd: string; -}; - -export function getSessionProfile(sessionId: string, cwd: string): Promise { - return clients.sessions.getSessionProfile({ sessionId, cwd }); -} - -export function setSessionProfile( - sessionId: string, - cwd: string, - activeProfile: ProfileName -): Promise<{ activeProfile: ProfileName; permissionMode: PermissionMode }> { - return clients.sessions.setSessionProfile({ sessionId, cwd, activeProfile }); -} - // ---- Settings: Memory ---- export function getMemoryConfig(): Promise<{ @@ -172,7 +142,6 @@ export function getAgentConfig(): Promise { export function setAgentConfig(partial: { maxSteps?: number; maxStopContinuations?: number; - activeProfile?: ProfileName; permissionMode?: PermissionMode; }): Promise { return clients.settings.setAgentConfig(partial); diff --git a/packages/desktop/src/lib/frame-reducer.ts b/packages/desktop/src/lib/frame-reducer.ts index 4834da7e..70f0712f 100644 --- a/packages/desktop/src/lib/frame-reducer.ts +++ b/packages/desktop/src/lib/frame-reducer.ts @@ -7,7 +7,6 @@ export interface StreamState { reasoningText: string; roundHasText: boolean; hasError: boolean; - planTitle: string | null; turnIdSynced: boolean; } @@ -18,7 +17,6 @@ export function createStreamState(assistantMessageId: string): StreamState { reasoningText: '', roundHasText: false, hasError: false, - planTitle: null, turnIdSynced: false, }; } @@ -127,9 +125,6 @@ export function reduceFrame(frame: Frame, state: StreamState, fx: StreamEffects) }); return; case 'tool_call': - if (e.name === 'submit_plan') { - state.planTitle = String((e.args as Record).title ?? ''); - } fx.applyItem({ id: e.id, type: 'tool_call', @@ -172,7 +167,6 @@ export function reduceFrame(frame: Frame, state: StreamState, fx: StreamEffects) fx.onInputDelivered?.(e.id); return; case 'tool_result': { - if (e.name === 'submit_plan' && e.outcome.status !== 'ok') state.planTitle = null; if (e.name === 'ask_user') fx.markAskAnswered?.(e.id); if (e.outcome.status === 'denied') { fx.applyItem({ id: e.id, type: 'tool_call', name: e.name, args: (e as any).args ?? {}, status: 'rejected' }); diff --git a/packages/desktop/src/shared/PlanDecisionModal.tsx b/packages/desktop/src/shared/PlanDecisionModal.tsx deleted file mode 100644 index 0b28a323..00000000 --- a/packages/desktop/src/shared/PlanDecisionModal.tsx +++ /dev/null @@ -1,127 +0,0 @@ -import { useState, useCallback } from 'react'; -import { X, Check, Pencil, Ban } from 'lucide-react'; - -export interface PlanDecisionModalProps { - title?: string; - sessionId?: string; - onImplement: () => void; - onSubmitOpinion: (opinion: string) => void; - onCancel: () => void; -} - -type Submitting = null | 'implement' | 'opinion' | 'cancel'; - -export default function PlanDecisionModal({ - title, - sessionId, - onImplement, - onSubmitOpinion, - onCancel, -}: PlanDecisionModalProps) { - const [opinion, setOpinion] = useState(''); - const [submitting, setSubmitting] = useState(null); - - const opinionEmpty = opinion.trim() === ''; - - const handleImplement = useCallback(() => { - if (submitting) return; - setSubmitting('implement'); - onImplement(); - }, [onImplement, submitting]); - - const handleSubmitOpinion = useCallback(() => { - if (submitting || opinionEmpty) return; - setSubmitting('opinion'); - onSubmitOpinion(opinion); - }, [onSubmitOpinion, opinion, opinionEmpty, submitting]); - - const handleCancel = useCallback(() => { - if (submitting) return; - setSubmitting('cancel'); - onCancel(); - }, [onCancel, submitting]); - - return ( -
-
e.stopPropagation()} - > -
- 计划已提交 - {title && ( - · {title} - )} - {sessionId && ( - - 会话 {sessionId.slice(0, 8)} - - )} - -
- -
- 模型已把实现方案通过 submit_plan 保存。计划全文在上方对话中,决定如何处理: -
- -
-