Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(lite): ask before host deletes and widen the sandbox on approval (#4076)
nullptr-error256a3f296686
diff --git a/frontend/src/api/mcp-service.ts b/frontend/src/api/mcp-service.tsindex 1563bd03a..d43776de5 100644--- a/frontend/src/api/mcp-service.ts+++ b/frontend/src/api/mcp-service.ts@@ -291,7 +291,14 @@ export async function revokeMCPOAuthToken(serviceId: string): Promise<void> {export async function resolveToolApproval(pendingId: string,- body: { decision: 'approve' | 'reject'; modified_args?: Record<string, unknown>; reason?: string; allow_in_session?: boolean }+ body: {+ decision: 'approve' | 'reject'+ modified_args?: Record<string, unknown>+ reason?: string+ allow_in_session?: boolean+ scope?: 'once' | 'session'+ access?: 'read' | 'write'+ }): Promise<{ resumed: boolean }> {const res: any = await post(`/api/v1/agent/tool-approvals/${encodeURIComponent(pendingId)}`, body)// resumed: the run had been suspended and now continues on the server;diff --git a/frontend/src/composables/useChatStreamHandler.collaboration.test.ts b/frontend/src/composables/useChatStreamHandler.collaboration.test.tsindex 2537d6c17..7d5bed33e 100644--- a/frontend/src/composables/useChatStreamHandler.collaboration.test.ts+++ b/frontend/src/composables/useChatStreamHandler.collaboration.test.ts@@ -9,6 +9,7 @@ import * as history from '../utils/rag-pipeline-history.ts'import * as timestamps from '../utils/messageTimestamp.ts'import * as steering from '../utils/steerStreamFork.ts'import * as dataChange from '../utils/assistantDataChange.ts'+import * as hostApproval from '../views/chat/components/hostApproval.ts'import type { useChatStreamHandler as StreamHandler } from './useChatStreamHandler.ts'const source = readFileSync(new URL('./useChatStreamHandler.ts', import.meta.url), 'utf8')@@ -22,6 +23,7 @@ const modules: Record<string, unknown> = {'@/utils/messageTimestamp': timestamps,'@/utils/steerStreamFork': steering,'@/utils/assistantDataChange': dataChange,+ '@/views/chat/components/hostApproval': hostApproval,}const exports: { useChatStreamHandler?: typeof StreamHandler } = {}vm.runInNewContext(compiled, {diff --git a/frontend/src/composables/useChatStreamHandler.dataChange.test.ts b/frontend/src/composables/useChatStreamHandler.dataChange.test.tsindex 71822f122..68c56bc26 100644--- a/frontend/src/composables/useChatStreamHandler.dataChange.test.ts+++ b/frontend/src/composables/useChatStreamHandler.dataChange.test.ts@@ -6,6 +6,7 @@ import * as finalContent from '../utils/finalArtifactContent.ts'import * as history from '../utils/rag-pipeline-history.ts'import * as timestamps from '../utils/messageTimestamp.ts'import * as steering from '../utils/steerStreamFork.ts'+import * as hostApproval from '../views/chat/components/hostApproval.ts'import { change, fixture } from '../test-utils/vueFixture.ts'function setup(t: TestContext) {@@ -19,6 +20,7 @@ function setup(t: TestContext) {'@/utils/messageTimestamp': timestamps,'@/utils/steerStreamFork': steering,'@/utils/assistantDataChange': f.dataChange,+ '@/views/chat/components/hostApproval': hostApproval,})const handler = useChatStreamHandler({messagesList: vue.reactive([]), loading: vue.ref(false), isReplying: vue.ref(false),diff --git a/frontend/src/composables/useChatStreamHandler.integration.test.ts b/frontend/src/composables/useChatStreamHandler.integration.test.tsindex 0ed113541..6d91bb309 100644--- a/frontend/src/composables/useChatStreamHandler.integration.test.ts+++ b/frontend/src/composables/useChatStreamHandler.integration.test.ts@@ -9,6 +9,7 @@ import * as history from '../utils/rag-pipeline-history.ts'import * as timestamps from '../utils/messageTimestamp.ts'import * as steering from '../utils/steerStreamFork.ts'import * as dataChange from '../utils/assistantDataChange.ts'+import * as hostApproval from '../views/chat/components/hostApproval.ts'import { useProtectedImageRecovery } from './useProtectedImageRecovery.ts'import { clearProtectedFileFailureCache, hydrateProtectedFileImages } from '../utils/security.ts'import { setDefaultProtectedFileAccess } from '../utils/protectedFileAccess.ts'@@ -27,6 +28,7 @@ const modules: Record<string, unknown> = {'@/utils/messageTimestamp': timestamps,'@/utils/steerStreamFork': steering,'@/utils/assistantDataChange': dataChange,+ '@/views/chat/components/hostApproval': hostApproval,}const exports: { useChatStreamHandler?: typeof StreamHandler } = {}vm.runInNewContext(compiled, {@@ -151,6 +153,27 @@ for (const mode of ['ordinary', 'quick-timeline', 'agent'] as const) {})}+test('a live host approval reaches the composer while the tool is still running', async t => {+ const h = setup(t, 'agent')+ hostApproval.clearComposerApproval()+ h.send('tool_call', '', false, { tool_call_id: 'call-1', tool_name: 'shell_exec', arguments: { command: 'rm a.txt' } })+ h.send('tool_approval_required', 'MCP tool requires human approval', true, {+ pending_id: 'pending-1', kind: 'host_command', tool_call_id: 'call-1',+ host: { reason: 'delete', command: 'rm a.txt', allow_session: true },+ })+ await h.flush()+ assert.equal(hostApproval.pendingComposerApprovals.value[0]?.pending_id, 'pending-1')+ h.send('tool_approval_required', 'MCP tool requires human approval', true, {+ pending_id: 'pending-2', kind: 'host_command', tool_call_id: 'call-2',+ host: { reason: 'delete', command: 'rm b.txt', allow_session: true },+ })+ await h.flush()+ assert.deepEqual(hostApproval.pendingComposerApprovals.value.map((item) => item.pending_id), ['pending-1', 'pending-2'])+ h.send('tool_approval_resolved', '', true, { pending_id: 'pending-1', approved: true, scope: 'once' })+ await h.flush()+ assert.deepEqual(hostApproval.pendingComposerApprovals.value.map((item) => item.pending_id), ['pending-2'])+})+test('ordinary completion waits for the buffered typewriter before recovering images', async t => {const h = setup(t, 'ordinary')h.revealed.value = 0diff --git a/frontend/src/composables/useChatStreamHandler.pageButton.test.ts b/frontend/src/composables/useChatStreamHandler.pageButton.test.tsindex bb4ac376b..23c8a3492 100644--- a/frontend/src/composables/useChatStreamHandler.pageButton.test.ts+++ b/frontend/src/composables/useChatStreamHandler.pageButton.test.ts@@ -6,6 +6,7 @@ import * as finalContent from '../utils/finalArtifactContent.ts'import * as history from '../utils/rag-pipeline-history.ts'import * as timestamps from '../utils/messageTimestamp.ts'import * as steering from '../utils/steerStreamFork.ts'+import * as hostApproval from '../views/chat/components/hostApproval.ts'import { fixture } from '../test-utils/vueFixture.ts'function setup(t: TestContext) {@@ -17,6 +18,7 @@ function setup(t: TestContext) {'@/utils/messageTimestamp': timestamps,'@/utils/steerStreamFork': steering,'@/utils/assistantDataChange': f.dataChange,+ '@/views/chat/components/hostApproval': hostApproval,})const messagesList = vue.reactive<any[]>([])const handler = useChatStreamHandler({diff --git a/frontend/src/composables/useChatStreamHandler.suspend.test.ts b/frontend/src/composables/useChatStreamHandler.suspend.test.tsindex 50f3492f1..6e0510918 100644--- a/frontend/src/composables/useChatStreamHandler.suspend.test.ts+++ b/frontend/src/composables/useChatStreamHandler.suspend.test.ts@@ -9,6 +9,7 @@ import * as history from '../utils/rag-pipeline-history.ts'import * as timestamps from '../utils/messageTimestamp.ts'import * as steering from '../utils/steerStreamFork.ts'import * as dataChange from '../utils/assistantDataChange.ts'+import * as hostApproval from '../views/chat/components/hostApproval.ts'import type { useChatStreamHandler as StreamHandler } from './useChatStreamHandler.ts'const source = readFileSync(new URL('./useChatStreamHandler.ts', import.meta.url), 'utf8')@@ -22,6 +23,7 @@ const modules: Record<string, unknown> = {'@/utils/messageTimestamp': timestamps,'@/utils/steerStreamFork': steering,'@/utils/assistantDataChange': dataChange,+ '@/views/chat/components/hostApproval': hostApproval,}const exports: { useChatStreamHandler?: typeof StreamHandler } = {}vm.runInNewContext(compiled, {diff --git a/frontend/src/composables/useChatStreamHandler.ts b/frontend/src/composables/useChatStreamHandler.tsindex b4cf1fe64..e38254112 100644--- a/frontend/src/composables/useChatStreamHandler.ts+++ b/frontend/src/composables/useChatStreamHandler.ts@@ -1,4 +1,5 @@import { emitAssistantDataChange } from '@/utils/assistantDataChange'+import { approvalEventFromRecord, clearComposerApproval, showComposerApproval } from '@/views/chat/components/hostApproval'import { applyFinalArtifactContent } from '@/utils/finalArtifactContent'import { markRaw, nextTick, type Ref } from 'vue'import { useI18n } from 'vue-i18n'@@ -528,6 +529,11 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {})}+ const approvals = Array.isArray(step.approvals) ? step.approvals as ChatMessage[] : []+ approvals.forEach((record) => {+ events.push(approvalEventFromRecord(record))+ })+if (toolCalls && Array.isArray(toolCalls)) {toolCalls.forEach((toolCall: ChatMessage) => {if (toolCall.name === 'final_answer') return@@ -989,7 +995,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {if (!message.agentEventStream) message.agentEventStream = []const d = dataPayload || {}if (turnPromptEvents().some(e => e.pending_id === d.pending_id)) break- ;(message.agentEventStream as ChatMessage[]).push({+ const approvalEvent = {type: 'tool_approval_required',pending_id: d.pending_id,service_name: d.service_name,@@ -1006,8 +1012,18 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {expires_at: d.expires_at,requested_at: d.requested_at,tool_call_id: d.tool_call_id,+ kind: d.kind,+ host: d.host,resolved: false,- })+ }+ // Replace the array. A markRaw stream ignores push, so the open chat+ // stayed on "running" until a session reload rebuilt it.+ message.agentEventStream = [+ ...(message.agentEventStream as ChatMessage[]),+ approvalEvent,+ ]+ message.pendingHostApproval = approvalEvent+ showComposerApproval(approvalEvent)break}case 'agent_prompt_required': {@@ -1080,7 +1096,14 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {ev.resolve_reason = d.reasonev.timed_out = d.timed_outev.canceled = d.canceled+ ev.resolve_scope = d.scope+ message.agentEventStream = [...(message.agentEventStream as ChatMessage[])]+ }+ const pending = message.pendingHostApproval as { pending_id?: string } | undefined+ if (pending && pending.pending_id === pid) {+ message.pendingHostApproval = null}+ clearComposerApproval(typeof pid === 'string' ? pid : undefined)break}case 'mcp_oauth_required': {@@ -1651,7 +1674,11 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {data.response_type === 'run_suspended' ||data.response_type === 'run_resumed' ||data.response_type === 'agent_prompt_required' ||- data.response_type === 'agent_prompt_resolved'+ data.response_type === 'agent_prompt_resolved' ||+ data.response_type === 'tool_approval_required' ||+ data.response_type === 'tool_approval_resolved' ||+ data.response_type === 'mcp_oauth_required' ||+ data.response_type === 'mcp_oauth_resolved'const activeAssistant = getTrailingIncompleteAssistant()const isCurrentlyAgentMode = activeAssistant?.isAgentMode === truediff --git a/frontend/src/composables/useChildAgentStream.test.ts b/frontend/src/composables/useChildAgentStream.test.tsindex fad7c13b2..99b7246cd 100644--- a/frontend/src/composables/useChildAgentStream.test.ts+++ b/frontend/src/composables/useChildAgentStream.test.ts@@ -10,6 +10,7 @@ import * as history from '../utils/rag-pipeline-history.ts'import * as timestamps from '../utils/messageTimestamp.ts'import * as steering from '../utils/steerStreamFork.ts'import * as dataChange from '../utils/assistantDataChange.ts'+import * as hostApproval from '../views/chat/components/hostApproval.ts'import type { useChatStreamHandler as StreamHandler } from './useChatStreamHandler.ts'const source = readFileSync(new URL('./useChatStreamHandler.ts', import.meta.url), 'utf8')@@ -23,6 +24,7 @@ const modules: Record<string, unknown> = {'@/utils/messageTimestamp': timestamps,'@/utils/steerStreamFork': steering,'@/utils/assistantDataChange': dataChange,+ '@/views/chat/components/hostApproval': hostApproval,}const exports: { useChatStreamHandler?: typeof StreamHandler } = {}vm.runInNewContext(compiled, {diff --git a/frontend/src/composables/usePromptDock.test.mjs b/frontend/src/composables/usePromptDock.test.mjsindex dc65c14ef..1c101c5a9 100644--- a/frontend/src/composables/usePromptDock.test.mjs+++ b/frontend/src/composables/usePromptDock.test.mjs@@ -17,6 +17,9 @@ const modules = {'@/composables/useChatStreamHandler': {isAwaitingInput: (m) => m?.run_state === 'awaiting_input',},+ '@/views/chat/components/hostApproval': {+ isHostApprovalEvent: (e) => e?.kind === 'host_command' || e?.host != null,+ },}const exports = {}vm.runInNewContext(compiled, {@@ -49,6 +52,16 @@ test('docks the open prompts of streaming and suspended runs, oldest first', ()assert.deepEqual(ids(prompts), ['a', 'b', 'c'])})+test('leaves Lite host approvals to the composer card', () => {+ const prompts = pendingPrompts([{+ role: 'assistant', is_completed: false, agentEventStream: [+ approval('host', { kind: 'host_command', host: { command: 'rm a' } }),+ approval('mcp'),+ ],+ }])+ assert.deepEqual(ids(prompts), ['mcp'])+})+test('leaves settled runs, resolved prompts and unknown kinds in the timeline', () => {const prompts = pendingPrompts([{ role: 'assistant', is_completed: true, agentEventStream: [approval('settled')] },diff --git a/frontend/src/composables/usePromptDock.ts b/frontend/src/composables/usePromptDock.tsindex 4131d17e7..a66bc1564 100644--- a/frontend/src/composables/usePromptDock.ts+++ b/frontend/src/composables/usePromptDock.ts@@ -1,6 +1,7 @@import { computed, inject, provide, reactive, ref, type ComputedRef, type InjectionKey, type Ref } from 'vue'import { isAwaitingInput } from '@/composables/useChatStreamHandler'import { persistedAssistantId } from '@/utils/steerStreamFork'+import { isHostApprovalEvent } from '@/views/chat/components/hostApproval'type PromptEvent = Record<string, any>type ChatRow = Record<string, unknown>@@ -23,6 +24,8 @@ export function promptSubmission(pendingId: string): Record<string, unknown> | ufunction isDockable(e: PromptEvent): boolean {if (!DOCKED_TYPES.has(String(e?.type || '')) || e.resolved || !e.pending_id) return false+ // Lite host commands use the composer card, which shows the command and grant.+ if (e.type === 'tool_approval_required' && isHostApprovalEvent(e)) return falseif (e.type === 'agent_prompt_required' && e.kind !== 'ask_user') return falseif (submissions.has(e.pending_id)) return falseif (e.suspended && e.expires_at) {diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex ce625dd3f..04d488dd4 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -7165,6 +7165,29 @@ export default {indexSep: ', '}},+ hostApproval: {+ titleDelete: 'Confirm before deleting files',+ titleDangerous: 'Confirm a dangerous operation',+ titleDenied: 'The sandbox blocked this command; it needs access to',+ titleGeneric: 'Needs your confirmation',+ command: 'Command',+ cwd: 'Directory',+ grantPath: 'Needs access to',+ accessWrite: 'Read and write',+ accessRead: 'Read only',+ firstAttemptRan: 'This command already ran once and failed. Approving runs the whole command again.',+ snippet: 'Block details',+ sessionRules: 'If allowed for this session, these deletes in this directory are not asked again (file names may differ)',+ reject: 'Reject',+ approveOnce: 'Allow once',+ approveSession: 'Allow for this session',+ approvedOnce: 'Allowed once',+ approvedSession: 'Allowed for this session',+ rejectedTag: 'Rejected',+ submitted: 'Submitted',+ submitFailed: 'Submission failed',+ userRejected: 'Rejected by user'+ },mcpOAuth: {waiting: 'Awaiting authorization · {target}',waitingStatus: 'Awaiting authorization',diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.tsindex c630009e7..fccad85d5 100644--- a/frontend/src/i18n/locales/ja-JP.ts+++ b/frontend/src/i18n/locales/ja-JP.ts@@ -7165,6 +7165,29 @@ export default {indexSep: '、'}},+ hostApproval: {+ titleDelete: 'ファイルを削除する前に確認してください',+ titleDangerous: '危険な操作の確認',+ titleDenied: 'サンドボックスがこのコマンドを拒否しました。次のディレクトリへのアクセスが必要です',+ titleGeneric: '確認が必要です',+ command: 'コマンド',+ cwd: 'ディレクトリ',+ grantPath: 'アクセス先',+ accessWrite: '読み書き',+ accessRead: '読み取り専用',+ firstAttemptRan: 'このコマンドは一度実行して失敗しています。承認するとコマンド全体が再実行されます',+ snippet: '拒否の詳細',+ sessionRules: 'このセッションで許可すると、このディレクトリでの次の削除は再確認しません(ファイル名は異なっても可)',+ reject: '拒否',+ approveOnce: '今回のみ許可',+ approveSession: 'このセッションでは許可',+ approvedOnce: '今回のみ許可しました',+ approvedSession: 'このセッションでは許可済み',+ rejectedTag: '拒否済み',+ submitted: '送信しました',+ submitFailed: '送信に失敗しました',+ userRejected: 'ユーザーが拒否しました'+ },mcpOAuth: {waiting: '認可待ち · {target}',waitingStatus: '認可待ち',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 2f7e76d22..b26e90378 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -2495,6 +2495,29 @@ export default {smartReasoning: '스마트 추론',indexSep: ', '}+ },+ hostApproval: {+ titleDelete: '파일을 삭제하기 전에 확인이 필요합니다',+ titleDangerous: '위험한 작업 확인',+ titleDenied: '샌드박스가 이 명령을 차단했습니다. 다음 디렉터리에 대한 접근이 필요합니다',+ titleGeneric: '확인이 필요합니다',+ command: '명령',+ cwd: '디렉터리',+ grantPath: '접근이 필요한 경로',+ accessWrite: '읽기 및 쓰기',+ accessRead: '읽기 전용',+ firstAttemptRan: '이 명령은 이미 한 번 실행되어 실패했습니다. 승인하면 명령 전체가 다시 실행됩니다',+ snippet: '차단 상세',+ sessionRules: '이 세션에서 허용하면 이 디렉터리의 다음 삭제는 다시 묻지 않습니다(파일 이름은 달라도 됨)',+ reject: '거부',+ approveOnce: '한 번만 허용',+ approveSession: '이 세션에서 허용',+ approvedOnce: '한 번 허용됨',+ approvedSession: '이 세션에서 허용됨',+ rejectedTag: '거부됨',+ submitted: '제출됨',+ submitFailed: '제출 실패',+ userRejected: '사용자가 거부함'}},kbSettings: {diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 9da87388c..f98b670b9 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -2495,6 +2495,29 @@ export default {smartReasoning: 'Умное рассуждение',indexSep: ', '}+ },+ hostApproval: {+ titleDelete: 'Подтвердите удаление файлов',+ titleDangerous: 'Подтвердите опасную операцию',+ titleDenied: 'Песочница заблокировала команду; нужен доступ к каталогу',+ titleGeneric: 'Нужно ваше подтверждение',+ command: 'Команда',+ cwd: 'Каталог',+ grantPath: 'Нужен доступ к',+ accessWrite: 'Чтение и запись',+ accessRead: 'Только чтение',+ firstAttemptRan: 'Команда уже выполнялась и завершилась с ошибкой. После разрешения она будет выполнена целиком ещё раз',+ snippet: 'Подробности блокировки',+ sessionRules: 'Если разрешить для сеанса, такие удаления в этой папке больше не будут запрашиваться (имена файлов могут отличаться)',+ reject: 'Отклонить',+ approveOnce: 'Разрешить один раз',+ approveSession: 'Разрешить в этом сеансе',+ approvedOnce: 'Разрешено один раз',+ approvedSession: 'Разрешено в этом сеансе',+ rejectedTag: 'Отклонено',+ submitted: 'Отправлено',+ submitFailed: 'Не удалось отправить',+ userRejected: 'Отклонено пользователем'}},kbSettings: {diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 23c091012..8cdfb17ba 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -2497,6 +2497,29 @@ export default {smartReasoning: '智能推理',indexSep: '、'}+ },+ hostApproval: {+ titleDelete: '删除文件前需要你确认',+ titleDangerous: '危险操作确认',+ titleDenied: '命令被沙盒拦截,需要访问以下目录',+ titleGeneric: '需要你确认',+ command: '命令',+ cwd: '目录',+ grantPath: '需要访问',+ accessWrite: '读写',+ accessRead: '只读',+ firstAttemptRan: '这条命令已经执行过一次并失败,批准后会整条重新执行',+ snippet: '拦截详情',+ sessionRules: '本会话允许后,同目录下这类删除不再询问(文件名可以不同)',+ reject: '拒绝',+ approveOnce: '允许一次',+ approveSession: '本会话允许',+ approvedOnce: '已允许一次',+ approvedSession: '本会话已允许',+ rejectedTag: '已拒绝',+ submitted: '已提交',+ submitFailed: '提交失败',+ userRejected: '用户拒绝'}},kbSettings: {diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.tsindex 6e68d831b..59493dca7 100644--- a/frontend/src/i18n/locales/zh-TW.ts+++ b/frontend/src/i18n/locales/zh-TW.ts@@ -2497,6 +2497,29 @@ export default {smartReasoning: '智能推理',indexSep: '、'}+ },+ hostApproval: {+ titleDelete: '刪除檔案前需要你確認',+ titleDangerous: '危險操作確認',+ titleDenied: '命令被沙盒攔截,需要存取以下目錄',+ titleGeneric: '需要你確認',+ command: '命令',+ cwd: '目錄',+ grantPath: '需要存取',+ accessWrite: '讀寫',+ accessRead: '唯讀',+ firstAttemptRan: '這條命令已經執行過一次並失敗,批准後會整條重新執行',+ snippet: '攔截詳情',+ sessionRules: '本工作階段允許後,同目錄下這類刪除不再詢問(檔名可以不同)',+ reject: '拒絕',+ approveOnce: '允許一次',+ approveSession: '本工作階段允許',+ approvedOnce: '已允許一次',+ approvedSession: '本工作階段已允許',+ rejectedTag: '已拒絕',+ submitted: '已提交',+ submitFailed: '提交失敗',+ userRejected: '使用者拒絕'}},kbSettings: {diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.progress.test.ts b/frontend/src/views/chat/components/AgentStreamDisplay.progress.test.tsindex b493390a7..fa00b5976 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.progress.test.ts+++ b/frontend/src/views/chat/components/AgentStreamDisplay.progress.test.ts@@ -28,6 +28,12 @@ test('delegated work keeps progress and approvals in one chronological stream ancomputed, props: { ragMode: false }, hasCollaborationTasks: delegated, showIntermediateSteps: expanded,eventStream: stream, isConversationDone: done, intermediateStepsCount: ref(2), readingHistory, timelineCompleted: useDeferredTimelineCompletion(done, readingHistory),buildFullEventList: foldProgressIntoThinking, finalContent: ref(null),+ hideApprovalFromTimeline: (event: { type?: string; kind?: string; host?: unknown; resolved?: boolean }) => {+ if (event?.type === 'tool_approval_resolved') return true+ if (event?.type !== 'tool_approval_required') return false+ const host = event.kind === 'host_command' || event.host != null+ return host && !event.resolved+ },})for (const hasChildren of [false, true]) {delegated.value = hasChildrendiff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vueindex b3844bde7..4b0bcd14b 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -120,7 +120,7 @@</div><!-- MCP tool human approval (issue #1173) -->- <div v-else-if="event.type === 'tool_approval_required'" class="tool-event">+ <div v-else-if="event.type === 'tool_approval_required' && showInlineToolApproval(event)" class="tool-event"><ToolApprovalCard :pending-id="event.pending_id" :delegated-task="event.delegated_task" :service-name="event.service_name || ''":mcp-tool-name="event.mcp_tool_name || ''" :description="event.description":args-json="event.args_json" :grant-scope="event.grant_scope" :grant-lapsed="event.grant_lapsed" :timeout-seconds="event.timeout_seconds"@@ -150,6 +150,22 @@v-bind="embedAuthProps" /></div>+ <div v-else-if="showInlineHostApproval(event)" class="tool-event">+ <HostApprovalCard :pending-id="event.pending_id"+ :host="event.host || { reason: event.kind === 'host_command' ? 'delete' : '' }"+ :timeout-seconds="event.timeout_seconds" :requested-at="event.requested_at"+ :resolved="event.resolved" :approved="event.approved"+ :resolve-reason="event.resolve_reason" :resolve-scope="event.resolve_scope" />+ </div>++ <div v-else-if="showInlineToolApproval(event)" class="tool-event">+ <ToolApprovalCard :pending-id="event.pending_id" :service-name="event.service_name || ''"+ :mcp-tool-name="event.mcp_tool_name || ''" :description="event.description"+ :args-json="event.args_json" :timeout-seconds="event.timeout_seconds"+ :requested-at="event.requested_at" :resolved="event.resolved" :approved="event.approved"+ :resolve-reason="event.resolve_reason" v-bind="embedAuthProps" />+ </div>+<!-- Tool Call Event (non-thinking) --><div v-else-if="event.type === 'tool_call'" class="tool-event"><div class="action-card" :class="{@@ -399,7 +415,7 @@</div><!-- MCP tool human approval -->- <div v-else-if="event.type === 'tool_approval_required'" class="tool-event">+ <div v-else-if="event.type === 'tool_approval_required' && showInlineToolApproval(event)" class="tool-event"><ToolApprovalCard :pending-id="event.pending_id" :delegated-task="event.delegated_task" :service-name="event.service_name || ''":mcp-tool-name="event.mcp_tool_name || ''" :description="event.description" :args-json="event.args_json":grant-scope="event.grant_scope" :grant-lapsed="event.grant_lapsed" :timeout-seconds="event.timeout_seconds" :requested-at="event.requested_at" :resolved="event.resolved"@@ -427,6 +443,22 @@:canceled="event.canceled" v-bind="embedAuthProps" /></div>+ <div v-else-if="showInlineHostApproval(event)" class="tool-event">+ <HostApprovalCard :pending-id="event.pending_id"+ :host="event.host || { reason: event.kind === 'host_command' ? 'delete' : '' }"+ :timeout-seconds="event.timeout_seconds" :requested-at="event.requested_at"+ :resolved="event.resolved" :approved="event.approved"+ :resolve-reason="event.resolve_reason" :resolve-scope="event.resolve_scope" />+ </div>++ <div v-else-if="showInlineToolApproval(event)" class="tool-event">+ <ToolApprovalCard :pending-id="event.pending_id" :service-name="event.service_name || ''"+ :mcp-tool-name="event.mcp_tool_name || ''" :description="event.description"+ :args-json="event.args_json" :timeout-seconds="event.timeout_seconds"+ :requested-at="event.requested_at" :resolved="event.resolved" :approved="event.approved"+ :resolve-reason="event.resolve_reason" v-bind="embedAuthProps" />+ </div>+<!-- Thinking Tool Call --><div v-else-if="event.type === 'tool_call' && event.tool_name === 'thinking'" class="tool-event"><div class="action-card"@@ -756,6 +788,8 @@ import { isAssistantPageLink } from '@/utils/assistantPageLink';import AskUserCard from './AskUserCard.vue';import ChatActionIcon from '@/components/ChatActionIcon.vue';import ChatTimelineIcon from '@/components/ChatTimelineIcon.vue';+import HostApprovalCard from './HostApprovalCard.vue';+import { isHostApprovalEvent } from './hostApproval';import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';import ChatCitationFloat from '@/components/ChatCitationFloat.vue';import picturePreview from '@/components/picture-preview.vue';@@ -1178,6 +1212,9 @@ const props = defineProps<{followUpLoading?: boolean;canFork?: boolean;canRewind?: boolean;+ // The main chat draws the approval above the composer. Embed and skill+ // install have no composer slot, so they render the MCP card inline.+ deferToolApprovals?: boolean;}>();const emit = defineEmits<{@@ -1208,6 +1245,28 @@ const embedAuthProps = computed(() => ({embedVisitorId: props.embedVisitorId,}));+// Host command cards stay above the chat composer. MCP cards render here+// unless that composer is already showing them.+const approvalEvent = (event: { type?: string; kind?: string; host?: unknown; resolved?: boolean }) =>+ event?.type === 'tool_approval_required';++// Pending host cards sit above the composer. A resolved approval stays in the+// timeline so the turn still shows what was allowed or refused.+const showInlineHostApproval = (event: { type?: string; kind?: string; host?: unknown; resolved?: boolean }) =>+ approvalEvent(event) && isHostApprovalEvent(event) && !!event.resolved;++const showInlineToolApproval = (event: { type?: string; kind?: string; host?: unknown; resolved?: boolean }) => {+ if (!approvalEvent(event) || isHostApprovalEvent(event)) return false;+ if (event.resolved) return true;+ return !props.deferToolApprovals;+};++const hideApprovalFromTimeline = (event: { type?: string; kind?: string; host?: unknown; resolved?: boolean }) => {+ if (event?.type === 'tool_approval_resolved') return true;+ if (!approvalEvent(event)) return false;+ return !showInlineHostApproval(event) && !showInlineToolApproval(event);+};+const showRequestInfo = computed(() => !props.embeddedMode && !!(props.session?.request_id || props.session?.id),);@@ -2237,6 +2296,7 @@ const intermediateEvents = computed(() => {const hidden = hiddenThinkingEventIds.value;return result.filter((e: any) => {if (e.type === 'answer' || e.type === 'agent_complete') return false;+ if (hideApprovalFromTimeline(e)) return false;// Mid-run injected user messages render as normal user bubbles in the// message list, not inside the steps tree — the tree template has no// branch for this type and would otherwise emit an empty node.@@ -2266,7 +2326,7 @@ const displayEvents = computed(() => {// Injected user messages render as normal user bubbles in the message// list — never inside the agent timeline (the template has no branch for// the type and would render an empty card).- (e: any) => e.type !== 'user_message_injected',+ (e: any) => e.type !== 'user_message_injected' && !hideApprovalFromTimeline(e),);// Quick-answer RAG: pipeline steps (including attachment prep) live indiff --git a/frontend/src/views/chat/components/HostApprovalCard.vue b/frontend/src/views/chat/components/HostApprovalCard.vuenew file mode 100644index 000000000..8064887e5--- /dev/null+++ b/frontend/src/views/chat/components/HostApprovalCard.vue@@ -0,0 +1,296 @@+<template>+ <div class="host-approval" :class="{ 'is-dangerous': host.reason === 'dangerous', 'is-resolved': resolved }">+ <div class="host-approval__header">+ <t-icon class="host-approval__icon" :name="headerIcon" />+ <span class="host-approval__title">{{ $t(titleKey) }}</span>+ <span v-if="!resolved && secondsLeft >= 0" class="host-approval__timer" :class="timerClass">+ {{ formatCountdown(secondsLeft) }}+ </span>+ <span v-else-if="resolved" class="host-approval__status">{{ statusLine }}</span>+ </div>++ <div class="host-approval__body">+ <div class="host-approval__label">{{ $t('agentStream.hostApproval.command') }}</div>+ <pre class="host-approval__code">{{ host.command }}</pre>+ <div v-if="host.cwd" class="host-approval__meta">+ {{ $t('agentStream.hostApproval.cwd') }}:<code>{{ host.cwd }}</code>+ </div>++ <template v-if="host.grant_path">+ <div class="host-approval__label">{{ $t('agentStream.hostApproval.grantPath') }}</div>+ <pre class="host-approval__code">{{ host.grant_path }}</pre>+ <t-radio-group v-if="!resolved && canNarrowAccess(host)" v-model="access" variant="default-filled" size="small">+ <t-radio-button value="write">{{ $t('agentStream.hostApproval.accessWrite') }}</t-radio-button>+ <t-radio-button value="read">{{ $t('agentStream.hostApproval.accessRead') }}</t-radio-button>+ </t-radio-group>+ </template>++ <div v-if="host.first_attempt_ran && !resolved" class="host-approval__notice">+ <t-icon name="info-circle" />+ <span>{{ $t('agentStream.hostApproval.firstAttemptRan') }}</span>+ </div>++ <template v-if="!resolved && sessionRules.length">+ <div class="host-approval__label">{{ $t('agentStream.hostApproval.sessionRules') }}</div>+ <pre class="host-approval__code is-muted">{{ sessionRules.join('\n') }}</pre>+ </template>++ <template v-if="host.denial_snippet">+ <button type="button" class="host-approval__toggle" @click="snippetExpanded = !snippetExpanded">+ <t-icon :name="snippetExpanded ? 'chevron-down' : 'chevron-right'" />+ {{ $t('agentStream.hostApproval.snippet') }}+ </button>+ <pre v-if="snippetExpanded" class="host-approval__code is-muted">{{ host.denial_snippet }}</pre>+ </template>+ </div>++ <div v-if="!resolved" class="host-approval__actions">+ <t-button variant="outline" :disabled="submitting" @click="submit('reject', 'once')">+ {{ $t('agentStream.hostApproval.reject') }}+ </t-button>+ <t-button v-if="host.allow_session" variant="outline" theme="primary" :disabled="submitting"+ @click="submit('approve', 'session')">+ {{ $t('agentStream.hostApproval.approveSession') }}+ </t-button>+ <t-button :theme="host.reason === 'dangerous' ? 'danger' : 'primary'" :loading="submitting"+ @click="submit('approve', 'once')">+ {{ $t('agentStream.hostApproval.approveOnce') }}+ </t-button>+ </div>+ </div>+</template>++<script setup lang="ts">+import { ref, computed, onMounted, onBeforeUnmount } from 'vue'+import { MessagePlugin } from 'tdesign-vue-next'+import { useI18n } from 'vue-i18n'+import { resolveToolApproval } from '@/api/mcp-service'+import {+ buildHostResolveBody,+ canNarrowAccess,+ clearComposerApproval,+ hostApprovalTitleKey,+ sessionRuleLabels,+ type HostApprovalAccess,+ type HostApprovalPayload,+ type HostApprovalScope,+} from './hostApproval'++const props = defineProps<{+ pendingId: string+ host: HostApprovalPayload+ timeoutSeconds?: number+ requestedAt?: number+ resolved?: boolean+ approved?: boolean+ resolveReason?: string+ resolveScope?: string+}>()++const { t } = useI18n()+const submitting = ref(false)+const snippetExpanded = ref(false)+const access = ref<HostApprovalAccess>(props.host.grant_access === 'read' ? 'read' : 'write')+const now = ref(Date.now())+let timer: ReturnType<typeof setInterval> | null = null++const titleKey = computed(() => hostApprovalTitleKey(props.host.reason))+const sessionRules = computed(() => sessionRuleLabels(props.host))++const secondsLeft = computed(() => {+ if (props.resolved) return -1+ const deadline = (props.requestedAt || 0) * 1000 + (props.timeoutSeconds || 600) * 1000+ return Math.max(0, Math.floor((deadline - now.value) / 1000))+})++const timerClass = computed(() => {+ if (secondsLeft.value <= 30) return 'timer-critical'+ if (secondsLeft.value <= 120) return 'timer-warning'+ return ''+})++const headerIcon = computed(() => {+ if (!props.resolved) return props.host.reason === 'dangerous' ? 'error-circle' : 'secured'+ return props.approved ? 'check-circle' : 'close-circle'+})++const statusLine = computed(() => {+ if (!props.approved) return t('agentStream.hostApproval.rejectedTag')+ return props.resolveScope === 'session'+ ? t('agentStream.hostApproval.approvedSession')+ : t('agentStream.hostApproval.approvedOnce')+})++function formatCountdown(s: number): string {+ if (s < 60) return t('agentStream.toolApproval.countdownShort', { seconds: s })+ return `${Math.floor(s / 60)}:${(s % 60).toString().padStart(2, '0')}`+}++onMounted(() => {+ timer = setInterval(() => {+ now.value = Date.now()+ }, 1000)+})++onBeforeUnmount(() => {+ if (timer) clearInterval(timer)+})++const submit = async (decision: 'approve' | 'reject', scope: HostApprovalScope) => {+ if (props.resolved || submitting.value) return+ submitting.value = true+ try {+ await resolveToolApproval(+ props.pendingId,+ buildHostResolveBody(decision, {+ scope,+ access: access.value,+ proposedAccess: props.host.grant_access,+ allowSession: props.host.allow_session,+ reason: decision === 'reject' ? t('agentStream.hostApproval.userRejected') : undefined,+ }),+ )+ // The resolved SSE event may be held back like the prompt was.+ clearComposerApproval(props.pendingId)+ MessagePlugin.success(t('agentStream.hostApproval.submitted'))+ } catch (e: any) {+ const msg = e?.response?.data?.error?.message || e?.message || t('agentStream.hostApproval.submitFailed')+ MessagePlugin.error(msg)+ } finally {+ submitting.value = false+ }+}+</script>++<style scoped lang="less">+.host-approval {+ display: flex;+ flex-direction: column;+ gap: 12px;+ padding: 14px 16px;+ border: 1px solid var(--td-component-border);+ border-radius: var(--app-radius-xl);+ background: var(--td-bg-color-container);+ box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);++ &.is-dangerous {+ border-color: var(--td-error-color-5);+ }++ &.is-resolved {+ box-shadow: none;+ opacity: 0.85;+ }+}++.host-approval__header {+ display: flex;+ align-items: center;+ gap: 8px;+}++.host-approval__icon {+ font-size: var(--app-text-2xl);+ color: var(--td-brand-color);++ .is-dangerous & {+ color: var(--td-error-color);+ }+}++.host-approval__title {+ flex: 1;+ min-width: 0;+ font-size: var(--app-text-base);+ font-weight: 600;+ color: var(--td-text-color-primary);+}++.host-approval__timer,+.host-approval__status {+ flex-shrink: 0;+ font-size: var(--app-text-sm);+ color: var(--td-text-color-secondary);+ font-variant-numeric: tabular-nums;++ &.timer-warning {+ color: var(--td-warning-color);+ }++ &.timer-critical {+ color: var(--td-error-color);+ }+}++.host-approval__body {+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.host-approval__label {+ font-size: var(--app-text-sm);+ color: var(--td-text-color-secondary);+}++.host-approval__code {+ margin: 0;+ padding: 8px 10px;+ max-height: 160px;+ overflow: auto;+ border-radius: var(--app-radius-md);+ background: var(--td-bg-color-secondarycontainer);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: var(--app-text-sm);+ line-height: 1.5;+ white-space: pre-wrap;+ word-break: break-all;+ color: var(--td-text-color-primary);++ &.is-muted {+ color: var(--td-text-color-secondary);+ }+}++.host-approval__meta {+ font-size: var(--app-text-sm);+ color: var(--td-text-color-secondary);++ code {+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ word-break: break-all;+ }+}++.host-approval__notice {+ display: flex;+ align-items: flex-start;+ gap: 6px;+ padding: 8px 10px;+ border-radius: var(--app-radius-md);+ background: var(--td-warning-color-1);+ color: var(--td-warning-color-8);+ font-size: var(--app-text-sm);+ line-height: 1.5;+}++.host-approval__toggle {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ align-self: flex-start;+ padding: 0;+ border: none;+ background: none;+ font-size: var(--app-text-sm);+ color: var(--td-text-color-secondary);+ cursor: pointer;+}++.host-approval__actions {+ display: flex;+ justify-content: flex-end;+ gap: 8px;+ padding-top: 4px;+}+</style>diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vueindex 125bce475..5ee1ba6ac 100644--- a/frontend/src/views/chat/components/botmsg.vue+++ b/frontend/src/views/chat/components/botmsg.vue@@ -18,7 +18,7 @@<RagPipelineProgress :session="session" :embedded-mode="embeddedMode" /><AgentStreamDisplay v-if="session.isAgentMode" :session="session" :session-id="sessionId":user-query="userQuery" :rag-mode="true" :follow-up-loading="followUpLoading"- :embedded-mode="embeddedMode"+ :embedded-mode="embeddedMode" defer-tool-approvals:can-fork="canFork":can-rewind="canRewind"@fork="emit('fork', $event)"@@ -35,7 +35,7 @@<docInfo v-if="session.knowledge_references?.length" :session="session"></docInfo><AgentStreamDisplay :session="session" :session-id="sessionId" :user-query="userQuery"v-if="session.isAgentMode" :follow-up-loading="followUpLoading"- :embedded-mode="embeddedMode"+ :embedded-mode="embeddedMode" defer-tool-approvals:can-fork="canFork":can-rewind="canRewind"@fork="emit('fork', $event)"diff --git a/frontend/src/views/chat/components/hostApproval.test.ts b/frontend/src/views/chat/components/hostApproval.test.tsnew file mode 100644index 000000000..0c0bafe60--- /dev/null+++ b/frontend/src/views/chat/components/hostApproval.test.ts@@ -0,0 +1,89 @@+import assert from 'node:assert/strict'+import test from 'node:test'++import {+ approvalEventFromRecord,+ buildHostResolveBody,+ canNarrowAccess,+ hostApprovalTitleKey,+ isHostApprovalEvent,+ sessionRuleLabels,+} from './hostApproval'++test('only a sandbox block may be narrowed to read-only; a delete needs write', () => {+ assert.equal(canNarrowAccess({ reason: 'sandbox_denied', grant_path: '/x', grant_access: 'write' }), true)+ assert.equal(canNarrowAccess({ reason: 'delete', grant_path: '/x', grant_access: 'write' }), false)+ assert.equal(canNarrowAccess({ reason: 'dangerous', grant_path: '/x', grant_access: 'write' }), false)+ assert.equal(canNarrowAccess({ reason: 'sandbox_denied' }), false)+})++test('a stored approval becomes a resolved timeline event', () => {+ const event = approvalEventFromRecord({+ pending_id: 'pending-1',+ kind: 'host_command',+ tool_call_id: 'call-1',+ host: { reason: 'delete', command: 'rm a.txt' },+ resolved: true,+ approved: false,+ reason: 'user rejected',+ scope: 'once',+ })+ assert.equal(event.type, 'tool_approval_required')+ assert.equal(event.resolved, true)+ assert.equal(event.approved, false)+ assert.equal(event.resolve_reason, 'user rejected')+ assert.equal(event.resolve_scope, 'once')+ assert.equal(isHostApprovalEvent(event), true)+})++test('only host_command events use the host card', () => {+ assert.equal(isHostApprovalEvent({ kind: 'host_command' }), true)+ assert.equal(isHostApprovalEvent({ kind: '' }), false)+ assert.equal(isHostApprovalEvent({}), false)+ assert.equal(isHostApprovalEvent({ host: { reason: 'delete' } }), true)+})++test('titles follow the approval reason', () => {+ assert.equal(hostApprovalTitleKey('delete'), 'agentStream.hostApproval.titleDelete')+ assert.equal(hostApprovalTitleKey('dangerous'), 'agentStream.hostApproval.titleDangerous')+ assert.equal(hostApprovalTitleKey('sandbox_denied'), 'agentStream.hostApproval.titleDenied')+ assert.equal(hostApprovalTitleKey('unknown'), 'agentStream.hostApproval.titleGeneric')+})++test('session scope is only sent when the request allows it', () => {+ assert.deepEqual(buildHostResolveBody('approve', { scope: 'session', allowSession: true }), {+ decision: 'approve',+ scope: 'session',+ })+ assert.deepEqual(buildHostResolveBody('approve', { scope: 'session', allowSession: false }), {+ decision: 'approve',+ scope: 'once',+ })+})++test('access can only narrow a write proposal to read', () => {+ assert.deepEqual(+ buildHostResolveBody('approve', { scope: 'once', access: 'read', proposedAccess: 'write' }),+ { decision: 'approve', scope: 'once', access: 'read' },+ )+ assert.deepEqual(+ buildHostResolveBody('approve', { scope: 'once', access: 'write', proposedAccess: 'read' }),+ { decision: 'approve', scope: 'once' },+ )+})++test('the card lists the delete rules a session approval remembers', () => {+ assert.deepEqual(+ sessionRuleLabels({ reason: 'delete', allow_session: true, session_rules: ['rm -f -r', 'rmdir'] }),+ ['rm -f -r …', 'rmdir …'],+ )+ assert.deepEqual(sessionRuleLabels({ reason: 'delete', allow_session: false, session_rules: ['rm'] }), [])+ assert.deepEqual(sessionRuleLabels({ reason: 'sandbox_denied', allow_session: true }), [])+})++test('reject carries only the reason', () => {+ assert.deepEqual(buildHostResolveBody('reject', { reason: 'no', scope: 'session', allowSession: true }), {+ decision: 'reject',+ reason: 'no',+ })+})diff --git a/frontend/src/views/chat/components/hostApproval.ts b/frontend/src/views/chat/components/hostApproval.tsnew file mode 100644index 000000000..0fbc423d3--- /dev/null+++ b/frontend/src/views/chat/components/hostApproval.ts@@ -0,0 +1,128 @@+import { ref } from 'vue'++export const HOST_APPROVAL_KIND = 'host_command'++// The open chat reads this directly. Several tools can wait at once when+// parallel calls are on, so this is a list keyed by pending_id, not one slot.+export const pendingComposerApprovals = ref<Record<string, any>[]>([])++export function showComposerApproval(event: Record<string, any>) {+ const id = event?.pending_id+ if (!id) return+ const list = pendingComposerApprovals.value+ const index = list.findIndex((item) => item.pending_id === id)+ if (index >= 0) {+ const next = list.slice()+ next[index] = event+ pendingComposerApprovals.value = next+ return+ }+ pendingComposerApprovals.value = [...list, event]+}++// A stored agent-step approval becomes the same timeline event the live+// stream used, already resolved so it stays as a record.+export function approvalEventFromRecord(record: Record<string, any>) {+ return {+ type: 'tool_approval_required',+ pending_id: record.pending_id,+ service_name: record.service_name,+ mcp_tool_name: record.mcp_tool_name,+ description: record.description,+ args_json: record.args_json,+ timeout_seconds: record.timeout_seconds,+ requested_at: record.requested_at,+ tool_call_id: record.tool_call_id,+ kind: record.kind,+ host: record.host,+ resolved: record.resolved === true,+ approved: record.approved,+ resolve_reason: record.reason,+ timed_out: record.timed_out,+ canceled: record.canceled,+ resolve_scope: record.scope,+ }+}++export function clearComposerApproval(pendingId?: string) {+ if (!pendingId) {+ pendingComposerApprovals.value = []+ return+ }+ pendingComposerApprovals.value = pendingComposerApprovals.value.filter(+ (item) => item.pending_id !== pendingId,+ )+}++export interface HostApprovalPayload {+ reason: string+ command?: string+ cwd?: string+ grant_path?: string+ grant_access?: string+ denial_snippet?: string+ first_attempt_ran?: boolean+ allow_session?: boolean+ session_rules?: string[]+}++// What "allow for this session" remembers for a delete. The trailing … says+// the file names may differ next time.+export function sessionRuleLabels(host: HostApprovalPayload): string[] {+ if (host.reason !== 'delete' || !host.allow_session) return []+ return (host.session_rules || []).map((rule) => `${rule} …`)+}++// A delete card can carry the directory the delete needs, but removing a file+// takes write access, so only a sandbox block offers read-only.+export function canNarrowAccess(host: HostApprovalPayload): boolean {+ return host.reason === 'sandbox_denied' && !!host.grant_path+}++export type HostApprovalScope = 'once' | 'session'+export type HostApprovalAccess = 'read' | 'write'++export interface HostResolveBody {+ decision: 'approve' | 'reject'+ scope?: HostApprovalScope+ access?: HostApprovalAccess+ reason?: string+}++export function isHostApprovalEvent(event: { kind?: string; host?: unknown }): boolean {+ return event.kind === HOST_APPROVAL_KIND || event.host != null+}++export function hostApprovalTitleKey(reason: string): string {+ switch (reason) {+ case 'delete':+ return 'agentStream.hostApproval.titleDelete'+ case 'dangerous':+ return 'agentStream.hostApproval.titleDangerous'+ case 'sandbox_denied':+ return 'agentStream.hostApproval.titleDenied'+ default:+ return 'agentStream.hostApproval.titleGeneric'+ }+}++// The server re-checks both rules; this keeps the card from sending a+// request it would refuse.+export function buildHostResolveBody(+ decision: 'approve' | 'reject',+ opts: {+ scope?: HostApprovalScope+ access?: HostApprovalAccess+ proposedAccess?: string+ allowSession?: boolean+ reason?: string+ },+): HostResolveBody {+ if (decision === 'reject') return { decision, reason: opts.reason }+ const body: HostResolveBody = {+ decision,+ scope: opts.scope === 'session' && opts.allowSession ? 'session' : 'once',+ }+ if (opts.access === 'read' && opts.proposedAccess === 'write') body.access = 'read'+ return body+}diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vueindex b0d73c910..4a360a7fa 100644--- a/frontend/src/views/chat/index.vue+++ b/frontend/src/views/chat/index.vue@@ -158,6 +158,17 @@</div></div><div ref="composerElement" class="chat_composer">+ <div v-if="composerApprovals.length" class="host-approval-pop">+ <HostApprovalCard v-for="approval in composerApprovals" :key="approval.pending_id"+ :pending-id="approval.pending_id"+ :host="approval.host || { reason: approval.kind === 'host_command' ? 'delete' : '' }"+ :timeout-seconds="approval.timeout_seconds"+ :requested-at="approval.requested_at"+ :resolved="approval.resolved"+ :approved="approval.approved"+ :resolve-reason="approval.resolve_reason"+ :resolve-scope="approval.resolve_scope" />+ </div><div class="input-container" :class="{ 'is-embedded': embeddedMode }"><transition name="scroll-btn-fade"><div v-show="userHasScrolledUp" class="scroll-to-bottom-btn" @click="onClickScrollToBottom">@@ -228,6 +239,12 @@ import { storeToRefs } from 'pinia';import { inject, ref, onMounted, onBeforeMount, onUnmounted, nextTick, watch, reactive, computed, provide } from 'vue';import { useRoute, useRouter, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';import InputField from '../../components/Input-field.vue';+import HostApprovalCard from './components/HostApprovalCard.vue';+import {+ clearComposerApproval,+ isHostApprovalEvent,+ pendingComposerApprovals,+} from './components/hostApproval';import botmsg from './components/botmsg.vue';import usermsg from './components/usermsg.vue';import { getMessageList, getSession, forkSession, rewindSession } from "@/api/chat/index";@@ -500,6 +517,10 @@ const FORK_PREFILL_KEY = 'weknora:fork-prefill'let forkInFlight = falseconst rewindInFlight = ref(false)const rewindLockSessionId = ref('')+const composerApprovals = computed(() =>+ pendingComposerApprovals.value.filter((item) => item && !item.resolved && isHostApprovalEvent(item))+)+const composerLocked = computed(() =>isAutomationSession.value || (rewindInFlight.value && String(session_id.value || '') === rewindLockSessionId.value))@@ -704,6 +725,16 @@ const currentAssistantMessageId = ref(''); // 当前正在生成的 assistant me// continue-stream always fails even though the answer is coming — recover by polling// instead of erroring. Web/api replies are left on the original error path.const isAttachingImStream = ref(false);++// A session change drops the stack; continue-stream replay adds back the+// cards that are still waiting. Clearing on every isReplying change hid a+// card that replay had just restored.+watch(session_id, () => {+ clearComposerApproval();+});+watch(isReplying, (replying) => {+ if (!replying) clearComposerApproval();+});let recoverPollTimer = null;// True while polling to recover an in-flight IM reply we couldn't stream. Drives// the same "generating" typing indicator the normal reply path shows, so the wait@@ -1955,6 +1986,7 @@ onUnmounted(() => {window.removeEventListener(SESSION_MUTATION_EVENT, handleSessionMutation);if (recoverPollTimer) { clearTimeout(recoverPollTimer); recoverPollTimer = null; }backgroundPoller.dispose();+ clearComposerApproval();});// An embedded view outlives the page behind it: a route change must not stop// its stream or restore the main chat's defaults.@@ -2148,6 +2180,14 @@ onBeforeRouteUpdate((to, from, next) => {}}+.host-approval-pop {+ width: 100%;+ max-width: 800px;+ margin: 0 auto 8px;+ padding: 0 16px;+ box-sizing: border-box;+}+.chat_composer {position: absolute;bottom: 0;diff --git a/internal/agent/approval/gate.go b/internal/agent/approval/gate.goindex caf538240..cce6b0d85 100644--- a/internal/agent/approval/gate.go+++ b/internal/agent/approval/gate.go@@ -49,6 +49,10 @@ type Decision struct {// Suspended is set when no decision arrived during the in-memory wait// and the prompt now outlives the run; the call must not execute.Suspended *types.PromptSuspension+ // Scope is "once" or "session" for host approvals; empty means once.+ Scope string+ // Access narrows a host grant to "read"; empty keeps the proposal.+ Access string}// PendingRequest carries everything needed to block and notify the UI.@@ -270,6 +274,104 @@ func (req PendingRequest) grantRisk() policy.Risk {return req.GrantRisk}+// HostApprovalKindCommand marks a Lite host shell command approval.+const HostApprovalKindCommand = "host_command"++// HostPendingRequest asks the session owner about one Lite host command.+type HostPendingRequest struct {+ TenantID uint64+ UserID string+ SessionID string+ AssistantMessageID string+ RequestID string+ ToolCallID string+ EventBus *event.EventBus+ Host event.HostApprovalPayload+}++// RequestHostAndWait blocks until the session owner answers a Lite host+// command approval, the wait times out, or ctx is canceled. Unlike+// RequestAndWait it never consults the MCP checker: a nil checker must not+// turn a host question into an automatic yes.+func (g *Gate) RequestHostAndWait(ctx context.Context, req HostPendingRequest) (Decision, error) {+ if g == nil || g.broker == nil {+ return Decision{}, fmt.Errorf("host approval: nil gate")+ }+ if req.EventBus == nil {+ return Decision{}, fmt.Errorf("host approval: EventBus is nil")+ }+ if strings.TrimSpace(req.UserID) == "" {+ return Decision{}, fmt.Errorf("host approval: session owner is unknown")+ }++ host := req.Host+ request, err := json.Marshal(types.ToolApprovalPromptRequest{+ RegisteredToolName: "shell_exec",+ })+ if err != nil {+ return Decision{}, fmt.Errorf("encode host approval: %w", err)+ }+ out, err := g.broker.Await(ctx, hitl.Spec{+ Prompt: &types.AgentPrompt{+ TenantID: req.TenantID,+ UserID: req.UserID,+ SessionID: req.SessionID,+ AssistantMessageID: req.AssistantMessageID,+ RequestID: req.RequestID,+ Kind: types.AgentPromptKindToolApproval,+ ToolCallID: req.ToolCallID,+ Request: types.JSON(request),+ },+ Timeout: g.timeout,+ TimeoutReason: "approval timeout",+ Emit: func(ctx context.Context, p *types.AgentPrompt) error {+ timeoutSec := promptWaitSeconds(p, g.timeout, g.timeout)+ return req.EventBus.Emit(ctx, event.Event{+ ID: p.ID + "-approval-required",+ Type: event.EventToolApprovalRequired,+ SessionID: req.SessionID,+ Data: event.ToolApprovalRequiredData{+ PendingID: p.ID,+ TenantID: req.TenantID,+ SessionID: req.SessionID,+ AssistantMessageID: req.AssistantMessageID,+ RegisteredToolName: "shell_exec",+ TimeoutSeconds: timeoutSec,+ HotWaitSeconds: timeoutSec,+ Suspendable: p.Suspendable,+ RequestedAtUnix: time.Now().Unix(),+ ToolCallID: req.ToolCallID,+ RequestID: req.RequestID,+ Kind: HostApprovalKindCommand,+ Host: &host,+ },+ Metadata: map[string]interface{}{+ "assistant_message_id": req.AssistantMessageID,+ "pending_id": p.ID,+ },+ RequestID: req.RequestID,+ })+ },+ })+ if err != nil {+ return Decision{}, fmt.Errorf("host approval: %w", err)+ }+ if out.Suspended {+ return Decision{+ PendingID: out.Prompt.ID,+ Suspended: &types.PromptSuspension{+ Detached: out.Detached,+ PromptID: out.Prompt.ID,+ Kind: types.AgentPromptKindToolApproval,+ ExpiresAt: out.ExpiresAt,+ },+ }, nil+ }+ d := toolApprovalDecision(out)+ g.consumeDecision(ctx, &d, req.EventBus, out.Prompt)+ return d, nil+}+func (g *Gate) awaitToolApproval(ctx context.Context, req PendingRequest) (Decision, error) {granted, lapse := g.granted(ctx, req)if granted {@@ -416,6 +518,8 @@ func (g *Gate) consumeDecision(ctx context.Context, d *Decision, bus *event.Evenif !consumed && d.answered {d.Approved = falsed.ModifiedArgs = nil+ d.Scope = ""+ d.Access = ""d.Reason = "approval is no longer owned or was already consumed"if consumeErr == nil {d.Suspended = &types.PromptSuspension{@@ -441,6 +545,7 @@ func (g *Gate) consumeDecision(ctx context.Context, d *Decision, bus *event.EvenReason: d.Reason,TimedOut: d.TimedOut,Canceled: d.ContextCanceled,+ Scope: d.Scope,},Metadata: map[string]interface{}{"assistant_message_id": assistantMessageID,@@ -578,7 +683,12 @@ func (g *Gate) ResolveForResume(ctx context.Context, req ResolveRequest) (hitl.Rvar response anyswitch kind {case types.AgentPromptKindToolApproval:- r := types.ToolApprovalPromptResponse{Approved: req.Decision.Approved, Reason: req.Decision.Reason}+ r := types.ToolApprovalPromptResponse{+ Approved: req.Decision.Approved,+ Reason: req.Decision.Reason,+ Scope: req.Decision.Scope,+ Access: req.Decision.Access,+ }if r.Approved {r.ModifiedArgs = req.Decision.ModifiedArgsr.AllowInSession = req.Decision.AllowInSession@@ -642,6 +752,7 @@ func toolApprovalDecision(out hitl.Outcome) Decision {return d}d.Approved, d.Reason = r.Approved, r.Reason+ d.Scope, d.Access = r.Scope, r.Accessif r.Approved && len(r.ModifiedArgs) > 0 {d.ModifiedArgs = r.ModifiedArgs}@@ -678,6 +789,8 @@ func validateToolApprovalResponse(request, response json.RawMessage) error {ModifiedArgs json.RawMessage `json:"modified_args,omitempty"`Reason string `json:"reason,omitempty"`AllowInSession bool `json:"allow_in_session,omitempty"`+ Scope string `json:"scope,omitempty"`+ Access string `json:"access,omitempty"`}dec := json.NewDecoder(bytes.NewReader(response))dec.DisallowUnknownFields()diff --git a/internal/agent/approval/gate_host_test.go b/internal/agent/approval/gate_host_test.gonew file mode 100644index 000000000..61e49123f--- /dev/null+++ b/internal/agent/approval/gate_host_test.go@@ -0,0 +1,101 @@+package approval++import (+ "context"+ "encoding/json"+ "testing"++ "github.com/Tencent/WeKnora/internal/config"+ "github.com/Tencent/WeKnora/internal/event"+ "github.com/stretchr/testify/require"+)++func hostRequest(bus *event.EventBus) HostPendingRequest {+ return HostPendingRequest{+ TenantID: 1, UserID: "u1", SessionID: "s1", AssistantMessageID: "m1",+ ToolCallID: "tc1", EventBus: bus,+ Host: event.HostApprovalPayload{Reason: "delete", Command: "rm a", Cwd: "/w", AllowSession: true},+ }+}++// A nil MCP checker turns RequestAndWait into an automatic yes. The host+// entry point must still block for the user.+func TestRequestHostAndWaitBlocksWithoutChecker(t *testing.T) {+ bus := event.NewEventBus()+ g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 2}}, nil, nil)+ var seen event.ToolApprovalRequiredData+ bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error {+ seen = evt.Data.(event.ToolApprovalRequiredData)+ go func() {+ _ = g.Resolve(context.Background(), ResolveRequest{+ TenantID: 1, UserID: "u1", PendingID: seen.PendingID,+ Decision: Decision{Approved: true, Scope: "session", Access: "read"},+ })+ }()+ return nil+ })+ var resolved event.ToolApprovalResolvedData+ bus.On(event.EventToolApprovalResolved, func(_ context.Context, evt event.Event) error {+ resolved = evt.Data.(event.ToolApprovalResolvedData)+ return nil+ })++ d, err := g.RequestHostAndWait(context.Background(), hostRequest(bus))+ require.NoError(t, err)+ require.True(t, d.Approved)+ require.Equal(t, "session", d.Scope)+ require.Equal(t, "read", d.Access)+ require.Equal(t, HostApprovalKindCommand, seen.Kind)+ require.NotNil(t, seen.Host)+ require.Equal(t, "rm a", seen.Host.Command)+ require.Equal(t, "session", resolved.Scope)+}++func TestRequestHostAndWaitTimesOut(t *testing.T) {+ g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 1}}, nil, nil)+ d, err := g.RequestHostAndWait(context.Background(), hostRequest(event.NewEventBus()))+ require.NoError(t, err)+ require.False(t, d.Approved)+ require.True(t, d.TimedOut)+}++func TestRequestHostAndWaitNeedsOwner(t *testing.T) {+ g := NewGate(nil, nil, nil)+ req := hostRequest(event.NewEventBus())+ req.UserID = ""+ _, err := g.RequestHostAndWait(context.Background(), req)+ require.Error(t, err)+}++func TestRequestHostAndWaitRejectsOtherUser(t *testing.T) {+ bus := event.NewEventBus()+ g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 2}}, nil, nil)+ bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error {+ id := evt.Data.(event.ToolApprovalRequiredData).PendingID+ go func() {+ require.ErrorIs(t, g.Resolve(context.Background(), ResolveRequest{+ TenantID: 1, UserID: "mallory", PendingID: id,+ Decision: Decision{Approved: true},+ }), ErrUserMismatch)+ _ = g.Resolve(context.Background(), ResolveRequest{+ TenantID: 1, UserID: "u1", PendingID: id,+ Decision: Decision{Approved: false, Reason: "no"},+ })+ }()+ return nil+ })+ d, err := g.RequestHostAndWait(context.Background(), hostRequest(bus))+ require.NoError(t, err)+ require.False(t, d.Approved)+}++// MCP events must serialize exactly as before when Kind and Host are unset.+func TestMCPApprovalEventOmitsHostFields(t *testing.T) {+ raw, err := json.Marshal(event.ToolApprovalRequiredData{PendingID: "p"})+ require.NoError(t, err)+ require.NotContains(t, string(raw), `"kind"`)+ require.NotContains(t, string(raw), `"host"`)+ raw, err = json.Marshal(event.ToolApprovalResolvedData{PendingID: "p"})+ require.NoError(t, err)+ require.NotContains(t, string(raw), `"scope"`)+}diff --git a/internal/agent/prompts.go b/internal/agent/prompts.goindex 4ac33c5f0..6328c4f20 100644--- a/internal/agent/prompts.go+++ b/internal/agent/prompts.go@@ -386,10 +386,12 @@ func formatToolGuidanceForMode(names []string, skillInstallMode bool, layout sanif root := sandbox.PromptSafePath(layout.Root); root != "" {b.WriteString("Session workspace: ")b.WriteString(root)- b.WriteString(". Edit files in place under that folder. Commands start from ")+ b.WriteString(". That folder is the default place to edit, along with directories the user " ++ "has already approved for this session. Commands start from ")b.WriteString(root)- b.WriteString(" on every call unless work_dir names a subdirectory. " +- "Files persist on the user's machine.\n")+ b.WriteString(" on every call unless work_dir names a subdirectory or an approved directory. " ++ "shell_exec may try a path outside the workspace; the sandbox asks the user before opening it. " ++ "Deletes ask even inside the workspace. Files persist on the user's machine.\n")}} else if layout.IsSharedRemote() {root := sandbox.PromptSafePath(layout.Root)diff --git a/internal/agent/prompts_shell_test.go b/internal/agent/prompts_shell_test.goindex 940c8a027..5bb7191c9 100644--- a/internal/agent/prompts_shell_test.go+++ b/internal/agent/prompts_shell_test.go@@ -41,6 +41,7 @@ func TestToolGuidanceForHostUsesActualWorkspace(t *testing.T) {[]string{"shell_exec", "read_file", "write_sandbox_file"}, false, layout,)require.Contains(t, text, "Session workspace: /Users/dev/My Project")+ require.Contains(t, text, "asks the user before opening it")require.NotContains(t, text, sandbox.SessionWorkspaceRoot)require.NotContains(t, text, "is the only directory collected")require.NotContains(t, text, "sandbox:<file name>")diff --git a/internal/agent/tools/host_approval.go b/internal/agent/tools/host_approval.gonew file mode 100644index 000000000..8abee9df8--- /dev/null+++ b/internal/agent/tools/host_approval.go@@ -0,0 +1,95 @@+package tools++import (+ "context"+ "errors"++ "github.com/Tencent/WeKnora/internal/agent/approval"+ "github.com/Tencent/WeKnora/internal/event"+ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/Tencent/WeKnora/internal/types"+)++// HostApproval is the gate surface shell_exec needs on a Lite host workspace.+type HostApproval interface {+ RequestHostAndWait(ctx context.Context, req approval.HostPendingRequest) (approval.Decision, error)+}++var _ HostApproval = (*approval.Gate)(nil)++type hostCommandApprover struct {+ gate HostApproval+ meta *ToolExecContext+ tenantID uint64+}++func (a hostCommandApprover) ApproveCommand(+ ctx context.Context, req sandbox.CommandApprovalRequest,+) (sandbox.CommandApprovalDecision, error) {+ d, err := a.gate.RequestHostAndWait(ctx, approval.HostPendingRequest{+ TenantID: a.tenantID,+ UserID: a.meta.UserID,+ SessionID: req.SessionID,+ AssistantMessageID: a.meta.AssistantMessageID,+ RequestID: a.meta.RequestID,+ ToolCallID: a.meta.ToolCallID,+ EventBus: a.meta.EventBus,+ Host: event.HostApprovalPayload{+ Reason: req.Reason,+ Command: req.Command,+ Cwd: req.Cwd,+ GrantPath: req.GrantPath,+ GrantAccess: req.GrantAccess,+ DenialSnippet: req.DenialSnippet,+ FirstAttemptRan: req.FirstAttemptRan,+ AllowSession: req.AllowSession,+ SessionRules: req.SessionRules,+ },+ })+ if err != nil {+ return sandbox.CommandApprovalDecision{}, err+ }+ switch {+ case d.TimedOut:+ return sandbox.CommandApprovalDecision{}, errors.New("the approval request timed out")+ case d.ContextCanceled:+ return sandbox.CommandApprovalDecision{}, errors.New("the approval request was canceled")+ }+ return sandbox.CommandApprovalDecision{+ Approved: d.Approved,+ Session: d.Scope == "session" && req.AllowSession,+ Access: d.Access,+ Reason: d.Reason,+ }, nil+}++// WithHostApproval lets host commands wait for the session owner. Without it+// the host sandbox refuses anything it would have asked about.+func (t *ShellExecTool) WithHostApproval(gate HostApproval) *ShellExecTool {+ if t != nil {+ t.hostApproval = gate+ }+ return t+}++// hostApprovalContext attaches the approval port for one host command. The+// result is rooted at ApprovalCtx so a user who takes minutes to answer does+// not use up the command's own timeout; the host sandbox times each attempt.+func (t *ShellExecTool) hostApprovalContext(ctx context.Context, command, stdin string) context.Context {+ review := command+ if stdin != "" && shellStdinIsProgram(command) {+ review = command + "\n" + stdin+ }+ port := sandbox.CommandApproval{Command: review}+ meta, ok := ToolExecFromContext(ctx)+ if !ok || t.hostApproval == nil || meta.EventBus == nil {+ return sandbox.WithCommandApproval(ctx, port)+ }+ tenantID, _ := types.TenantIDFromContext(ctx)+ port.Approver = hostCommandApprover{gate: t.hostApproval, meta: meta, tenantID: tenantID}+ base := ctx+ if meta.ApprovalCtx != nil {+ base = WithToolExecContext(WithOutputBudget(meta.ApprovalCtx, OutputBudget(ctx)), meta)+ }+ return sandbox.WithCommandApproval(base, port)+}diff --git a/internal/agent/tools/host_approval_test.go b/internal/agent/tools/host_approval_test.gonew file mode 100644index 000000000..49ddf6da4--- /dev/null+++ b/internal/agent/tools/host_approval_test.go@@ -0,0 +1,113 @@+package tools++import (+ "context"+ "testing"+ "time"++ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/internal/agent/approval"+ "github.com/Tencent/WeKnora/internal/event"+ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/Tencent/WeKnora/internal/types"+)++type fakeHostGate struct {+ decision approval.Decision+ requests []approval.HostPendingRequest+}++func (f *fakeHostGate) RequestHostAndWait(+ _ context.Context, req approval.HostPendingRequest,+) (approval.Decision, error) {+ f.requests = append(f.requests, req)+ return f.decision, nil+}++func hostExecContext(t *testing.T) (context.Context, context.Context) {+ t.Helper()+ parent := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))+ meta := &ToolExecContext{+ SessionID: "s1", AssistantMessageID: "m1", RequestID: "r1", ToolCallID: "tc1",+ UserID: "u1", EventBus: event.NewEventBus(), ApprovalCtx: parent,+ }+ toolCtx, cancel := context.WithTimeout(WithToolExecContext(parent, meta), time.Second)+ t.Cleanup(cancel)+ return parent, toolCtx+}++func TestHostApprovalContextAsksThroughGate(t *testing.T) {+ gate := &fakeHostGate{decision: approval.Decision{Approved: true, Scope: "session", Access: "read"}}+ tool := NewShellExecTool(nil, nil).WithHostApproval(gate)+ _, toolCtx := hostExecContext(t)++ ctx := tool.hostApprovalContext(toolCtx, "rm a.txt", "")+ port, ok := sandbox.CommandApprovalFrom(ctx)+ require.True(t, ok)+ require.Equal(t, "rm a.txt", port.Command)+ require.NotNil(t, port.Approver)+ _, hasDeadline := ctx.Deadline()+ require.False(t, hasDeadline, "waiting for the user must not eat the tool timeout")++ d, err := port.Approver.ApproveCommand(ctx, sandbox.CommandApprovalRequest{+ SessionID: "s1", Command: "rm a.txt", Cwd: "/w", Reason: "delete", AllowSession: true,+ SessionRules: []string{"rm"},+ })+ require.NoError(t, err)+ require.Equal(t, sandbox.CommandApprovalDecision{Approved: true, Session: true, Access: "read"}, d)+ req := gate.requests[0]+ require.Equal(t, uint64(7), req.TenantID)+ require.Equal(t, "u1", req.UserID)+ require.Equal(t, "tc1", req.ToolCallID)+ require.Equal(t, "rm a.txt", req.Host.Command)+ require.Equal(t, "delete", req.Host.Reason)+ require.Equal(t, []string{"rm"}, req.Host.SessionRules)+}++func TestHostApprovalContextKeepsTheOutputBudget(t *testing.T) {+ tool := NewShellExecTool(nil, nil).WithHostApproval(&fakeHostGate{})+ _, toolCtx := hostExecContext(t)++ ctx := tool.hostApprovalContext(WithOutputBudget(toolCtx, 1234), "rm a.txt", "")+ require.Equal(t, 1234, OutputBudget(ctx))+}++func TestHostApprovalSessionScopeNeedsPermission(t *testing.T) {+ gate := &fakeHostGate{decision: approval.Decision{Approved: true, Scope: "session"}}+ tool := NewShellExecTool(nil, nil).WithHostApproval(gate)+ _, toolCtx := hostExecContext(t)+ port, _ := sandbox.CommandApprovalFrom(tool.hostApprovalContext(toolCtx, "rm -rf ~", ""))++ d, err := port.Approver.ApproveCommand(context.Background(), sandbox.CommandApprovalRequest{+ Reason: "dangerous", AllowSession: false,+ })+ require.NoError(t, err)+ require.False(t, d.Session)+}++func TestHostApprovalTimeoutIsAnError(t *testing.T) {+ gate := &fakeHostGate{decision: approval.Decision{TimedOut: true, Reason: "approval timeout"}}+ tool := NewShellExecTool(nil, nil).WithHostApproval(gate)+ _, toolCtx := hostExecContext(t)+ port, _ := sandbox.CommandApprovalFrom(tool.hostApprovalContext(toolCtx, "rm a", ""))++ _, err := port.Approver.ApproveCommand(context.Background(), sandbox.CommandApprovalRequest{Reason: "delete"})+ require.ErrorContains(t, err, "timed out")+}++func TestHostApprovalReviewIncludesStdinProgram(t *testing.T) {+ tool := NewShellExecTool(nil, nil).WithHostApproval(&fakeHostGate{})+ _, toolCtx := hostExecContext(t)+ port, _ := sandbox.CommandApprovalFrom(tool.hostApprovalContext(toolCtx, "bash", "rm -rf out\n"))+ require.Contains(t, port.Command, "rm -rf out")+}++func TestHostApprovalWithoutGateStillCarriesCommand(t *testing.T) {+ tool := NewShellExecTool(nil, nil)+ _, toolCtx := hostExecContext(t)+ port, ok := sandbox.CommandApprovalFrom(tool.hostApprovalContext(toolCtx, "rm a", ""))+ require.True(t, ok)+ require.Nil(t, port.Approver)+ require.Equal(t, "rm a", port.Command)+}diff --git a/internal/agent/tools/read_file.go b/internal/agent/tools/read_file.goindex 21b3749d5..20bcfcc04 100644--- a/internal/agent/tools/read_file.go+++ b/internal/agent/tools/read_file.go@@ -114,9 +114,10 @@ func (t *ReadFileTool) updateDescription() {if t.workspace != nil {layout := t.boundLayout()if layout.IsHost() {- scopes = append(scopes, "Sandbox files: absolute or relative paths in "+layoutRootOrGeneric(layout)+". "++ scopes = append(scopes, "Sandbox files: absolute or relative paths in "+layoutRootOrGeneric(layout)++ ", and in directories the user has approved for this session. "+"Image files are returned as images for you to inspect. "+- "This does not read files outside that folder or publish files as user-visible artifacts.")+ "Other paths are refused. This does not publish files as user-visible artifacts.")} else {scopes = append(scopes,"Sandbox files: absolute paths inside the current session's sandbox, including /tmp; "+diff --git a/internal/agent/tools/sandbox_edit.go b/internal/agent/tools/sandbox_edit.goindex 41296fd2b..08261ad5f 100644--- a/internal/agent/tools/sandbox_edit.go+++ b/internal/agent/tools/sandbox_edit.go@@ -140,7 +140,9 @@ func (t *EditSandboxFileTool) boundLayout() sandbox.WorkspaceLayout {return t.describeLayout(t.editor)}-const hostEditSandboxFileDescription = "Apply exact text replacements to an existing text file in %s.\n" ++const hostEditSandboxFileDescription = "Apply exact text replacements to an existing text file in %s, " ++ "or in a directory the user has already approved for this session. " ++ "Paths outside that are refused; use shell_exec when the user should be asked to open a new directory.\n" +"Read the relevant content first. Send edits as an array, even for one replacement. \n" +"Every old_string matches the original file, must be unique unless replace_all=true, " +"and must not overlap another edit. \n" +diff --git a/internal/agent/tools/sandbox_write.go b/internal/agent/tools/sandbox_write.goindex 2e30a1365..8239b069a 100644--- a/internal/agent/tools/sandbox_write.go+++ b/internal/agent/tools/sandbox_write.go@@ -170,7 +170,9 @@ func writeSandboxDescription(l sandbox.WorkspaceLayout, sizeGuidance string) strreturn fmt.Sprintf(rewriteRemoteWorkspaceCopy(writeSandboxFileDescription, l), sizeGuidance)}-const hostWriteSandboxFileDescription = "Create, overwrite, or append a text file in %s.\n" ++const hostWriteSandboxFileDescription = "Create, overwrite, or append a text file in %s, " ++ "or in a directory the user has already approved for this session. " ++ "Paths outside that are refused; use shell_exec when the user should be asked to open a new directory.\n" +"Send both path and content (path first). Use edit_sandbox_file for small changes to an existing file. " +"File content does not pass through shell quoting.\n" +"Large files: first call uses mode=overwrite (default), " +diff --git a/internal/agent/tools/shell_exec.go b/internal/agent/tools/shell_exec.goindex 50c9c406b..f776cc4c9 100644--- a/internal/agent/tools/shell_exec.go+++ b/internal/agent/tools/shell_exec.go@@ -180,14 +180,17 @@ func shellExecDescription(l sandbox.WorkspaceLayout) string {const hostShellExecDescription = "Execute a command in %s. The process is OS-sandboxed on this machine.\n" +"- CWD defaults to %s on every call; cd does not persist. " +- "work_dir must be that folder or a subdirectory.\n" ++ "work_dir may be that folder, a subdirectory, or a directory the user already approved for this session.\n" +"- Use ls/find to discover files, grep/awk to search, and cat/head/tail/sed to inspect text. " +- "Read known paths directly.\n" ++ "Read known paths directly. " ++ "A path outside the workspace can be tried; if the sandbox blocks it, the user is asked.\n" +"- Use write_sandbox_file for scripts or large text; edit_sandbox_file for precise changes. " +"Commands are limited to 8192 bytes. Execution is synchronous (no nohup or trailing &).\n" +- "- Edit files in place under %s.\n" ++ "- Edit files under %s when they belong there. Writing outside it can be attempted: " ++ "the sandbox blocks the path and asks the user before opening it. " ++ "Deletes (rm, rmdir, unlink, git rm, git clean, find -delete) ask even inside the workspace.\n" +"- Non-zero exit_code is a command result: inspect stderr before deciding whether a corrected call is useful. " +- "Do not bypass permission or policy denials through another tool.\n" ++ "Do not bypass a user refusal by switching tools or rewriting the same action.\n" +"- stdout/stderr have independent byte limits. " +"Redirect verbose commands to a workspace log when output must be kept.\n" +"- If you are not sure the command finishes within a couple of minutes, use " +@@ -282,6 +285,7 @@ type ShellExecTool struct {// inject them. Install-mode tools never invoke it.envCapture SkillEnvCaptureskillEnvironment *skills.Manager+ hostApproval HostApproval}func (t *ShellExecTool) WithSkillEnvironment(manager *skills.Manager) *ShellExecTool {@@ -597,8 +601,12 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ}output, finishOutput := shellCommandOutput(ctx, command)defer finishOutput()+ execBase := ctx+ if layout.IsHost() {+ execBase = t.hostApprovalContext(ctx, command, input.Stdin)+ }// Observe only the requested command, not skill staging or artifact probes.- execCtx := sandbox.WithCommandOutput(ctx, output)+ execCtx := sandbox.WithCommandOutput(execBase, output)var res *sandbox.ExecuteResultvar err errorvar outputFiles []stringdiff --git a/internal/agent/tools/workspace_layout_test.go b/internal/agent/tools/workspace_layout_test.goindex 511dc4858..cd2e98681 100644--- a/internal/agent/tools/workspace_layout_test.go+++ b/internal/agent/tools/workspace_layout_test.go@@ -186,6 +186,7 @@ func TestShellExecHostLayoutAllowsWorkDirUnderWriteRoots(t *testing.T) {func TestShellExecHostDescriptionUsesActualWorkspacePath(t *testing.T) {tool := NewShellExecTool(&layoutShellExecutor{layout: hostLayout()}, nil)require.Contains(t, tool.Description(), hostLayout().Root)+ require.Contains(t, tool.Description(), "asks the user before opening it")require.NotContains(t, tool.Description(), sandbox.SessionWorkspaceRoot)require.Contains(t, string(tool.Parameters()), hostLayout().Root)require.NotContains(t, string(tool.Parameters()), sandbox.SessionWorkspaceRoot)diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.goindex bfd973410..3c0a6e407 100644--- a/internal/application/service/agent_service.go+++ b/internal/application/service/agent_service.go@@ -1176,9 +1176,11 @@ func (s *agentService) registerSandboxShellTool(}if executor := sessionSandboxShellExecutor(sandboxMgr); executor != nil {resolver := s.userEnvResolver(ctx, config)- toolRegistry.RegisterTool(- tools.NewShellExecTool(executor, resolver).WithEnvCapture(s.skillEnvCapture(config)),- )+ shell := tools.NewShellExecTool(executor, resolver).WithEnvCapture(s.skillEnvCapture(config))+ if gate, ok := s.toolApprovalGate.(tools.HostApproval); ok {+ shell = shell.WithHostApproval(gate)+ }+ toolRegistry.RegisterTool(shell)logger.Infof(ctx, "Registered shell_exec tool")s.registerShellExecAsync(ctx, toolRegistry, executor, resolver, config)} else {diff --git a/internal/application/service/session.go b/internal/application/service/session.goindex be06c94c2..ca8ac25e5 100644--- a/internal/application/service/session.go+++ b/internal/application/service/session.go@@ -953,6 +953,9 @@ func (s *sessionService) destroyBoundSandbox(ctx context.Context, sessionID striif sessionID == "" {return}+ if releaser, ok := s.hostSandbox.(sandbox.SessionStateReleaser); ok {+ releaser.ReleaseSessionState(ctx, sessionID)+ }// Resolve the workspace's own manager: the sandbox to release lives on// whichever backend that workspace is configured for, not necessarily the// process-wide default.diff --git a/internal/application/service/session_attachment_staging.go b/internal/application/service/session_attachment_staging.goindex 06670d091..bf0283aec 100644--- a/internal/application/service/session_attachment_staging.go+++ b/internal/application/service/session_attachment_staging.go@@ -542,7 +542,9 @@ func buildSandboxAttachmentsPrompt(attachments []stagedSessionAttachment, layout"and patch existing ones with edit_sandbox_file.")if layout.IsHost() {if workspace != "" {- b.WriteString(" Edit files in place under " + escapeAttachmentXML(workspace) + ".")+ b.WriteString(" Edit files under " + escapeAttachmentXML(workspace) ++ ", or under a directory the user has already approved for this session. " ++ "shell_exec may try a path outside that; the sandbox asks the user before opening it.")}} else {remote := sandbox.RemoteWorkspaceLayout()diff --git a/internal/application/service/session_attachment_staging_test.go b/internal/application/service/session_attachment_staging_test.goindex 2f3298050..e5bcb7c61 100644--- a/internal/application/service/session_attachment_staging_test.go+++ b/internal/application/service/session_attachment_staging_test.go@@ -562,7 +562,8 @@ func TestAttachmentPromptUsesLayoutRoot(t *testing.T) {})require.Contains(t, prompt, `root="/Users/dev/appdata/s1/input"`)- require.Contains(t, prompt, "Edit files in place under /Users/dev/My Project")+ require.Contains(t, prompt, "Edit files under /Users/dev/My Project")+ require.Contains(t, prompt, "already approved for this session")require.NotContains(t, prompt, "/workspace")require.NotContains(t, prompt, "only directory collected")}diff --git a/internal/application/service/session_delete_host_test.go b/internal/application/service/session_delete_host_test.goindex 2e97ac447..564ccbf07 100644--- a/internal/application/service/session_delete_host_test.go+++ b/internal/application/service/session_delete_host_test.go@@ -124,3 +124,27 @@ func (m *destroyingSandboxManager) DestroySession(_ context.Context, sessionID sm.destroyed = append(m.destroyed, sessionID)return os.RemoveAll(m.workspace)}++type releasingHostManager struct {+ destroyingSandboxManager+ released []string+}++func (m *releasingHostManager) ReleaseSessionState(_ context.Context, sessionID string) {+ m.released = append(m.released, sessionID)+}++func TestDeleteSessionReleasesHostApprovals(t *testing.T) {+ host := &releasingHostManager{destroyingSandboxManager: destroyingSandboxManager{+ typ: sandbox.SandboxTypeHost, workspace: t.TempDir(),+ }}+ svc, db := newSessionServiceForHostDeleteTest(t, host, nil)+ ctx := testSessionScopeContext(1, "u1")+ require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{+ ID: "host-s2", TenantID: 1, UserID: "u1", Title: "chat",+ }).Error)++ require.NoError(t, svc.DeleteSession(ctx, "host-s2"))+ require.Equal(t, []string{"host-s2"}, host.released)+ require.Empty(t, host.destroyed)+}diff --git a/internal/container/sandbox_host.go b/internal/container/sandbox_host.goindex d8844ad1f..40112a13f 100644--- a/internal/container/sandbox_host.go+++ b/internal/container/sandbox_host.go@@ -30,7 +30,7 @@ type hostSandboxDeps struct {homeDir stringappDataDir string// sessionRoot is where auto-allocated session workspaces go. Empty falls- // back to ~/Documents/WeKnoraLite.+ // back to ~/.weknora/sessions.sessionRoot stringskillsRoot string// projects maps a session to a user-approved project directory.@@ -76,7 +76,9 @@ func buildHostSandbox(deps hostSandboxDeps) *hostSandboxParts {resolver := localsandbox.NewWorkspaceResolver(localsandbox.DirLayout{SessionRoot: sessionRoot,}, deps.projects)- builder := localsandbox.NewPolicyBuilder(homeDir, appDataDir).WithSkillsRoot(deps.skillsRoot)+ builder := localsandbox.NewPolicyBuilder(homeDir, appDataDir).+ WithSkillsRoot(deps.skillsRoot).+ WithSessionRoot(sessionRoot)svc := localsandbox.NewService(backend, resolver, builder, deps.modes)return &hostSandboxParts{manager: adapter.New(svc), service: svc, builder: builder}}@@ -161,7 +163,7 @@ func finishHostSandbox(parts *hostSandboxParts, skillsRoot string) service.HostS}func defaultHostSessionRoot(homeDir string) string {- return filepath.Join(homeDir, "Documents", "WeKnoraLite")+ return filepath.Join(homeDir, ".weknora", "sessions")}func defaultHostSkillsRoot(homeDir string) string {diff --git a/internal/container/sandbox_host_test.go b/internal/container/sandbox_host_test.goindex ac4b99219..b2782bb1a 100644--- a/internal/container/sandbox_host_test.go+++ b/internal/container/sandbox_host_test.go@@ -72,8 +72,8 @@ func TestHostSandboxManagerNilWhenAvailableFails(t *testing.T) {}))}-func TestDefaultHostSessionRootUsesWeKnoraLite(t *testing.T) {- require.Equal(t, "/Users/dev/Documents/WeKnoraLite", defaultHostSessionRoot("/Users/dev"))+func TestDefaultHostSessionRootUsesDotWeknora(t *testing.T) {+ require.Equal(t, "/Users/dev/.weknora/sessions", defaultHostSessionRoot("/Users/dev"))}func TestDefaultHostSkillsRootIsDotWeknora(t *testing.T) {diff --git a/internal/event/event_data.go b/internal/event/event_data.goindex 2a7ce8dce..87309abc5 100644--- a/internal/event/event_data.go+++ b/internal/event/event_data.go@@ -302,6 +302,9 @@ type ToolApprovalRequiredData struct {// GrantLapsed, when set, is why an earlier grant for this call no longer// applies; see types.ToolApprovalPromptRequest.GrantLapsed string `json:"grant_lapsed,omitempty"`+ // Kind is empty for MCP approvals and "host_command" for Lite host commands.+ Kind string `json:"kind,omitempty"`+ Host *HostApprovalPayload `json:"host,omitempty"`}// ToolApprovalResolvedData confirms the user decision (or timeout/cancel).@@ -311,6 +314,22 @@ type ToolApprovalResolvedData struct {Reason string `json:"reason,omitempty"`TimedOut bool `json:"timed_out,omitempty"`Canceled bool `json:"canceled,omitempty"`+ // Scope is "once" or "session" for host approvals.+ Scope string `json:"scope,omitempty"`+}++// HostApprovalPayload describes a Lite host command waiting for the user.+type HostApprovalPayload struct {+ Reason string `json:"reason"`+ Command string `json:"command,omitempty"`+ Cwd string `json:"cwd,omitempty"`+ GrantPath string `json:"grant_path,omitempty"`+ GrantAccess string `json:"grant_access,omitempty"`+ DenialSnippet string `json:"denial_snippet,omitempty"`+ FirstAttemptRan bool `json:"first_attempt_ran,omitempty"`+ AllowSession bool `json:"allow_session"`+ // SessionRules is what "allow for this session" remembers for a delete.+ SessionRules []string `json:"session_rules,omitempty"`}// AgentPromptRequiredData asks the user a question of the given kind.diff --git a/internal/handler/mcp_service.go b/internal/handler/mcp_service.goindex 747de5f82..ff0d755c8 100644--- a/internal/handler/mcp_service.go+++ b/internal/handler/mcp_service.go@@ -4,6 +4,7 @@ import ("context""encoding/json"stderrors "errors"+ "fmt""net/http""strings""time"@@ -862,6 +863,46 @@ type resolveToolApprovalBody struct {// AllowInSession, on approve, also allows later calls of the same kind// in the session, when the prompt offered that.AllowInSession bool `json:"allow_in_session"`+ // Scope and Access are only read by Lite host command approvals.+ Scope string `json:"scope"`+ Access string `json:"access"`+}++func toolApprovalDecision(body resolveToolApprovalBody) (approval.Decision, error) {+ dec := approval.Decision{Reason: body.Reason}+ switch body.Decision {+ case "approve":+ dec.Approved = true+ // Reject "null" / non-object payloads up front. Without this, "null"+ // (4 bytes) passes the len>0 check and the downstream tool sees a nil+ // argument map, silently losing the original args.+ trimmed := strings.TrimSpace(string(body.ModifiedArgs))+ if len(trimmed) > 0 && trimmed != "null" {+ var probe map[string]interface{}+ if err := json.Unmarshal(body.ModifiedArgs, &probe); err != nil || probe == nil {+ return approval.Decision{}, fmt.Errorf("modified_args must be a non-null JSON object")+ }+ dec.ModifiedArgs = body.ModifiedArgs+ }+ dec.AllowInSession = body.AllowInSession+ case "reject":+ dec.Approved = false+ default:+ return approval.Decision{}, fmt.Errorf("decision must be approve or reject")+ }+ switch body.Scope {+ case "", "once", "session":+ dec.Scope = body.Scope+ default:+ return approval.Decision{}, fmt.Errorf("scope must be once or session")+ }+ switch body.Access {+ case "", "read", "write":+ dec.Access = body.Access+ default:+ return approval.Decision{}, fmt.Errorf("access must be read or write")+ }+ return dec, nil}// ResolveToolApproval completes a pending MCP tool approval (agent execution resumes).@@ -897,27 +938,9 @@ func (h *MCPServiceHandler) ResolveToolApproval(c *gin.Context) {c.Error(errors.NewBadRequestError(err.Error()))return}- dec := approval.Decision{Reason: body.Reason}- switch body.Decision {- case "approve":- dec.Approved = true- // Reject "null" / non-object payloads up front. Without this, "null"- // (4 bytes) passes the len>0 check and the downstream tool sees a nil- // argument map, silently losing the original args.- trimmed := strings.TrimSpace(string(body.ModifiedArgs))- if len(trimmed) > 0 && trimmed != "null" {- var probe map[string]interface{}- if err := json.Unmarshal(body.ModifiedArgs, &probe); err != nil || probe == nil {- c.Error(errors.NewBadRequestError("modified_args must be a non-null JSON object"))- return- }- dec.ModifiedArgs = body.ModifiedArgs- }- dec.AllowInSession = body.AllowInSession- case "reject":- dec.Approved = false- default:- c.Error(errors.NewBadRequestError("decision must be approve or reject"))+ dec, err := toolApprovalDecision(body)+ if err != nil {+ _ = c.Error(errors.NewBadRequestError(err.Error()))return}principal, _ := types.PrincipalFromContext(ctx)diff --git a/internal/handler/session/agent_stream_approval_test.go b/internal/handler/session/agent_stream_approval_test.gonew file mode 100644index 000000000..f9308f69c--- /dev/null+++ b/internal/handler/session/agent_stream_approval_test.go@@ -0,0 +1,41 @@+package session++import (+ "testing"++ "github.com/Tencent/WeKnora/internal/event"+ "github.com/Tencent/WeKnora/internal/types"+)++func TestAttachToolApprovalsMatchesTheToolCall(t *testing.T) {+ steps := []types.AgentStep{{+ ToolCalls: []types.ToolCall{{ID: "call-1"}, {ID: "call-2"}},+ }}+ records := []types.ToolApprovalRecord{+ {PendingID: "p2", ToolCallID: "call-2", Resolved: true, Approved: true},+ {PendingID: "p1", ToolCallID: "call-1", Resolved: true, Approved: false},+ {PendingID: "loose", Resolved: true},+ }++ got := attachToolApprovals(steps, records)+ if len(got) != 1 {+ t.Fatalf("steps = %d", len(got))+ }+ approvals := got[0].Approvals+ if len(approvals) != 3 {+ t.Fatalf("approvals = %#v", approvals)+ }+ if approvals[0].PendingID != "p2" || approvals[1].PendingID != "p1" || approvals[2].PendingID != "loose" {+ t.Fatalf("order = %#v", approvals)+ }+}++func TestHostApprovalSnapshotKeepsSessionRules(t *testing.T) {+ got := hostApprovalSnapshot(&event.HostApprovalPayload{+ Reason: "delete", Command: "rm -rf build", AllowSession: true,+ SessionRules: []string{"rm -f -r"},+ })+ if got == nil || len(got.SessionRules) != 1 || got.SessionRules[0] != "rm -f -r" {+ t.Fatalf("snapshot = %#v", got)+ }+}diff --git a/internal/handler/session/agent_stream_handler.go b/internal/handler/session/agent_stream_handler.goindex c47b153b6..d0d663f73 100644--- a/internal/handler/session/agent_stream_handler.go+++ b/internal/handler/session/agent_stream_handler.go@@ -65,6 +65,7 @@ type AgentStreamHandler struct {sandboxIDLookup SandboxIDLookup// State tracking+ toolApprovals []types.ToolApprovalRecordknowledgeRefs []*types.SearchResultfinalAnswer stringanswerSegments []*answerSegment // Per-answer-event-ID accumulation, so superseded preambles can be dropped@@ -382,12 +383,96 @@ func toolApprovalDataToMap(v interface{}) map[string]interface{} {return m}+func (h *AgentStreamHandler) rememberToolApproval(data event.ToolApprovalRequiredData) {+ h.mu.Lock()+ defer h.mu.Unlock()+ h.toolApprovals = append(h.toolApprovals, types.ToolApprovalRecord{+ PendingID: data.PendingID,+ ToolCallID: data.ToolCallID,+ Kind: data.Kind,+ ServiceName: data.ServiceName,+ MCPToolName: data.MCPToolName,+ Description: data.Description,+ ArgsJSON: data.ArgsJSON,+ TimeoutSeconds: data.TimeoutSeconds,+ RequestedAt: data.RequestedAtUnix,+ Host: hostApprovalSnapshot(data.Host),+ })+}++func (h *AgentStreamHandler) resolveRememberedToolApproval(data event.ToolApprovalResolvedData) {+ h.mu.Lock()+ defer h.mu.Unlock()+ for i := range h.toolApprovals {+ if h.toolApprovals[i].PendingID != data.PendingID {+ continue+ }+ h.toolApprovals[i].Resolved = true+ h.toolApprovals[i].Approved = data.Approved+ h.toolApprovals[i].Reason = data.Reason+ h.toolApprovals[i].TimedOut = data.TimedOut+ h.toolApprovals[i].Canceled = data.Canceled+ h.toolApprovals[i].Scope = data.Scope+ return+ }+}++func hostApprovalSnapshot(host *event.HostApprovalPayload) *types.HostApprovalSnapshot {+ if host == nil {+ return nil+ }+ return &types.HostApprovalSnapshot{+ Reason: host.Reason,+ Command: host.Command,+ Cwd: host.Cwd,+ GrantPath: host.GrantPath,+ GrantAccess: host.GrantAccess,+ DenialSnippet: host.DenialSnippet,+ FirstAttemptRan: host.FirstAttemptRan,+ AllowSession: host.AllowSession,+ SessionRules: append([]string(nil), host.SessionRules...),+ }+}++// attachToolApprovals copies each decision onto the step that ran that tool.+// A decision with no matching call stays on the last step.+func attachToolApprovals(steps []types.AgentStep, records []types.ToolApprovalRecord) []types.AgentStep {+ if len(steps) == 0 || len(records) == 0 {+ return steps+ }+ used := make([]bool, len(records))+ for i := range steps {+ for j, rec := range records {+ if used[j] || rec.ToolCallID == "" {+ continue+ }+ for _, call := range steps[i].ToolCalls {+ if call.ID != rec.ToolCallID {+ continue+ }+ steps[i].Approvals = append(steps[i].Approvals, rec)+ used[j] = true+ break+ }+ }+ }+ last := len(steps) - 1+ for j, rec := range records {+ if used[j] {+ continue+ }+ steps[last].Approvals = append(steps[last].Approvals, rec)+ }+ return steps+}+// handleToolApprovalRequired persists MCP tool human-approval prompts for SSE / replay (issue #1173).func (h *AgentStreamHandler) handleToolApprovalRequired(ctx context.Context, evt event.Event) error {data, ok := evt.Data.(event.ToolApprovalRequiredData)if !ok {return nil}+ h.rememberToolApproval(data)meta := toolApprovalDataToMap(data)meta["pending_id"] = data.PendingIDif err := h.streamManager.AppendEvent(h.ctx, h.sessionID, h.assistantMessageID, interfaces.StreamEvent{@@ -409,6 +494,7 @@ func (h *AgentStreamHandler) handleToolApprovalResolved(ctx context.Context, evtif !ok {return nil}+ h.resolveRememberedToolApproval(data)meta := toolApprovalDataToMap(data)meta["pending_id"] = data.PendingIDif err := h.streamManager.AppendEvent(h.ctx, h.sessionID, h.assistantMessageID, interfaces.StreamEvent{@@ -813,6 +899,7 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event// Update agent steps if providedif data.AgentSteps != nil {if steps, ok := data.AgentSteps.([]types.AgentStep); ok {+ steps = attachToolApprovals(steps, h.toolApprovals)h.assistantMessage.AgentSteps = agenttools.SanitizeAgentStepsForStorage(steps)}}diff --git a/internal/handler/session/resource_urls.go b/internal/handler/session/resource_urls.goindex 9fe099f1d..ba3fca175 100644--- a/internal/handler/session/resource_urls.go+++ b/internal/handler/session/resource_urls.go@@ -1,6 +1,7 @@package sessionimport (+ "bytes""context"stderrors "errors""strings"@@ -13,6 +14,32 @@ import ("github.com/gin-gonic/gin")+// streamPushPadding is an SSE comment written after an event that waits on the+// user. A line starting with ':' is ignored by the client, and it is not+// followed by a blank line, so it does not dispatch an empty event.+//+// Lite delivers the page through WKURLSchemeTask. A short trailing chunk on+// that still-open task stays invisible until a later write arrives. The+// approval (or OAuth) prompt is otherwise the last write until the user+// answers, so this comment follows it and pushes that frame to the page.+var streamPushPadding = func() []byte {+ const size = 32 << 10+ buf := make([]byte, 2, size+3)+ buf[0] = ':'+ buf[1] = ' '+ buf = append(buf, bytes.Repeat([]byte{' '}, size)...)+ return append(buf, '\n')+}()++func streamPausesForUser(eventType types.ResponseType) bool {+ switch eventType {+ case types.ResponseTypeToolApprovalRequired, types.ResponseTypeMCPOAuthRequired:+ return true+ default:+ return false+ }+}+// resourceModeError turns a mode-resolution failure into the response the client// should see: a rejected scope is a 403, a typo in the parameter is a 400.func resourceModeError(err error) error {@@ -123,6 +150,10 @@ func emitStreamEvent(}c.SSEvent("message", response)c.Writer.Flush()+ if streamPausesForUser(evt.Type) {+ _, _ = c.Writer.Write(streamPushPadding)+ c.Writer.Flush()+ }}// flushHeldStreamContent emits whatever the holdback buffer still retains, so adiff --git a/internal/handler/session/resource_urls_test.go b/internal/handler/session/resource_urls_test.goindex 302c5bd76..c7ff04793 100644--- a/internal/handler/session/resource_urls_test.go+++ b/internal/handler/session/resource_urls_test.go@@ -6,6 +6,7 @@ import ("mime/multipart""net/http""net/http/httptest"+ "strings""testing""github.com/gin-gonic/gin"@@ -240,6 +241,47 @@ func TestHandleAgentEventsForSSE_FlushesHeldContentOnStop(t *testing.T) {)}+func TestEmitStreamEvent_UserWaitPushesTheFrameWithAnSSEComment(t *testing.T) {+ rewriter := storageurl.NewStreamRewriter(storageurl.NewRewriter(nil, "TEST"))+ for _, eventType := range []types.ResponseType{+ types.ResponseTypeToolApprovalRequired,+ types.ResponseTypeMCPOAuthRequired,+ } {+ t.Run(string(eventType), func(t *testing.T) {+ c, recorder := newTestGinContext(t, "")+ emitStreamEvent(context.Background(), c, interfaces.StreamEvent{+ ID: "wait-1",+ Type: eventType,+ Data: map[string]interface{}{"pending_id": "p1"},+ }, "req-1", rewriter)++ body := recorder.Body.String()+ frame := indexOf(body, `"response_type":"`+string(eventType)+`"`)+ comment := indexOf(body, "\n: ")+ require.GreaterOrEqual(t, frame, 0)+ require.Greater(t, comment, frame)+ line, rest, found := strings.Cut(body[comment+1:], "\n")+ require.True(t, found)+ assert.GreaterOrEqual(t, len(line), 32<<10)+ assert.Empty(t, rest, "the comment must not dispatch an empty event")+ assert.NotContains(t, line, "\n")+ })+ }+}++func TestEmitStreamEvent_AnswerIsNotPadded(t *testing.T) {+ c, recorder := newTestGinContext(t, "")+ rewriter := storageurl.NewStreamRewriter(storageurl.NewRewriter(nil, "TEST"))+ emitStreamEvent(context.Background(), c, interfaces.StreamEvent{+ ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "hello",+ }, "req-1", rewriter)++ body := recorder.Body.String()+ assert.Contains(t, body, `"response_type":"answer"`)+ assert.NotContains(t, body, "\n: ")+ assert.Less(t, len(body), 8<<10)+}+func TestHoldbackKeyRoundTrip(t *testing.T) {responseType, eventID := parseHoldbackKey(holdbackKey(types.ResponseTypeThinking, "think-1"))assert.Equal(t, types.ResponseTypeThinking, responseType)diff --git a/internal/handler/tool_approval_decision_test.go b/internal/handler/tool_approval_decision_test.gonew file mode 100644index 000000000..b2b9263a2--- /dev/null+++ b/internal/handler/tool_approval_decision_test.go@@ -0,0 +1,44 @@+package handler++import (+ "encoding/json"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestToolApprovalDecisionCarriesHostScope(t *testing.T) {+ d, err := toolApprovalDecision(resolveToolApprovalBody{Decision: "approve", Scope: "session", Access: "read"})+ require.NoError(t, err)+ require.True(t, d.Approved)+ require.Equal(t, "session", d.Scope)+ require.Equal(t, "read", d.Access)+}++func TestToolApprovalDecisionRejectsUnknownScopeOrAccess(t *testing.T) {+ _, err := toolApprovalDecision(resolveToolApprovalBody{Decision: "approve", Scope: "forever"})+ require.Error(t, err)+ _, err = toolApprovalDecision(resolveToolApprovalBody{Decision: "approve", Access: "admin"})+ require.Error(t, err)+}++func TestToolApprovalDecisionKeepsMCPBehaviour(t *testing.T) {+ d, err := toolApprovalDecision(resolveToolApprovalBody{+ Decision: "approve", ModifiedArgs: json.RawMessage(`{"a":1}`),+ })+ require.NoError(t, err)+ require.JSONEq(t, `{"a":1}`, string(d.ModifiedArgs))++ _, err = toolApprovalDecision(resolveToolApprovalBody{Decision: "approve", ModifiedArgs: json.RawMessage(`null`)})+ require.NoError(t, err)+ _, err = toolApprovalDecision(resolveToolApprovalBody{Decision: "approve", ModifiedArgs: json.RawMessage(`[1]`)})+ require.Error(t, err)++ d, err = toolApprovalDecision(resolveToolApprovalBody{Decision: "reject", Reason: "no"})+ require.NoError(t, err)+ require.False(t, d.Approved)+ require.Equal(t, "no", d.Reason)++ _, err = toolApprovalDecision(resolveToolApprovalBody{Decision: "maybe"})+ require.Error(t, err)+}diff --git a/internal/localsandbox/adapter/adapter.go b/internal/localsandbox/adapter/adapter.goindex 8478aba6b..f77f87471 100644--- a/internal/localsandbox/adapter/adapter.go+++ b/internal/localsandbox/adapter/adapter.go@@ -52,6 +52,7 @@ var (_ sandbox.SessionWorkspaceLayoutProvider = (*Adapter)(nil)_ sandbox.SessionShellExecutor = (*Adapter)(nil)_ sandbox.SessionFileStore = (*Adapter)(nil)+ _ sandbox.SessionStateReleaser = (*Adapter)(nil))// GetType reports SandboxTypeHost.@@ -68,6 +69,14 @@ func (a *Adapter) VersionsWorkspace(context.Context, string) bool { return false// Cleanup is a no-op; host holds no process-wide resources to tear down.func (a *Adapter) Cleanup(context.Context) error { return nil }+// ReleaseSessionState forgets every approval made in a deleted session.+func (a *Adapter) ReleaseSessionState(_ context.Context, sessionID string) {+ if a == nil || a.svc == nil {+ return+ }+ a.svc.ReleaseSession(sessionID)+}+// Execute is the legacy script entry point. The local sandbox exposes shell// execution only, so callers must use ExecShellCommand.func (a *Adapter) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {@@ -104,7 +113,7 @@ func (a *Adapter) SessionWorkspaceLayout(logger.Warnf(ctx, "[LocalSandbox] layout session=%s: %v", sessionID, err)return sandbox.WorkspaceLayout{}, err}- layout := LayoutFor(ws)+ layout := LayoutFor(ws, a.svc.SessionGrants(sessionID)...)logger.Debugf(ctx, "[LocalSandbox] layout session=%s root=%s", sessionID, layout.Root)return layout, nil}@@ -116,12 +125,15 @@ func (a *Adapter) ExecShellCommand(timeout time.Duration,env map[string]string,) (*sandbox.ExecuteResult, error) {+ approver, review := runApproval(ctx)res, err := a.svc.Run(ctx, localsandbox.RunRequest{- SessionID: sessionID,- Command: command,- WorkDir: workDir,- Timeout: timeout,- Env: env,+ SessionID: sessionID,+ Command: command,+ WorkDir: workDir,+ Timeout: timeout,+ Env: env,+ ReviewCommand: review,+ Approver: approver,})if err != nil {logger.Warnf(ctx, "[LocalSandbox] exec session=%s work_dir=%q: %v", sessionID, workDir, err)@@ -139,11 +151,13 @@ func executeResult(ctx context.Context, sessionID string, res *localsandbox.RunRKilled: res.Exit.Killed,}if res.Denial.IsDenied() {- // A denial is a normal, reportable outcome: the model must see why the- // command failed so it can choose a path inside the workspace.logger.Warnf(ctx, "[LocalSandbox] exec denied session=%s reason=%d path=%q",sessionID, res.Denial.Reason, res.Denial.Path)- out.Stderr += "\n[sandbox] denied by workspace policy"+ }+ if res.Notice != "" {+ // The model must see why the command failed or was refused so it can+ // choose another path instead of retrying the same one.+ out.Stderr += "\n" + res.Notice}return out}diff --git a/internal/localsandbox/adapter/adapter_test.go b/internal/localsandbox/adapter/adapter_test.goindex 1adcb9e2b..c277a147b 100644--- a/internal/localsandbox/adapter/adapter_test.go+++ b/internal/localsandbox/adapter/adapter_test.go@@ -211,7 +211,7 @@ func TestAdapterExecShellCommandAnnotatesDenial(t *testing.T) {res, err := a.ExecShellCommand(context.Background(), "s1", "touch /etc/x", "", 0, nil)require.NoError(t, err)require.Equal(t, 1, res.ExitCode)- require.Contains(t, res.Stderr, "[sandbox] denied by workspace policy")+ require.Contains(t, res.Stderr, "[sandbox] blocked")}func TestAdapterListSessionFilesStopsWalkingAtCap(t *testing.T) {diff --git a/internal/localsandbox/adapter/approval.go b/internal/localsandbox/adapter/approval.gonew file mode 100644index 000000000..89c6b5195--- /dev/null+++ b/internal/localsandbox/adapter/approval.go@@ -0,0 +1,53 @@+package adapter++import (+ "context"++ "github.com/Tencent/WeKnora/internal/localsandbox"+ "github.com/Tencent/WeKnora/internal/sandbox"+)++// approverBridge adapts the agent-side approval port to the sandbox's own+// Approver. It is the only place that knows both vocabularies.+type approverBridge struct{ inner sandbox.CommandApprover }++func (b approverBridge) Approve(+ ctx context.Context, req localsandbox.ApprovalRequest,+) (localsandbox.ApprovalDecision, error) {+ out := sandbox.CommandApprovalRequest{+ SessionID: req.SessionID,+ Command: req.Command,+ Cwd: req.Cwd,+ Reason: string(req.Reason),+ DenialSnippet: req.DenialSnippet,+ FirstAttemptRan: req.FirstAttemptRan,+ AllowSession: req.AllowSession,+ SessionRules: req.SessionRules,+ }+ if req.Proposed != nil {+ out.GrantPath = req.Proposed.Path+ out.GrantAccess = string(req.Proposed.Access)+ }+ d, err := b.inner.ApproveCommand(ctx, out)+ if err != nil {+ return localsandbox.ApprovalDecision{}, err+ }+ decision := localsandbox.ApprovalDecision{Approved: d.Approved, Session: d.Session, Reason: d.Reason}+ if d.Access != "" && req.Proposed != nil {+ decision.Grant = &localsandbox.Grant{Path: req.Proposed.Path, Access: localsandbox.Access(d.Access)}+ }+ return decision, nil+}++// runApproval reads the approval port for one command. Without a port the+// request carries no approver, so the sandbox refuses anything it would ask.+func runApproval(ctx context.Context) (localsandbox.Approver, string) {+ approval, ok := sandbox.CommandApprovalFrom(ctx)+ if !ok {+ return nil, ""+ }+ if approval.Approver == nil {+ return nil, approval.Command+ }+ return approverBridge{inner: approval.Approver}, approval.Command+}diff --git a/internal/localsandbox/adapter/approval_test.go b/internal/localsandbox/adapter/approval_test.gonew file mode 100644index 000000000..7e5a37ae6--- /dev/null+++ b/internal/localsandbox/adapter/approval_test.go@@ -0,0 +1,98 @@+package adapter++import (+ "context"+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/internal/localsandbox"+ "github.com/Tencent/WeKnora/internal/sandbox"+)++type recordingCommandApprover struct {+ decision sandbox.CommandApprovalDecision+ requests []sandbox.CommandApprovalRequest+}++func (r *recordingCommandApprover) ApproveCommand(+ _ context.Context, req sandbox.CommandApprovalRequest,+) (sandbox.CommandApprovalDecision, error) {+ r.requests = append(r.requests, req)+ return r.decision, nil+}++func TestExecShellCommandAsksThroughContextApprover(t *testing.T) {+ a := New(testService(t, &stubBackend{}))+ approver := &recordingCommandApprover{decision: sandbox.CommandApprovalDecision{Approved: true}}+ ctx := sandbox.WithCommandApproval(context.Background(), sandbox.CommandApproval{+ Approver: approver, Command: "rm notes.md",+ })++ res, err := a.ExecShellCommand(ctx, "s1", "wrapped", "", 0, nil)+ require.NoError(t, err)+ require.Equal(t, 0, res.ExitCode)+ require.Len(t, approver.requests, 1)+ require.Equal(t, "delete", approver.requests[0].Reason)+ require.Equal(t, "rm notes.md", approver.requests[0].Command)+}++func TestExecShellCommandRefusesDeleteWithoutApprover(t *testing.T) {+ a := New(testService(t, &stubBackend{}))+ ctx := sandbox.WithCommandApproval(context.Background(), sandbox.CommandApproval{Command: "rm notes.md"})++ res, err := a.ExecShellCommand(ctx, "s1", "wrapped", "", 0, nil)+ require.NoError(t, err)+ require.Equal(t, 1, res.ExitCode)+ require.Contains(t, res.Stderr, "needs the user's approval")+}++func TestApproverBridgeNarrowsOnlyTheProposedPath(t *testing.T) {+ inner := &recordingCommandApprover{decision: sandbox.CommandApprovalDecision{+ Approved: true, Session: true, Access: "read",+ }}+ bridge := approverBridge{inner: inner}+ proposed := localsandbox.Grant{Path: "/Users/dev/other", Access: localsandbox.AccessWrite}++ d, err := bridge.Approve(context.Background(), localsandbox.ApprovalRequest{+ SessionID: "s1", Command: "touch x", Reason: localsandbox.ReasonDenied,+ Proposed: &proposed, FirstAttemptRan: true, AllowSession: true,+ })+ require.NoError(t, err)+ require.True(t, d.Approved)+ require.True(t, d.Session)+ require.Equal(t, &localsandbox.Grant{Path: proposed.Path, Access: localsandbox.AccessRead}, d.Grant)+ req := inner.requests[0]+ require.Equal(t, "sandbox_denied", req.Reason)+ require.Equal(t, proposed.Path, req.GrantPath)+ require.Equal(t, "write", req.GrantAccess)+ require.True(t, req.FirstAttemptRan)+}++func TestApproverBridgePassesSessionRules(t *testing.T) {+ inner := &recordingCommandApprover{decision: sandbox.CommandApprovalDecision{Approved: true}}+ bridge := approverBridge{inner: inner}++ _, err := bridge.Approve(context.Background(), localsandbox.ApprovalRequest{+ SessionID: "s1", Command: "rm -rf build", Reason: localsandbox.ReasonDelete,+ AllowSession: true, SessionRules: []string{"rm -f -r"},+ })+ require.NoError(t, err)+ require.Equal(t, []string{"rm -f -r"}, inner.requests[0].SessionRules)+}++func TestLayoutForAddsSessionGrants(t *testing.T) {+ l := LayoutFor(localsandbox.Workspace{Root: "/w"},+ localsandbox.Grant{Path: "/rw", Access: localsandbox.AccessWrite},+ localsandbox.Grant{Path: "/ro", Access: localsandbox.AccessRead},+ )+ require.Equal(t, []string{"/w", "/rw"}, l.WriteRoots)+ require.Equal(t, []string{"/w", "/rw", "/ro"}, l.ReadRoots)+}++func TestAdapterReleasesSessionState(t *testing.T) {+ var a any = New(nil)+ releaser, ok := a.(sandbox.SessionStateReleaser)+ require.True(t, ok)+ releaser.ReleaseSessionState(context.Background(), "s1")+}diff --git a/internal/localsandbox/adapter/layout.go b/internal/localsandbox/adapter/layout.goindex 50a51e030..3084d0950 100644--- a/internal/localsandbox/adapter/layout.go+++ b/internal/localsandbox/adapter/layout.go@@ -10,17 +10,27 @@ import ()// LayoutFor maps a resolved workspace onto the layout the agent tools consume.+// Session grants the user approved are added so the tool-layer scope checks+// agree with the policy the sandbox enforces.//// The tools enforce this as a convention (what the model is told, and what the// scope errors say). The real enforcement for host file operations is// PathGuard inside the adapter's SessionFileStore, so a mistake here cannot// widen actual access.-func LayoutFor(ws localsandbox.Workspace) sandbox.WorkspaceLayout {+func LayoutFor(ws localsandbox.Workspace, grants ...localsandbox.Grant) sandbox.WorkspaceLayout {+ writeRoots := []string{ws.Root}+ readRoots := []string{ws.Root}+ for _, g := range grants {+ if g.Access == localsandbox.AccessWrite {+ writeRoots = append(writeRoots, g.Path)+ }+ readRoots = append(readRoots, g.Path)+ }return sandbox.WorkspaceLayout{Origin: sandbox.WorkspaceOriginHost,Root: ws.Root,- WriteRoots: []string{ws.Root},- ReadRoots: []string{ws.Root},+ WriteRoots: writeRoots,+ ReadRoots: readRoots,Hint: ws.Root,}}diff --git a/internal/localsandbox/aliases.go b/internal/localsandbox/aliases.goindex 20f802f28..eee2af094 100644--- a/internal/localsandbox/aliases.go+++ b/internal/localsandbox/aliases.go@@ -17,6 +17,10 @@ type (NetworkMode = core.NetworkMode// Command is one execution request.Command = core.Command+ // CommandSegment is one apparent delete inside a shell invocation.+ CommandSegment = core.CommandSegment+ // DeleteRule is the shape of a delete a session approval remembers.+ DeleteRule = core.DeleteRule// ExitStatus is the platform-neutral outcome of one sandboxed process.ExitStatus = core.ExitStatus// Denial is the heuristic verdict on whether a failure came from the sandbox.@@ -47,6 +51,10 @@ type (PolicyBuilder = core.PolicyBuilder// Grant is a permission the user has already approved.Grant = core.Grant+ // Access is what a Grant opens on its path.+ Access = core.Access+ // CommandVerdict is what a command's text says about deleting files.+ CommandVerdict = core.CommandVerdict)const (@@ -64,6 +72,11 @@ const (// ModeFull runs without any sandbox. Not shipped.ModeFull = core.ModeFull+ // AccessRead adds a grant as a readable root.+ AccessRead = core.AccessRead+ // AccessWrite adds a grant as a writable root.+ AccessWrite = core.AccessWrite+// WorkspaceProject is a directory the user picked.WorkspaceProject = core.WorkspaceProject// WorkspaceSession is auto-allocated per session under the session root.@@ -135,3 +148,23 @@ func ClassifyDenial(status ExitStatus, stdout, stderr string) Denial {func ClassifyRunDenial(p Policy, status ExitStatus, stdout, stderr string) Denial {return core.ClassifyRunDenial(p, status, stdout, stderr)}++// ClassifyCommand reports whether command deletes files.+func ClassifyCommand(command, homeDir string) CommandVerdict {+ return core.ClassifyCommand(command, homeDir)+}++// DeleteSegments returns the apparent delete commands inside command.+func DeleteSegments(command, homeDir string) []CommandSegment {+ return core.DeleteSegments(command, homeDir)+}++// DeleteTargets returns the paths visible rm, rmdir and unlink commands remove.+func DeleteTargets(command, homeDir string) []string {+ return core.DeleteTargets(command, homeDir)+}++// DeletesStayBelow reports whether every visible delete stays strictly inside cwd.+func DeletesStayBelow(command, cwd, homeDir string) bool {+ return core.DeletesStayBelow(command, cwd, homeDir)+}diff --git a/internal/localsandbox/approval.go b/internal/localsandbox/approval.gonew file mode 100644index 000000000..117748f53--- /dev/null+++ b/internal/localsandbox/approval.go@@ -0,0 +1,53 @@+package localsandbox++import "context"++// ApprovalReason says why the sandbox is asking the user.+type ApprovalReason string++const (+ // ReasonDelete asks before a command that deletes files runs.+ ReasonDelete ApprovalReason = "delete"+ // ReasonDangerous asks before a recursive delete of root or home. It can+ // only be approved once.+ ReasonDangerous ApprovalReason = "dangerous"+ // ReasonDenied asks to widen the sandbox after it blocked a command.+ ReasonDenied ApprovalReason = "sandbox_denied"+)++// ApprovalRequest is one question for the user.+type ApprovalRequest struct {+ SessionID string+ // Command is what the model wrote, before stdin or skill wrapping.+ Command string+ Cwd string+ Reason ApprovalReason+ // Proposed is the directory approving opens: after a denial, or before a+ // delete that removes something outside the policy. A delete grant is+ // always write; narrowing it to read is ignored.+ Proposed *Grant+ DenialSnippet string+ // FirstAttemptRan warns that approving re-runs the whole command.+ FirstAttemptRan bool+ // AllowSession is false when only a one-time answer is acceptable.+ AllowSession bool+ // SessionRules is what a session approval of a delete remembers, shown+ // on the card: later deletes these rules cover are not asked again.+ SessionRules []string+}++// ApprovalDecision is the user's answer.+type ApprovalDecision struct {+ Approved bool+ // Session remembers the answer for the rest of this session.+ Session bool+ // Grant, when set, may only narrow Proposed from write to read.+ Grant *Grant+ // Reason is returned to the model when the user refuses.+ Reason string+}++// Approver asks the user and blocks for the answer. Any error is a refusal.+type Approver interface {+ Approve(ctx context.Context, req ApprovalRequest) (ApprovalDecision, error)+}diff --git a/internal/localsandbox/core/command.go b/internal/localsandbox/core/command.gonew file mode 100644index 000000000..7d61d0d85--- /dev/null+++ b/internal/localsandbox/core/command.go@@ -0,0 +1,706 @@+package core++import (+ "path"+ "path/filepath"+ "regexp"+ "slices"+ "strings"+)++// CommandVerdict is what a command's text says about deleting files.+type CommandVerdict struct {+ // Deletes is true when any segment removes files or directories.+ Deletes bool+ // Dangerous is true for a recursive delete of the filesystem root or home.+ Dangerous bool+}++// CommandSegment is one apparent command inside a shell invocation, after+// wrappers such as sudo or env are removed. Session approval remembers these+// segments, so a later invocation that contains the same delete does not ask+// again just because the surrounding commands changed.+//+// Opaque segments hide the real delete (a shell -c script, eval, or \rm).+// Their text is the whole command, and they are never remembered for the session.+type CommandSegment struct {+ Text string+ Dangerous bool+ Opaque bool+ // Rule is what a session approval remembers for this segment. It is+ // empty for an opaque segment, which can only be approved once.+ Rule DeleteRule+}++// DeleteRule is the shape of one delete, in the spirit of a Codex prefix+// rule: the program (git with its subcommand) and its options, without the+// operands. Options are a sorted set, so -rf, -fr and -r -f are one rule.+type DeleteRule struct {+ Program string+ Flags []string+}++func (r DeleteRule) String() string {+ if len(r.Flags) == 0 {+ return r.Program+ }+ return r.Program + " " + strings.Join(r.Flags, " ")+}++// Covers reports whether approving r also approves o: the same program with+// no option r lacks. Approving rm -rf covers rm; approving rm does not cover+// rm -rf.+func (r DeleteRule) Covers(o DeleteRule) bool {+ if r.Program == "" || r.Program != o.Program {+ return false+ }+ for _, flag := range o.Flags {+ if !slices.Contains(r.Flags, flag) {+ return false+ }+ }+ return true+}++func deleteRule(words []string) DeleteRule {+ program, args := programName(words[0]), words[1:]+ switch program {+ case "git":+ sub, rest := gitSubcommandArgs(args)+ return DeleteRule{Program: "git " + sub, Flags: optionSet(rest)}+ case "find":+ return DeleteRule{Program: "find", Flags: findActions(args)}+ }+ return DeleteRule{Program: program, Flags: optionSet(args)}+}++// optionSet splits grouped short options (-rf is -r -f), keeps long options+// whole, stops at --, and returns the sorted set.+func optionSet(args []string) []string {+ var flags []string+ for _, a := range args {+ switch {+ case a == "--":+ return sortedUnique(flags)+ case strings.HasPrefix(a, "--"):+ flags = append(flags, a)+ case strings.HasPrefix(a, "-") && len(a) > 1:+ for _, c := range a[1:] {+ flags = append(flags, "-"+string(c))+ }+ }+ }+ return sortedUnique(flags)+}++// findActions is what makes a find command delete. Its filters (-name,+// -type) select files and are left out, like operands.+func findActions(args []string) []string {+ var actions []string+ for i, a := range args {+ switch a {+ case "-delete":+ actions = append(actions, a)+ case "-exec", "-execdir", "-ok", "-okdir":+ if i+1 < len(args) {+ switch p := programName(args[i+1]); p {+ case "rm", "rmdir", "unlink":+ actions = append(actions, a+" "+p)+ }+ }+ }+ }+ return sortedUnique(actions)+}++func sortedUnique(items []string) []string {+ if len(items) == 0 {+ return nil+ }+ slices.Sort(items)+ return slices.Compact(items)+}++var commandSeparators = regexp.MustCompile(`&&|\|\||[;|&\n]`)++// wrapperPrograms run the next word as the real command.+var wrapperPrograms = map[string]bool{+ "sudo": true, "env": true, "command": true, "exec": true, "builtin": true,+ "nice": true, "nohup": true, "time": true, "xargs": true,+}++// wrapperValueOptions take the next word as their value, so that word is not+// the program: xargs -n 1 rm runs rm, not 1.+var wrapperValueOptions = map[string]map[string]bool{+ "xargs": {"-n": true, "-L": true, "-I": true, "-P": true, "-s": true, "-d": true, "-E": true, "-a": true},+ "sudo": {"-u": true, "-g": true, "-C": true, "-h": true, "-p": true, "-U": true},+ "env": {"-u": true, "-C": true, "-S": true},+ "nice": {"-n": true},+}++// shellPrograms run their -c argument as a script.+var shellPrograms = map[string]bool{+ "bash": true, "sh": true, "zsh": true, "dash": true, "ksh": true,+ "mksh": true, "fish": true, "csh": true, "tcsh": true,+}++// substitutionMarkers run a nested command whose text the segment split does+// not see: $(...), `...`, <(...), >(...).+var substitutionMarkers = []string{"$(", "`", "<(", ">("}++// quotedDelete catches delete programs the segment split cannot see, including+// a path or a leading backslash: bash -c "/bin/rm -rf out", \rm -rf out.+// It may only make the verdict stricter.+var quotedDelete = regexp.MustCompile(+ "(^|[\\s'\"(`])[/\\\\]*(?:[\\w.+-]+[/\\\\]+)*\\\\*(rm|rmdir|unlink)(\\s|$)",+)++// escapedDelete is \rm / \rmdir / \unlink, which path.Base does not treat as rm.+var escapedDelete = regexp.MustCompile(`(^|[\s'\"(` + "`" + `])\\(rm|rmdir|unlink)(\s|$)`)++// Folded copies are used where the filesystem itself ignores case, so RM and+// /bin/RM are the same program as rm. Linux stays case-sensitive.+var (+ quotedDeleteFolded = regexp.MustCompile(`(?i)` + quotedDelete.String())+ escapedDeleteFolded = regexp.MustCompile(`(?i)` + escapedDelete.String())+)++// ClassifyCommand reports whether command deletes files. It decides whether to+// ask the user first; it is not a sandbox boundary, and a script can still+// delete files without saying so on the command line.+func ClassifyCommand(command, homeDir string) CommandVerdict {+ segments := DeleteSegments(command, homeDir)+ var v CommandVerdict+ for _, segment := range segments {+ v.Deletes = true+ v.Dangerous = v.Dangerous || segment.Dangerous+ }+ return v+}++// DeleteSegments returns every apparent command in command that removes files.+// A delete the segment split cannot name (quoted, in a shell -c script, in+// eval, behind \rm, or in a command substitution) makes the whole invocation+// one opaque segment, which cannot be remembered for the session. Script text+// is classified again, so find -delete and git clean inside it still count.+func DeleteSegments(command, homeDir string) []CommandSegment {+ out := visibleDeleteSegments(command, homeDir)+ hidden := quotedOrEscapedDelete(command) || nestedScriptDeletes(command, homeDir) ||+ expandedDeleteProgram(command)+ if hidden && len(out) == 0 {+ if text := wholeCommand(command); text != "" {+ out = append(out, CommandSegment{+ Text: text,+ Dangerous: mentionsDangerousDelete(command, homeDir),+ Opaque: true,+ })+ }+ }+ if !hidesDelete(command) || len(out) == 0 {+ return out+ }+ text := wholeCommand(command)+ if text == "" {+ return out+ }+ return []CommandSegment{{+ Text: text,+ Dangerous: segmentDangerous(out) || mentionsDangerousDelete(command, homeDir),+ Opaque: true,+ }}+}++// DeleteTargets returns the operands of visible rm, rmdir and unlink commands,+// with ~ and $HOME expanded. Relative operands stay relative to the command's+// cwd and globs stay as written. Operands built from other variables or+// redirections are skipped, and a command that hides a delete has no targets.+// The result only decides which directory a delete card offers; the sandbox+// still enforces every write.+func DeleteTargets(command, homeDir string) []string {+ if hidesDelete(command) {+ return nil+ }+ var out []string+ for _, segment := range commandSeparators.Split(command, -1) {+ words := shellWords(segment)+ i := programIndex(words)+ if i >= len(words) {+ continue+ }+ switch programName(words[i]) {+ case "rm", "rmdir", "unlink":+ default:+ continue+ }+ for _, arg := range deleteOperands(words[i+1:]) {+ if target, ok := expandHome(arg, homeDir); ok {+ out = append(out, target)+ }+ }+ }+ return out+}++// DeletesStayBelow reports whether every visible delete in command names+// only entries strictly inside cwd. A session approval keys its rules by+// cwd and ignores operands, so it may only cover deletes that cannot reach+// past cwd or empty it at once: ., *, .*, .., an absolute path elsewhere, a+// ~ path, or an operand built from a variable all fail. find and git -C may+// start at cwd itself; their filters and subcommand narrow what they remove.+func DeletesStayBelow(command, cwd, homeDir string) bool {+ if hidesDelete(command) || cwd == "" {+ return false+ }+ for _, segment := range commandSeparators.Split(command, -1) {+ words := shellWords(segment)+ i := programIndex(words)+ if i >= len(words) {+ continue+ }+ args := words[i+1:]+ switch programName(words[i]) {+ case "rm", "rmdir", "unlink":+ for _, arg := range deleteOperands(args) {+ if !operandBelow(arg, cwd, homeDir, false) {+ return false+ }+ }+ case "find":+ if len(findActions(args)) == 0 {+ continue+ }+ for _, root := range findRoots(args) {+ if !operandBelow(root, cwd, homeDir, true) {+ return false+ }+ }+ case "git":+ if sub, _ := gitSubcommandArgs(args); sub != "rm" && sub != "clean" {+ continue+ }+ for j := 0; j+1 < len(args); j++ {+ if args[j] == "-C" && !operandBelow(args[j+1], cwd, homeDir, true) {+ return false+ }+ }+ }+ }+ return true+}++func deleteOperands(args []string) []string {+ var out []string+ operands := false+ for _, arg := range args {+ if !operands {+ if arg == "--" {+ operands = true+ continue+ }+ if strings.HasPrefix(arg, "-") && len(arg) > 1 {+ continue+ }+ }+ out = append(out, arg)+ }+ return out+}++// findRoots are the start paths before find's first expression; none means ".".+func findRoots(args []string) []string {+ var roots []string+ for _, arg := range args {+ if strings.HasPrefix(arg, "-") || arg == "(" || arg == "!" {+ break+ }+ roots = append(roots, arg)+ }+ if len(roots) == 0 {+ return []string{"."}+ }+ return roots+}++// operandBelow reports whether arg names an entry strictly inside cwd, or+// cwd itself when allowCwd is set.+func operandBelow(arg, cwd, homeDir string, allowCwd bool) bool {+ target, ok := expandHome(arg, homeDir)+ if !ok {+ return false+ }+ if filepath.IsAbs(target) {+ rel, err := filepath.Rel(filepath.Clean(cwd), filepath.Clean(target))+ if err != nil {+ return false+ }+ target = rel+ }+ target = filepath.Clean(target)+ if target == "." {+ return allowCwd+ }+ if target == ".." || strings.HasPrefix(target, "../") {+ return false+ }+ first, _, _ := strings.Cut(filepath.ToSlash(target), "/")+ return strings.Trim(first, "*.") != "" || strings.Contains(target, "/")+}++func expandHome(arg, homeDir string) (string, bool) {+ if strings.ContainsAny(arg, "<>") {+ return "", false+ }+ for _, prefix := range []string{"~", "$HOME", "${HOME}"} {+ if arg != prefix && !strings.HasPrefix(arg, prefix+"/") {+ continue+ }+ if homeDir == "" {+ return "", false+ }+ return filepath.Join(homeDir, strings.TrimPrefix(arg, prefix)), true+ }+ if strings.ContainsAny(arg, "$`") || strings.HasPrefix(arg, "~") {+ return "", false+ }+ return arg, true+}++// shellWords splits one segment the way the shell groups plain words: quotes+// join, a backslash escapes the next character. Expansions stay as text.+func shellWords(segment string) []string {+ var words []string+ var cur strings.Builder+ inWord := false+ var quote byte+ flush := func() {+ if w := strings.Trim(cur.String(), "(){}"); inWord && w != "" {+ words = append(words, w)+ }+ cur.Reset()+ inWord = false+ }+ for i := 0; i < len(segment); i++ {+ c := segment[i]+ switch {+ case quote != 0:+ switch {+ case c == quote:+ quote = 0+ case c == '\\' && quote == '"' && i+1 < len(segment):+ i+++ cur.WriteByte(segment[i])+ default:+ cur.WriteByte(c)+ }+ case c == '\'' || c == '"':+ quote = c+ inWord = true+ case c == '\\' && i+1 < len(segment):+ i+++ cur.WriteByte(segment[i])+ inWord = true+ case c == ' ' || c == '\t' || c == '\r':+ flush()+ default:+ cur.WriteByte(c)+ inWord = true+ }+ }+ flush()+ return words+}++func wholeCommand(command string) string {+ return strings.Join(strings.Fields(command), " ")+}++func visibleDeleteSegments(command, homeDir string) []CommandSegment {+ var out []CommandSegment+ for _, segment := range commandSeparators.Split(command, -1) {+ words := shellWords(segment)+ deletes, dangerous := classifySegment(words, homeDir)+ if !deletes {+ continue+ }+ text := apparentCommand(words)+ if text == "" {+ continue+ }+ out = append(out, CommandSegment{+ Text: text,+ Dangerous: dangerous,+ Rule: deleteRule(words[programIndex(words):]),+ })+ }+ return out+}++// deleteProgramText finds a delete program name anywhere in the text, so an+// expansion that assembles one (${RM:-rm}, x=rm; $x, $(printf rm)) is caught.+var (+ deleteProgramText = regexp.MustCompile(`rm|unlink`)+ deleteProgramTextFolded = regexp.MustCompile(`(?i)rm|unlink`)+)++// expandedDeleteProgram reports a segment whose program is itself an+// expansion while the command mentions a delete program. The real program+// is only known when the shell runs it, so it is treated as a hidden delete.+func expandedDeleteProgram(command string) bool {+ text := deleteProgramText+ if caseInsensitivePaths() {+ text = deleteProgramTextFolded+ }+ if !text.MatchString(command) {+ return false+ }+ for _, segment := range commandSeparators.Split(command, -1) {+ words := shellWords(segment)+ if i := programIndex(words); i < len(words) && strings.ContainsAny(words[i], "$`") {+ return true+ }+ }+ return false+}++func quotedOrEscapedDelete(command string) bool {+ return quotedDeletePattern().MatchString(command) || escapedDeletePattern().MatchString(command)+}++func quotedDeletePattern() *regexp.Regexp {+ if caseInsensitivePaths() {+ return quotedDeleteFolded+ }+ return quotedDelete+}++func escapedDeletePattern() *regexp.Regexp {+ if caseInsensitivePaths() {+ return escapedDeleteFolded+ }+ return escapedDelete+}++// programName is the command name used for classification. On a+// case-insensitive filesystem, RM, /bin/RM, and rm.exe are all rm.+func programName(word string) string {+ base := path.Base(word)+ if i := strings.LastIndexAny(base, `/\`); i >= 0 {+ base = base[i+1:]+ }+ if !caseInsensitivePaths() {+ return base+ }+ base = strings.ToLower(base)+ return strings.TrimSuffix(base, ".exe")+}++// nestedScriptDeletes classifies the body of bash/sh/zsh -c and eval. The+// outer program is the shell, so the visible pass never sees find or git.+func nestedScriptDeletes(command, homeDir string) bool {+ return scriptsDelete(hiddenScripts(command), homeDir, 0)+}++func scriptsDelete(scripts []string, homeDir string, depth int) bool {+ if depth > 6 {+ return false+ }+ for _, script := range scripts {+ script = strings.TrimSpace(script)+ if script == "" {+ continue+ }+ if len(visibleDeleteSegments(script, homeDir)) > 0 || quotedOrEscapedDelete(script) {+ return true+ }+ if scriptsDelete(hiddenScripts(script), homeDir, depth+1) {+ return true+ }+ }+ return false+}++// hiddenScripts returns the command text passed to a shell -c or eval.+func hiddenScripts(command string) []string {+ var scripts []string+ for _, segment := range commandSeparators.Split(command, -1) {+ if script, ok := segmentScript(shellWords(segment)); ok && script != "" {+ scripts = append(scripts, script)+ }+ }+ return scripts+}++// segmentScript reports whether words run a script given on the command+// line (eval, or a shell with -c) and returns that script.+func segmentScript(words []string) (string, bool) {+ i := programIndex(words)+ if i >= len(words) {+ return "", false+ }+ program, args := programName(words[i]), words[i+1:]+ if program == "eval" {+ return strings.Join(args, " "), true+ }+ if !shellPrograms[program] {+ return "", false+ }+ for j, arg := range args {+ if arg == "-c" || (strings.HasPrefix(arg, "-") && !strings.HasPrefix(arg, "--") && strings.Contains(arg, "c")) {+ return strings.Join(args[j+1:], " "), true+ }+ }+ return "", false+}++func segmentDangerous(segments []CommandSegment) bool {+ for _, segment := range segments {+ if segment.Dangerous {+ return true+ }+ }+ return false+}++// hidesDelete reports scripts, substitutions, and escapes whose real command+// is not the segment the splitter classified.+func hidesDelete(command string) bool {+ if escapedDeletePattern().MatchString(command) || expandedDeleteProgram(command) {+ return true+ }+ for _, marker := range substitutionMarkers {+ if strings.Contains(command, marker) {+ return true+ }+ }+ for _, segment := range commandSeparators.Split(command, -1) {+ if _, ok := segmentScript(shellWords(segment)); ok {+ return true+ }+ }+ return false+}++func mentionsDangerousDelete(command, homeDir string) bool {+ flat := strings.NewReplacer("'", " ", `"`, " ", "`", " ", `\`, " ").Replace(command)+ words := strings.Fields(flat)+ for i := 0; i < len(words); i++ {+ if programName(words[i]) != "rm" {+ continue+ }+ if recursiveOnHome(words[i+1:], homeDir) {+ return true+ }+ }+ return false+}++// apparentCommand is the program and its arguments, without leading wrappers.+// The program is its base name, so /bin/rm and rm are the same segment.+func apparentCommand(words []string) string {+ i := programIndex(words)+ if i >= len(words) {+ return ""+ }+ words = append([]string(nil), words[i:]...)+ words[0] = programName(words[0])+ return strings.Join(words, " ")+}++func programIndex(words []string) int {+ wrapper := ""+ for i := 0; i < len(words); i++ {+ word := words[i]+ switch {+ case isAssignment(word):+ case wrapperPrograms[programName(word)]:+ wrapper = programName(word)+ case strings.HasPrefix(word, "-"):+ if wrapperValueOptions[wrapper][word] {+ i+++ }+ default:+ return i+ }+ }+ return len(words)+}++func classifySegment(words []string, homeDir string) (deletes, dangerous bool) {+ i := programIndex(words)+ if i >= len(words) {+ return false, false+ }+ program, args := programName(words[i]), words[i+1:]+ switch program {+ case "rm":+ return true, recursiveOnHome(args, homeDir)+ case "rmdir", "unlink":+ return true, false+ case "git":+ sub, _ := gitSubcommandArgs(args)+ return sub == "rm" || sub == "clean", false+ case "find":+ return len(findActions(args)) > 0, false+ }+ return false, false+}++func isAssignment(word string) bool {+ eq := strings.IndexByte(word, '=')+ return eq > 0 && !strings.HasPrefix(word, "-")+}++// gitSubcommandArgs returns git's subcommand and the arguments after it,+// skipping global options such as -C dir.+func gitSubcommandArgs(args []string) (string, []string) {+ for i := 0; i < len(args); i++ {+ switch {+ case args[i] == "-C" || args[i] == "-c":+ i+++ case strings.HasPrefix(args[i], "-"):+ default:+ return args[i], args[i+1:]+ }+ }+ return "", nil+}++func recursiveOnHome(args []string, homeDir string) bool {+ recursive := false+ var targets []string+ for _, a := range args {+ switch {+ case a == "--recursive":+ recursive = true+ case strings.HasPrefix(a, "--"):+ case strings.HasPrefix(a, "-") && len(a) > 1:+ if strings.ContainsAny(a[1:], "rR") {+ recursive = true+ }+ default:+ targets = append(targets, a)+ }+ }+ if !recursive {+ return false+ }+ for _, target := range targets {+ if isRootOrHome(target, homeDir) {+ return true+ }+ }+ return false+}++func isRootOrHome(target, homeDir string) bool {+ switch strings.TrimRight(target, "/") {+ case "", "/*", "~", "~/*", "$HOME", "${HOME}", "$HOME/*":+ return true+ }+ if homeDir == "" {+ return false+ }+ home := path.Clean(homeDir)+ clean := path.Clean(target)+ return clean == home || clean == home+"/*"+}diff --git a/internal/localsandbox/core/command_test.go b/internal/localsandbox/core/command_test.gonew file mode 100644index 000000000..457007373--- /dev/null+++ b/internal/localsandbox/core/command_test.go@@ -0,0 +1,288 @@+package core++import (+ "strings"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestClassifyCommandDetectsDeletes(t *testing.T) {+ const home = "/Users/dev"+ cases := []struct {+ command string+ deletes bool+ dangerous bool+ }{+ {"ls -la", false, false},+ {"echo hi > a.txt", false, false},+ {"docker run --rm alpine true", false, false},+ {"git status", false, false},+ {"rm a.txt", true, false},+ {"rm -f build/*.o", true, false},+ {"rmdir empty", true, false},+ {"unlink a.txt", true, false},+ {"/bin/rm a.txt", true, false},+ {"sudo rm a.txt", true, false},+ {"env FOO=1 rm a.txt", true, false},+ {"FOO=1 rm a.txt", true, false},+ {"find . -name '*.o' | xargs rm", true, false},+ {"git status && rm -rf dist", true, false},+ {"ls; rm a.txt", true, false},+ {"git rm a.txt", true, false},+ {"git -C repo rm a.txt", true, false},+ {"git clean -fdx", true, false},+ {`git -C "my repo" clean -fd`, true, false},+ {`git -C my\ repo clean -fd`, true, false},+ {"find . -name '*.tmp' -delete", true, false},+ {"find . -name '*.tmp' -exec rm {} +", true, false},+ {"find . -type f -print", false, false},+ {`bash -c "rm -rf out"`, true, false},+ {`bash -c "/bin/rm -rf out"`, true, false},+ {`bash -c "find . -delete"`, true, false},+ {`sh -c "git clean -fdx"`, true, false},+ {`eval "find /path -delete"`, true, false},+ {`zsh -lc "find . -exec rm {} +"`, true, false},+ {`bash -c "echo hi"`, false, false},+ {`bash -c "git status"`, false, false},+ {`bash -c "find . -type f -print"`, false, false},+ {`\rm -rf out`, true, false},+ {"rm a.txt; bash -c 'rm -rf .'", true, false},+ {`rm a.txt && sh -c "rm -rf ~"`, true, true},+ {"rm -rf ~", true, true},+ {"rm -rf ~/", true, true},+ {"rm -r $HOME", true, true},+ {"rm -Rf /Users/dev", true, true},+ {"rm --recursive /Users/dev/", true, true},+ {"rm -rf ~/*", true, true},+ {"rm -f ~", true, false},+ {"rm -rf ~/project/dist", true, false},+ }+ for _, tc := range cases {+ got := ClassifyCommand(tc.command, home)+ require.Equal(t, tc.deletes, got.Deletes, "deletes: %s", tc.command)+ require.Equal(t, tc.dangerous, got.Dangerous, "dangerous: %s", tc.command)+ }+}++func TestDeleteSegmentsKeepsOnlyTheDelete(t *testing.T) {+ got := DeleteSegments("git status && sudo rm -f a.txt && echo ok", "/Users/dev")+ require.Equal(t, []CommandSegment{{+ Text: "rm -f a.txt", Rule: DeleteRule{Program: "rm", Flags: []string{"-f"}},+ }}, got)+}++func TestDeleteSegmentsNormalizesTheProgramName(t *testing.T) {+ got := DeleteSegments("/bin/rm a.txt", "/Users/dev")+ require.Equal(t, []CommandSegment{{Text: "rm a.txt", Rule: DeleteRule{Program: "rm"}}}, got)+}++// The rule is the shape of the delete, like a Codex prefix rule: operands+// drop out, and option order or grouping does not matter.+func TestDeleteSegmentsDeriveARuleWithoutOperands(t *testing.T) {+ cases := []struct {+ command string+ rule string+ }{+ {"rm a.txt", "rm"},+ {"rm a.txt b.txt", "rm"},+ {"rm -rf build", "rm -f -r"},+ {"rm -fr dist", "rm -f -r"},+ {"rm -r -f out", "rm -f -r"},+ {"sudo /bin/rm -f a", "rm -f"},+ {"rm --recursive --force a", "rm --force --recursive"},+ {"rm -- -f", "rm"},+ {"rmdir -p a/b", "rmdir -p"},+ {"unlink a", "unlink"},+ {"git rm --cached a.txt", "git rm --cached"},+ {"git -C repo clean -fdx", "git clean -d -f -x"},+ {`git -C "my repo" clean -fdx`, "git clean -d -f -x"},+ {"find . -name '*.o' -delete", "find -delete"},+ {"find src -type f -exec rm {} +", "find -exec rm"},+ {"ls | xargs -n 1 rm -f", "rm -f"},+ }+ for _, tc := range cases {+ got := DeleteSegments(tc.command, "/Users/dev")+ require.Len(t, got, 1, tc.command)+ require.Equal(t, tc.rule, got[0].Rule.String(), tc.command)+ }+}++// The sandbox needs to know where a delete lands before it runs, so a delete+// outside the workspace can ask for that directory on the same card.+func TestDeleteTargetsNamesTheOperandsOfVisibleDeletes(t *testing.T) {+ home := "/Users/dev"+ cases := []struct {+ command string+ want []string+ }{+ {"rm a.txt", []string{"a.txt"}},+ {"rm -rf ~/Desktop/dir", []string{"/Users/dev/Desktop/dir"}},+ {"sudo rm -f $HOME/a ${HOME}/b ~", []string{"/Users/dev/a", "/Users/dev/b", "/Users/dev"}},+ {"rm -- -f", []string{"-f"}},+ {"ls && rmdir out && unlink /tmp/x", []string{"out", "/tmp/x"}},+ {"rm \"/Users/dev/My File.txt\" 'b c'", []string{"/Users/dev/My File.txt", "b c"}},+ {`rm my\ file.txt`, []string{"my file.txt"}},+ {"rm $TMPDIR/x", nil},+ {"git clean -fdx", nil},+ {"find . -delete", nil},+ {"echo hi", nil},+ }+ for _, tc := range cases {+ require.Equal(t, tc.want, DeleteTargets(tc.command, home), tc.command)+ }+}++func TestDeleteRuleCoversTheSameProgramWithFewerOptions(t *testing.T) {+ rf := DeleteRule{Program: "rm", Flags: []string{"-f", "-r"}}+ require.True(t, rf.Covers(DeleteRule{Program: "rm", Flags: []string{"-f", "-r"}}))+ require.True(t, rf.Covers(DeleteRule{Program: "rm", Flags: []string{"-r"}}))+ require.True(t, rf.Covers(DeleteRule{Program: "rm"}))+ require.False(t, rf.Covers(DeleteRule{Program: "rm", Flags: []string{"-f", "-r", "-v"}}))+ require.False(t, rf.Covers(DeleteRule{Program: "rmdir"}))+ require.False(t, DeleteRule{Program: "rm"}.Covers(rf), "a plain rm must not open a recursive one")+ require.False(t, DeleteRule{}.Covers(DeleteRule{}), "an empty rule covers nothing")+}++// Without these, an approved visible rm would let a hidden delete next to it+// run unasked.+func TestDeleteSegmentsTreatsSubstitutionsAndOtherShellsAsOpaque(t *testing.T) {+ for _, command := range []string{+ "rm a.txt; echo $(rm -rf .)",+ "rm a.txt; echo `rm -rf .`",+ "rm a.txt; cat <(rm -rf .)",+ "rm a.txt; dash -c 'rm -rf .'",+ "rm a.txt; ksh -c 'rm -rf .'",+ "echo $(rm -rf .)",+ } {+ got := DeleteSegments(command, "/Users/dev")+ require.Len(t, got, 1, command)+ require.True(t, got[0].Opaque, command)+ require.Equal(t, DeleteRule{}, got[0].Rule, command)+ }+}++// The shell assembles the program at run time, so the text cannot name it.+func TestDeleteSegmentsTreatsAnExpandedProgramAsOpaque(t *testing.T) {+ for _, command := range []string{+ "${RM:-rm} -rf build",+ "x=rm; $x -rf build",+ "$(printf rm) -rf build",+ "`echo rm` -rf build",+ "sudo $DEL_BIN unlink-me",+ } {+ got := DeleteSegments(command, "/Users/dev")+ require.Len(t, got, 1, command)+ require.True(t, got[0].Opaque, command)+ require.Nil(t, DeleteTargets(command, "/Users/dev"), command)+ }+ require.Empty(t, DeleteSegments("$PYTHON build.py", "/Users/dev"))+}++// A session rule ignores operands, so it may only cover deletes that stay+// strictly inside the cwd it was approved in.+func TestDeletesStayBelow(t *testing.T) {+ const home = "/Users/dev"+ const cwd = "/Users/dev/proj"+ cases := []struct {+ command string+ below bool+ }{+ {"rm a.txt", true},+ {"rm -rf build dist/cache", true},+ {"rm -f *.log", true},+ {"rm -rf */node_modules", true},+ {"rm -rf /Users/dev/proj/build", true},+ {"ls | xargs rm -f", true},+ {"find . -name '*.tmp' -delete", true},+ {"find -name '*.tmp' -delete", true},+ {"find src -type f -exec rm {} +", true},+ {"git clean -fdx", true},+ {"git -C sub rm a.txt", true},+ {"echo hi", true},+ {"rm -rf .", false},+ {"rm -rf ./", false},+ {"rm -rf *", false},+ {"rm -rf .*", false},+ {"rm -rf ./*", false},+ {"rm -rf ..", false},+ {"rm -rf ../other", false},+ {"rm -rf build/../..", false},+ {"rm -rf /Users/dev/proj", false},+ {"rm -rf /Users/dev/Desktop/a", false},+ {"rm -rf ~/Desktop/*", false},+ {"rm -rf $DIR", false},+ {"rm a.txt && rm -rf ../x", false},+ {"find .. -delete", false},+ {"find /tmp -name x -delete", false},+ {"git -C .. clean -fdx", false},+ {"bash -c 'rm a.txt'", false},+ }+ for _, tc := range cases {+ require.Equal(t, tc.below, DeletesStayBelow(tc.command, cwd, home), tc.command)+ }+ require.False(t, DeletesStayBelow("rm a.txt", "", home))+}++func TestClassifyCommandProgramCaseFollowsTheFilesystem(t *testing.T) {+ const home = "/Users/dev"+ want := caseInsensitivePaths()+ for _, command := range []string{+ "RM -rf dir",+ "/bin/RM -rf dir",+ `BASH -c "find . -delete"`,+ "FIND . -delete",+ "GIT clean -fdx",+ "SUDO RM a.txt",+ `\RM -rf out`,+ "rm.exe a.txt",+ `RM.EXE -rf dir`,+ } {+ require.Equal(t, want, ClassifyCommand(command, home).Deletes, command)+ }+ require.Equal(t, want, ClassifyCommand("RM -rf ~", home).Dangerous)+ require.False(t, ClassifyCommand("docker run --RM alpine true", home).Deletes)+ require.False(t, ClassifyCommand("git CLEAN -fdx", home).Deletes)+ require.False(t, ClassifyCommand("FIND . -DELETE", home).Deletes)+ if want {+ require.Equal(t, []CommandSegment{{Text: "rm a.txt", Rule: DeleteRule{Program: "rm"}}},+ DeleteSegments("/bin/RM a.txt", home))+ require.Equal(t, []CommandSegment{{+ Text: "rm -rf ~", Dangerous: true, Rule: DeleteRule{Program: "rm", Flags: []string{"-f", "-r"}},+ }}, DeleteSegments("RM -rf ~", home))+ } else {+ require.Empty(t, DeleteSegments("/bin/RM a.txt", home))+ }+}++func TestDeleteSegmentsKeepsAQuotedDeleteAsTheWholeCommand(t *testing.T) {+ got := DeleteSegments(`bash -c "rm -rf out"`, "/Users/dev")+ require.Equal(t, []CommandSegment{{+ Text: `bash -c "rm -rf out"`, Opaque: true,+ }}, got)+}++func TestDeleteSegmentsDoesNotLetAVisibleRmCoverAHiddenOne(t *testing.T) {+ home := "/Users/dev"+ cases := []struct {+ command string+ dangerous bool+ }{+ {"rm a.txt; bash -c 'rm -rf .'", false},+ {`rm a.txt && sh -c "rm -rf ~"`, true},+ {`bash -c "/bin/rm -rf out"`, false},+ {`\rm -rf out`, false},+ {`bash -c "find . -delete"`, false},+ {`sh -c "git clean -fdx"`, false},+ {`eval "find /path -delete"`, false},+ {"rm a.txt; bash -c 'find . -delete'", false},+ }+ for _, tc := range cases {+ got := DeleteSegments(tc.command, home)+ require.Equal(t, []CommandSegment{{+ Text: strings.Join(strings.Fields(tc.command), " "),+ Dangerous: tc.dangerous,+ Opaque: true,+ }}, got, tc.command)+ }+}diff --git a/internal/localsandbox/core/denial.go b/internal/localsandbox/core/denial.goindex b17ea6601..039891c6a 100644--- a/internal/localsandbox/core/denial.go+++ b/internal/localsandbox/core/denial.go@@ -64,6 +64,11 @@ var denialPathPattern = regexp.MustCompile(`\s*:\s*(?:operation not permitted|permission denied|read-only file system)`)// ClassifyDenial inspects a failed execution for signs of a sandbox denial.+//+// Exit code 0 is success, including a compound command whose earlier segment+// was denied and whose later segment succeeded. Treating that as a denial+// would ask the user to approve a command that already finished, then run+// the whole command again.func ClassifyDenial(status ExitStatus, stdout, stderr string) Denial {if status.Killed || status.Code == 0 {return Denial{}@@ -75,6 +80,7 @@ func ClassifyDenial(status ExitStatus, stdout, stderr string) Denial {}combined := stderr + "\n" + stdout+ path := firstDenialPath(combined)lowered := strings.ToLower(combined)for _, marker := range denialMarkers {if !strings.Contains(lowered, marker.needle) {@@ -82,7 +88,7 @@ func ClassifyDenial(status ExitStatus, stdout, stderr string) Denial {}return Denial{Reason: marker.reason,- Path: firstDenialPath(combined),+ Path: path,Snippet: truncateSnippet(combined),}}diff --git a/internal/localsandbox/core/denial_test.go b/internal/localsandbox/core/denial_test.goindex 165213c11..6ff2046a2 100644--- a/internal/localsandbox/core/denial_test.go+++ b/internal/localsandbox/core/denial_test.go@@ -13,6 +13,13 @@ func TestClassifyDenialIgnoresSuccess(t *testing.T) {require.False(t, d.IsDenied())}+func TestClassifyDenialIgnoresExitZeroEvenWhenOutputNamesAPath(t *testing.T) {+ d := ClassifyDenial(ExitStatus{Code: 0}, "",+ "bash: /Users/dev/Desktop/probe.txt: Operation not permitted")+ require.Equal(t, DenialNone, d.Reason)+ require.False(t, d.IsDenied())+}+func TestClassifyDenialDetectsOperationNotPermitted(t *testing.T) {d := ClassifyDenial(ExitStatus{Code: 1}, "","touch: /Users/dev/outside.txt: Operation not permitted")diff --git a/internal/localsandbox/core/escalation.go b/internal/localsandbox/core/escalation.gonew file mode 100644index 000000000..c6f40a72e--- /dev/null+++ b/internal/localsandbox/core/escalation.go@@ -0,0 +1,228 @@+package core++import (+ "fmt"+ "os"+ "path/filepath"+ "strings"+)++// systemRoots are never offered as grants: writing under them is something the+// user should do by hand, not approve for an agent from a card.+var systemRoots = []string{"/System", "/usr", "/bin", "/sbin", "/etc", "/private/etc", "/Library"}++// ProposeGrant returns the directory a denied command would need, or false+// when the denial cannot be tied to a path this policy actually withholds.+// The path parsed from output is only a hint; the PathGuard re-check is what+// makes the proposal. The proposal is always read-write: the user may narrow+// it to read-only on the card, never widen it.+func (b *PolicyBuilder) ProposeGrant(p Policy, d Denial, cwd string) (Grant, bool) {+ if !d.IsDenied() || d.Path == "" {+ return Grant{}, false+ }+ target := d.Path+ if !filepath.IsAbs(target) {+ if cwd == "" {+ return Grant{}, false+ }+ target = filepath.Join(cwd, target)+ }+ target = filepath.Clean(target)+ if _, err := NewPathGuard(p).CheckWrite(target); err == nil {+ return Grant{}, false+ }+ // The card and the stored grant use the resolved path. A symlink inside+ // the workspace must not be offered as if it were that workspace path.+ resolved, err := resolveExistingPrefix(target)+ if err != nil {+ return Grant{}, false+ }+ dir, ok := grantDirectory(resolved)+ if !ok || b.rejectGrantPath(p, resolved) != nil || b.rejectGrantPath(p, dir) != nil {+ return Grant{}, false+ }+ return Grant{Path: dir, Access: AccessWrite}, true+}++// rejectGrantPath is the check ProposeGrant and Relax share. path must already+// be absolute; callers resolve symlinks first so a later EvalSymlinks in the+// seatbelt backend cannot widen the grant.+func (b *PolicyBuilder) rejectGrantPath(p Policy, path string) error {+ if err := b.rejectBroadWorkspace(path); err != nil {+ return err+ }+ for _, deny := range p.DenyRead {+ denyPath := deny+ if resolved, err := resolveExistingPrefix(deny); err == nil {+ denyPath = resolved+ }+ if PathUnder(path, deny) || PathUnder(path, denyPath) {+ return fmt.Errorf("localsandbox: %q is read-denied and cannot be granted", path)+ }+ }+ for _, root := range systemRoots {+ if PathUnder(path, root) {+ return fmt.Errorf("%w: %q", ErrWorkspaceTooBroad, path)+ }+ }+ if err := b.rejectAppOwnedPath(path); err != nil {+ return err+ }+ if err := b.rejectHomeDotPath(path); err != nil {+ return err+ }+ if err := rejectGitMetadata(p, path); err != nil {+ return err+ }+ return nil+}++// rejectGitMetadata refuses a grant inside repository metadata: a .git+// directory anywhere, or a read-only subpath the policy already protects+// (such as the directory a .git file points to).+func rejectGitMetadata(p Policy, path string) error {+ if hasGitComponent(path) {+ return fmt.Errorf("localsandbox: %q is git metadata and cannot be granted", path)+ }+ for _, root := range p.WritableRoots {+ for _, ro := range root.ReadOnlySubpaths {+ roPath := ro+ if resolved, err := resolveExistingPrefix(ro); err == nil {+ roPath = resolved+ }+ if PathUnder(path, ro) || PathUnder(path, roPath) {+ return fmt.Errorf("localsandbox: %q is read-only and cannot be granted", path)+ }+ }+ }+ return nil+}++// rejectAppOwnedPath refuses the skills tree, the session tree, and the+// application directory that contains them. A grant of ~/.weknora, or of+// one skill or another session's workspace, would let this session rewrite+// files every session trusts.+func (b *PolicyBuilder) rejectAppOwnedPath(path string) error {+ for _, root := range b.appOwnedRoots() {+ resolved := root+ if candidate, err := resolveExistingPrefix(root); err == nil {+ resolved = candidate+ }+ if PathUnder(path, root) || PathUnder(path, resolved) || PathUnder(root, path) || PathUnder(resolved, path) {+ return fmt.Errorf("%w: %q belongs to the application", ErrWorkspaceTooBroad, path)+ }+ }+ return nil+}++// rejectHomeDotPath refuses anything under a dot entry of the home directory.+// Toolchain bins (~/.local/bin, ~/.cargo/bin), shell and git config+// (~/.config/fish, ~/.config/git) and version managers (~/.nvm) live there,+// and the user runs what they hold outside the sandbox: a write grant on one+// of them is a persistent escape, and a read grant exposes tokens and state.+func (b *PolicyBuilder) rejectHomeDotPath(path string) error {+ if b.homeDir == "" || isFilesystemRoot(filepath.Clean(b.homeDir)) {+ return nil+ }+ homes := []string{filepath.Clean(b.homeDir)}+ if resolved, err := resolveExistingPrefix(homes[0]); err == nil && resolved != homes[0] {+ homes = append(homes, resolved)+ }+ parts := strings.Split(filepath.ToSlash(path), "/")+ for _, home := range homes {+ if !PathUnder(path, home) || samePath(path, home) {+ continue+ }+ depth := len(strings.Split(filepath.ToSlash(home), "/"))+ if depth < len(parts) && strings.HasPrefix(parts[depth], ".") {+ return fmt.Errorf("%w: %q is a hidden directory in home", ErrWorkspaceTooBroad, path)+ }+ }+ return nil+}++func (b *PolicyBuilder) appOwnedRoots() []string {+ var roots []string+ seen := map[string]bool{}+ add := func(p string) {+ p = filepath.Clean(strings.TrimSpace(p))+ if p == "" || p == "." || !filepath.IsAbs(p) || isFilesystemRoot(p) || samePath(p, b.homeDir) || seen[p] {+ return+ }+ seen[p] = true+ roots = append(roots, p)+ }+ add(b.skillsRoot)+ add(b.sessionRoot)+ if b.skillsRoot != "" {+ add(filepath.Dir(filepath.Clean(b.skillsRoot)))+ }+ if b.sessionRoot != "" {+ add(filepath.Dir(filepath.Clean(b.sessionRoot)))+ }+ return roots+}++// resolveExistingPrefix EvalSymlinks the longest existing prefix and rejoins+// the remainder. The result is what the kernel will see.+func resolveExistingPrefix(path string) (string, error) {+ if path == "" || !filepath.IsAbs(path) {+ return "", fmt.Errorf("localsandbox: %q is not absolute", path)+ }+ cur := filepath.Clean(path)+ remainder := ""+ for {+ resolved, err := filepath.EvalSymlinks(cur)+ if err == nil {+ if remainder == "" {+ return resolved, nil+ }+ return filepath.Clean(filepath.Join(resolved, remainder)), nil+ }+ if !os.IsNotExist(err) {+ return "", err+ }+ parent := filepath.Dir(cur)+ if parent == cur {+ return "", fmt.Errorf("localsandbox: %q has no existing ancestor", path)+ }+ if remainder == "" {+ remainder = filepath.Base(cur)+ } else {+ remainder = filepath.Join(filepath.Base(cur), remainder)+ }+ cur = parent+ }+}++// grantDirectory is the directory a card may offer. A directory target is+// itself. A file target is its parent, and that parent must already exist.+// Missing intermediate directories are not replaced by a higher ancestor+// such as ~/Documents.+func grantDirectory(p string) (string, bool) {+ info, err := os.Lstat(p)+ if err == nil && info.Mode()&os.ModeSymlink != 0 {+ if resolved, rerr := filepath.EvalSymlinks(p); rerr == nil {+ p = resolved+ info, err = os.Lstat(p)+ }+ }+ if err == nil && info.IsDir() {+ return p, true+ }+ parent := filepath.Dir(p)+ if parent == p {+ return "", false+ }+ info, err = os.Lstat(parent)+ if err == nil && info.Mode()&os.ModeSymlink != 0 {+ if resolved, rerr := filepath.EvalSymlinks(parent); rerr == nil {+ parent = resolved+ info, err = os.Lstat(parent)+ }+ }+ if err != nil || !info.IsDir() {+ return "", false+ }+ return parent, true+}diff --git a/internal/localsandbox/core/escalation_test.go b/internal/localsandbox/core/escalation_test.gonew file mode 100644index 000000000..d127c8941--- /dev/null+++ b/internal/localsandbox/core/escalation_test.go@@ -0,0 +1,333 @@+package core++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/stretchr/testify/require"+)++type proposeEnv struct {+ b *PolicyBuilder+ p Policy+ home string+ root string+ other string+}++func proposeFixture(t *testing.T) proposeEnv {+ t.Helper()+ base, err := filepath.EvalSymlinks(t.TempDir())+ require.NoError(t, err)+ home := filepath.Join(base, "home")+ root := filepath.Join(home, "proj")+ other := filepath.Join(base, "other")+ for _, dir := range []string{root, other, filepath.Join(home, ".ssh"), filepath.Join(home, ".nvm")} {+ require.NoError(t, os.MkdirAll(dir, 0o755))+ }+ b := NewPolicyBuilder(home, filepath.Join(home, "AppData"))+ p, err := b.Build(ModeAuto, Workspace{Kind: WorkspaceProject, Root: root})+ require.NoError(t, err)+ return proposeEnv{b: b, p: p, home: home, root: root, other: other}+}++func denialAt(path string) Denial {+ return Denial{Reason: DenialOperationNotPermitted, Path: path}+}++func TestProposeGrantOffersExistingDirOutsidePolicy(t *testing.T) {+ env := proposeFixture(t)+ g, ok := env.b.ProposeGrant(env.p, denialAt(filepath.Join(env.other, "a.txt")), env.root)+ require.True(t, ok)+ require.Equal(t, Grant{Path: env.other, Access: AccessWrite}, g)+}++func TestProposeGrantDoesNotWalkUpPastAMissingDirectory(t *testing.T) {+ env := proposeFixture(t)+ _, ok := env.b.ProposeGrant(env.p, denialAt(filepath.Join(env.other, "new", "deep", "f")), env.root)+ require.False(t, ok)+}++func TestProposeGrantRejectsTheApplicationTree(t *testing.T) {+ env := proposeFixture(t)+ app := filepath.Join(env.home, ".weknora")+ skills := filepath.Join(app, "skills", "pdf")+ otherSession := filepath.Join(app, "sessions", "2026", "10", "08", "session-other")+ desktop := filepath.Join(env.home, "Desktop")+ for _, dir := range []string{skills, otherSession, desktop} {+ require.NoError(t, os.MkdirAll(dir, 0o755))+ }+ env.b.WithSkillsRoot(filepath.Join(app, "skills")).WithSessionRoot(filepath.Join(app, "sessions"))++ for _, path := range []string{+ filepath.Join(app, "notes.txt"),+ filepath.Join(skills, "run.py"),+ filepath.Join(otherSession, "a.txt"),+ filepath.Join(app, "sessions", "2026", "a.txt"),+ } {+ _, ok := env.b.ProposeGrant(env.p, denialAt(path), env.root)+ require.False(t, ok, path)+ }+ for _, path := range []string{app, filepath.Join(app, "skills"), otherSession} {+ _, err := env.b.Relax(env.p, Grant{Path: path, Access: AccessWrite})+ require.Error(t, err, path)+ }++ g, ok := env.b.ProposeGrant(env.p, denialAt(filepath.Join(desktop, "a.txt")), env.root)+ require.True(t, ok)+ require.Equal(t, desktop, g.Path)+}++func TestProposeGrantResolvesRelativePathFromCwd(t *testing.T) {+ env := proposeFixture(t)+ g, ok := env.b.ProposeGrant(env.p, denialAt("a.txt"), env.other)+ require.True(t, ok)+ require.Equal(t, env.other, g.Path)+}++// Toolchains, shell and git config under a home dot entry run outside the+// sandbox the next time the user uses them, so none of them is offered.+func TestProposeGrantRejectsHomeDotDirectories(t *testing.T) {+ env := proposeFixture(t)+ dirs := []string{+ filepath.Join(env.home, ".nvm"),+ filepath.Join(env.home, ".local", "bin"),+ filepath.Join(env.home, ".cargo", "bin"),+ filepath.Join(env.home, ".config", "git"),+ filepath.Join(env.home, ".config", "fish"),+ }+ for _, dir := range dirs {+ require.NoError(t, os.MkdirAll(dir, 0o755))+ _, ok := env.b.ProposeGrant(env.p, denialAt(filepath.Join(dir, "x")), env.root)+ require.False(t, ok, dir)+ for _, access := range []Access{AccessWrite, AccessRead} {+ _, err := env.b.Relax(env.p, Grant{Path: dir, Access: access})+ require.ErrorIs(t, err, ErrWorkspaceTooBroad, dir)+ }+ }++ // A dot directory below an ordinary folder is the user's own data.+ project := filepath.Join(env.home, "Desktop", "site", ".vitepress")+ require.NoError(t, os.MkdirAll(project, 0o755))+ g, ok := env.b.ProposeGrant(env.p, denialAt(filepath.Join(project, "config.ts")), env.root)+ require.True(t, ok)+ require.Equal(t, project, g.Path)+}++// Allowed by the policy means the failure was not the sandbox.+func TestProposeGrantSkipsPathInsideWorkspace(t *testing.T) {+ env := proposeFixture(t)+ _, ok := env.b.ProposeGrant(env.p, denialAt(filepath.Join(env.root, "a.txt")), env.root)+ require.False(t, ok)+}++func TestProposeGrantSkipsCredentialDir(t *testing.T) {+ env := proposeFixture(t)+ _, ok := env.b.ProposeGrant(env.p, denialAt(filepath.Join(env.home, ".ssh", "id_rsa")), env.root)+ require.False(t, ok)+}++func TestProposeGrantSkipsHomeItself(t *testing.T) {+ env := proposeFixture(t)+ _, ok := env.b.ProposeGrant(env.p, denialAt(filepath.Join(env.home, "notes.txt")), env.root)+ require.False(t, ok)+}++func TestProposeGrantSkipsSystemDirs(t *testing.T) {+ env := proposeFixture(t)+ _, ok := env.b.ProposeGrant(env.p, denialAt("/etc/hosts"), env.root)+ require.False(t, ok)+}++func TestProposeGrantResolvesSymlinkToTheRealDirectory(t *testing.T) {+ env := proposeFixture(t)+ link := filepath.Join(env.root, "link")+ require.NoError(t, os.Symlink(env.other, link))++ g, ok := env.b.ProposeGrant(env.p, denialAt(filepath.Join(link, "a.txt")), env.root)+ require.True(t, ok)+ require.Equal(t, Grant{Path: env.other, Access: AccessWrite}, g)+}++func TestProposeGrantRejectsSymlinkToHome(t *testing.T) {+ env := proposeFixture(t)+ link := filepath.Join(env.root, "link")+ require.NoError(t, os.Symlink(env.home, link))++ _, ok := env.b.ProposeGrant(env.p, denialAt(filepath.Join(link, "x")), env.root)+ require.False(t, ok)+}++func TestRelaxResolvesSymlinkAndRejectsRetargetToHome(t *testing.T) {+ env := proposeFixture(t)+ link := filepath.Join(env.root, "link")+ require.NoError(t, os.Symlink(env.other, link))++ relaxed, err := env.b.Relax(env.p, Grant{Path: link, Access: AccessWrite})+ require.NoError(t, err)+ var roots []string+ for _, r := range relaxed.WritableRoots {+ roots = append(roots, r.Path)+ }+ require.Contains(t, roots, env.other)+ require.NotContains(t, roots, link)++ require.NoError(t, os.Remove(link))+ require.NoError(t, os.Symlink(env.home, link))+ _, err = env.b.Relax(env.p, Grant{Path: link, Access: AccessWrite})+ require.Error(t, err)+}++func writableRootAt(t *testing.T, p Policy, path string) WritableRoot {+ t.Helper()+ for _, r := range p.WritableRoots {+ if r.Path == path {+ return r+ }+ }+ t.Fatalf("no writable root at %s", path)+ return WritableRoot{}+}++// A hook written into a granted repository runs with the user's own rights+// the next time they use git there, outside the sandbox.+func TestRelaxWriteGrantKeepsGitReadOnly(t *testing.T) {+ env := proposeFixture(t)+ gitDir := filepath.Join(env.other, ".git")+ require.NoError(t, os.MkdirAll(filepath.Join(gitDir, "hooks"), 0o755))++ relaxed, err := env.b.Relax(env.p, Grant{Path: env.other, Access: AccessWrite})+ require.NoError(t, err)+ require.Equal(t, []string{gitDir}, writableRootAt(t, relaxed, env.other).ReadOnlySubpaths)++ guard := NewPathGuard(relaxed)+ _, err = guard.CheckWrite(filepath.Join(gitDir, "hooks", "pre-commit"))+ require.ErrorIs(t, err, ErrPathDenied)+ _, err = guard.CheckWrite(filepath.Join(env.other, "a.txt"))+ require.NoError(t, err)+}++// Without this, git init in the granted directory creates a repository whose+// hooks the sandbox may write.+func TestRelaxWriteGrantProtectsAMissingGitDir(t *testing.T) {+ env := proposeFixture(t)++ relaxed, err := env.b.Relax(env.p, Grant{Path: env.other, Access: AccessWrite})+ require.NoError(t, err)+ require.Equal(t,+ []string{filepath.Join(env.other, ".git")},+ writableRootAt(t, relaxed, env.other).ReadOnlySubpaths)+}++func TestRelaxWriteGrantProtectsTheGitdirAGitFileNames(t *testing.T) {+ env := proposeFixture(t)+ gitdir := filepath.Join(env.other, ".repo", "worktrees", "w1")+ require.NoError(t, os.MkdirAll(gitdir, 0o755))+ require.NoError(t, os.WriteFile(filepath.Join(env.other, ".git"),+ []byte("gitdir: .repo/worktrees/w1\n"), 0o644))++ relaxed, err := env.b.Relax(env.p, Grant{Path: env.other, Access: AccessWrite})+ require.NoError(t, err)+ require.ElementsMatch(t,+ []string{filepath.Join(env.other, ".git"), gitdir},+ writableRootAt(t, relaxed, env.other).ReadOnlySubpaths)++ _, err = NewPathGuard(relaxed).CheckWrite(filepath.Join(gitdir, "hooks", "pre-commit"))+ require.ErrorIs(t, err, ErrPathDenied)+}++func protectedProjectFixture(t *testing.T) proposeEnv {+ t.Helper()+ env := proposeFixture(t)+ env.root = filepath.Join(env.home, "Documents", "proj")+ require.NoError(t, os.MkdirAll(filepath.Join(env.root, ".git", "hooks"), 0o755))+ p, err := env.b.Build(ModeAuto, Workspace{Kind: WorkspaceProject, Root: env.root, ProtectGit: true})+ require.NoError(t, err)+ env.p = p+ return env+}++// A card must never offer a directory inside a repository's metadata: the+// hooks there run outside the sandbox the next time the user runs git.+func TestProposeGrantRefusesTheWorkspaceGitDir(t *testing.T) {+ env := protectedProjectFixture(t)+ hook := filepath.Join(env.root, ".git", "hooks", "pre-commit")++ _, ok := env.b.ProposeGrant(env.p, denialAt(hook), env.root)+ require.False(t, ok)+ _, err := env.b.Relax(env.p, Grant{Path: filepath.Join(env.root, ".git", "hooks"), Access: AccessWrite})+ require.Error(t, err)+}++func TestRelaxRefusesAGitDirOutsideTheWorkspace(t *testing.T) {+ env := proposeFixture(t)+ for _, dir := range []string{+ filepath.Join(env.other, ".git"),+ filepath.Join(env.other, ".git", "hooks"),+ filepath.Join(env.other, "sub", ".GIT", "hooks"),+ } {+ require.NoError(t, os.MkdirAll(dir, 0o755))+ _, err := env.b.Relax(env.p, Grant{Path: dir, Access: AccessWrite})+ require.Error(t, err, dir)+ _, ok := env.b.ProposeGrant(env.p, denialAt(filepath.Join(dir, "x")), env.root)+ require.False(t, ok, dir)+ }+}++// Granting the folder that holds the project must not reopen the project's+// own .git, whichever writable root the guard looks at first.+func TestWriteGrantCoveringTheWorkspaceKeepsItsGitReadOnly(t *testing.T) {+ env := protectedProjectFixture(t)+ parent := filepath.Dir(env.root)++ relaxed, err := env.b.Relax(env.p, Grant{Path: parent, Access: AccessWrite})+ require.NoError(t, err)+ reversed := relaxed+ reversed.WritableRoots = []WritableRoot{relaxed.WritableRoots[1], relaxed.WritableRoots[0]}++ hook := filepath.Join(env.root, ".git", "hooks", "pre-commit")+ for _, p := range []Policy{relaxed, reversed} {+ guard := NewPathGuard(p)+ _, err = guard.CheckWrite(hook)+ require.ErrorIs(t, err, ErrPathDenied)+ require.ErrorIs(t, guard.WriteFile(hook, []byte("#!/bin/sh\n"), 0o755), ErrPathDenied)+ _, err = guard.CheckWrite(filepath.Join(parent, "notes.txt"))+ require.NoError(t, err)+ }+}++// A granted folder may hold other repositories. None of their .git+// directories become writable, including ones created after the grant.+func TestWriteGrantKeepsNestedGitDirsReadOnly(t *testing.T) {+ env := proposeFixture(t)+ nested := filepath.Join(env.other, "code", "app")+ require.NoError(t, os.MkdirAll(filepath.Join(nested, ".git", "hooks"), 0o755))++ relaxed, err := env.b.Relax(env.p, Grant{Path: env.other, Access: AccessWrite})+ require.NoError(t, err)+ require.True(t, writableRootAt(t, relaxed, env.other).ProtectGitDirs)++ guard := NewPathGuard(relaxed)+ for _, path := range []string{+ filepath.Join(nested, ".git", "hooks", "pre-commit"),+ filepath.Join(nested, ".git"),+ filepath.Join(env.other, "later", ".git", "config"),+ filepath.Join(env.other, "later", ".GIT", "config"),+ } {+ _, err = guard.CheckWrite(path)+ require.ErrorIs(t, err, ErrPathDenied, path)+ }+ _, err = guard.CheckWrite(filepath.Join(nested, "main.go"))+ require.NoError(t, err)+ _, err = guard.CheckWrite(filepath.Join(nested, ".gitignore"))+ require.NoError(t, err)+}++func TestProposeGrantNeedsADeniedPath(t *testing.T) {+ env := proposeFixture(t)+ _, ok := env.b.ProposeGrant(env.p, Denial{Reason: DenialOperationNotPermitted}, env.root)+ require.False(t, ok)+ _, ok = env.b.ProposeGrant(env.p, Denial{Path: filepath.Join(env.other, "a")}, env.root)+ require.False(t, ok)+}diff --git a/internal/localsandbox/core/pathguard.go b/internal/localsandbox/core/pathguard.goindex 497eee450..50a46b361 100644--- a/internal/localsandbox/core/pathguard.go+++ b/internal/localsandbox/core/pathguard.go@@ -5,6 +5,7 @@ import ("fmt""os""path/filepath"+ "strings")// ErrPathDenied is returned for every rejected path. Callers surface it to@@ -52,18 +53,38 @@ func (g *PathGuard) CheckWrite(path string) (string, error) {if g.denied(resolved) {return "", fmt.Errorf("%w: %q", ErrPathDenied, path)}+ if g.readOnly(resolved) {+ return "", fmt.Errorf("%w: %q is read-only", ErrPathDenied, path)+ }for _, root := range g.writable {- if !PathUnder(resolved, root.Path) {- continue+ if PathUnder(resolved, root.Path) {+ return resolved, nil}+ }+ return "", fmt.Errorf("%w: %q", ErrPathDenied, path)+}++// readOnly checks every root, not only the one that admits path: a root that+// covers another must not reopen that root's carve-outs. Seatbelt compiles+// the same rules as final denies.+func (g *PathGuard) readOnly(path string) bool {+ for _, root := range g.writable {for _, ro := range root.ReadOnlySubpaths {- if PathUnder(resolved, ro) {- return "", fmt.Errorf("%w: %q is read-only", ErrPathDenied, path)+ if PathUnder(path, ro) {+ return true+ }+ }+ if root.ProtectGitDirs && PathUnder(path, root.Path) {+ // Count elements instead of slicing bytes: PathUnder folds case,+ // and folding can change a string's length.+ parts := strings.Split(filepath.ToSlash(path), "/")+ depth := len(strings.Split(filepath.ToSlash(root.Path), "/"))+ if hasGitComponent(strings.Join(parts[depth:], "/")) {+ return true}}- return resolved, nil}- return "", fmt.Errorf("%w: %q", ErrPathDenied, path)+ return false}// CheckRead returns the resolved absolute path when reading is permitted.diff --git a/internal/localsandbox/core/pathguard_file.go b/internal/localsandbox/core/pathguard_file.goindex 665c54218..8696eeb3b 100644--- a/internal/localsandbox/core/pathguard_file.go+++ b/internal/localsandbox/core/pathguard_file.go@@ -48,15 +48,13 @@ func (g *PathGuard) allowWrite(path string) (root, rel string, err error) {if g.denied(path) {return "", "", fmt.Errorf("%w: %q", ErrPathDenied, path)}+ if g.readOnly(path) {+ return "", "", fmt.Errorf("%w: %q is read-only", ErrPathDenied, path)+ }for _, wr := range g.writable {if !PathUnder(path, wr.Path) {continue}- for _, ro := range wr.ReadOnlySubpaths {- if PathUnder(path, ro) {- return "", "", fmt.Errorf("%w: %q is read-only", ErrPathDenied, path)- }- }rel, err = relativeInside(wr.Path, path)if err != nil {continuediff --git a/internal/localsandbox/core/policy.go b/internal/localsandbox/core/policy.goindex d539831f6..49684a85d 100644--- a/internal/localsandbox/core/policy.go+++ b/internal/localsandbox/core/policy.go@@ -34,8 +34,12 @@ type WritableRoot struct {// Path is an absolute, cleaned host path.Path string// ReadOnlySubpaths sit inside Path but must not be written, typically- // Path/.git.+ // Path/.git. They stay read-only even where another root covers them.ReadOnlySubpaths []string+ // ProtectGitDirs keeps every directory named .git anywhere under Path+ // read-only, including ones created later. A git hook or config written+ // there runs with the user's own rights outside the sandbox.+ ProtectGitDirs bool}// Policy is the platform-neutral permission declaration. It is a value@@ -242,7 +246,9 @@ func (p Policy) canonical() Policy {for i, root := range p.WritableRoots {subs := append([]string(nil), root.ReadOnlySubpaths...)sort.Strings(subs)- out.WritableRoots[i] = WritableRoot{Path: root.Path, ReadOnlySubpaths: subs}+ out.WritableRoots[i] = WritableRoot{+ Path: root.Path, ReadOnlySubpaths: subs, ProtectGitDirs: root.ProtectGitDirs,+ }}sort.Slice(out.WritableRoots, func(i, j int) bool {return out.WritableRoots[i].Path < out.WritableRoots[j].Pathdiff --git a/internal/localsandbox/core/policy_builder.go b/internal/localsandbox/core/policy_builder.goindex cfe8b6b26..3c4aa9693 100644--- a/internal/localsandbox/core/policy_builder.go+++ b/internal/localsandbox/core/policy_builder.go@@ -124,10 +124,11 @@ var ErrInstallDirOutsideSkillsRoot = errors.New("localsandbox: install directory// PolicyBuilder derives a Policy from an approval mode and a workspace.type PolicyBuilder struct {- homeDir string- appDataDir string- skillsRoot string- jobsRoot string+ homeDir string+ appDataDir string+ skillsRoot string+ jobsRoot string+ sessionRoot string}// NewPolicyBuilder returns a builder scoped to the user's home and app-data dirs.@@ -139,6 +140,9 @@ func NewPolicyBuilder(homeDir, appDataDir string) *PolicyBuilder {}}+// HomeDir is the user's home the builder protects.+func (b *PolicyBuilder) HomeDir() string { return b.homeDir }+// Build derives a policy from the mode and the workspace. Pure: no IO, so it// is directly unit-testable.func (b *PolicyBuilder) Build(mode ApprovalMode, ws Workspace) (Policy, error) {@@ -167,6 +171,9 @@ func (b *PolicyBuilder) Build(mode ApprovalMode, ws Workspace) (Policy, error) {// Losing .git to a hallucinated rm -rf is unrecoverable, and it is// the least appropriate thing for an LLM to decide unilaterally.root.ReadOnlySubpaths = []string{filepath.Join(ws.Root, ".git")}+ // Submodules and nested repositories carry hooks that run+ // outside the sandbox the next time the user uses git there.+ root.ProtectGitDirs = true}p.WritableRoots = []WritableRoot{root}case ModeAsk:@@ -226,6 +233,16 @@ func (b *PolicyBuilder) WithSkillsRoot(root string) *PolicyBuilder {return b}+// WithSessionRoot records where session workspaces live. Grants cannot cover+// that tree or the skills tree: one session must not rewrite another+// session's files or the skills every session reads.+func (b *PolicyBuilder) WithSessionRoot(root string) *PolicyBuilder {+ if root = strings.TrimSpace(root); root != "" {+ b.sessionRoot = filepath.Clean(root)+ }+ return b+}+// BuildInstall is the policy one skill install runs under: only dir is// writable, the network is open for package downloads, and deny-read is the// same set auto mode enforces.@@ -282,11 +299,17 @@ func (b *PolicyBuilder) rejectBroadWorkspace(root string) error {if root == "" || !filepath.IsAbs(root) {return fmt.Errorf("%w: %q", ErrRelativePath, root)}+ if resolved, err := resolveExistingPrefix(root); err == nil {+ root = resolved+ }if isFilesystemRoot(root) {return fmt.Errorf("%w: %q", ErrFilesystemRoot, root)}if b.homeDir != "" && b.homeDir != string(filepath.Separator) {home := filepath.Clean(b.homeDir)+ if resolved, err := resolveExistingPrefix(home); err == nil {+ home = resolved+ }if PathUnder(home, root) {return fmt.Errorf("%w: %q covers the home directory", ErrWorkspaceTooBroad, root)}@@ -330,36 +353,101 @@ func (b *PolicyBuilder) denyRead() []string {return deny}-// Grant is one approved escalation.+// Access is what a Grant opens on its path.+type Access string++const (+ // AccessRead adds the path as a readable root.+ AccessRead Access = "read"+ // AccessWrite adds the path as a writable root, which is also readable.+ AccessWrite Access = "write"+)++// Grant is one approved escalation: a directory added to the policy.type Grant struct {- WritePath string- AllowNetwork bool+ Path string+ Access Access}// Relax derives a wider policy after the user approved an escalation. It never// removes a deny-read entry: those are the only mechanism enforcing them.+//+// The grant path is resolved on every call. A symlink approved earlier can be+// retargeted; the next command must see the new target and refuse it when+// that target is no longer grantable.func (b *PolicyBuilder) Relax(base Policy, g Grant) (Policy, error) {+ path, err := resolveExistingPrefix(g.Path)+ if err != nil {+ return Policy{}, err+ }+ if info, statErr := os.Lstat(path); statErr == nil && !info.IsDir() {+ path = filepath.Dir(path)+ }+ if err := b.rejectGrantPath(base, path); err != nil {+ return Policy{}, err+ }+out := baseout.WritableRoots = append([]WritableRoot(nil), base.WritableRoots...)-- if g.WritePath != "" {- path := filepath.Clean(g.WritePath)- if err := b.rejectBroadWorkspace(path); err != nil {- return Policy{}, err- }- for _, deny := range base.DenyRead {- if PathUnder(path, deny) {- return Policy{}, fmt.Errorf(- "localsandbox: %q is read-denied and cannot be granted", path)- }- }- out.WritableRoots = append(out.WritableRoots, WritableRoot{Path: path})- }- if g.AllowNetwork {- out.Network = NetworkUnrestricted+ out.ReadableRoots = append([]string(nil), base.ReadableRoots...)+ switch g.Access {+ case AccessWrite:+ out.WritableRoots = append(out.WritableRoots, WritableRoot{+ Path: path,+ ReadOnlySubpaths: gitMetadataPaths(path),+ ProtectGitDirs: true,+ })+ case AccessRead:+ out.ReadableRoots = append(out.ReadableRoots, path)+ default:+ return Policy{}, fmt.Errorf("localsandbox: unknown grant access %q", g.Access)}if err := out.Validate(); err != nil {return Policy{}, err}return out, nil}++// gitMetadataPaths is what a write grant on root must keep read-only: hooks+// and config there run with the user's own rights outside the sandbox. A+// missing .git is protected too, so git init cannot create a writable one.+// When .git is a file (worktree, submodule), the directory it names is+// protected as well if it lies inside root; outside root this grant does not+// make it writable.+func gitMetadataPaths(root string) []string {+ dotGit := filepath.Join(root, ".git")+ paths := []string{dotGit}+ info, err := os.Lstat(dotGit)+ if err != nil || !info.Mode().IsRegular() {+ return paths+ }+ data, err := os.ReadFile(dotGit)+ if err != nil {+ return paths+ }+ line, _, _ := strings.Cut(string(data), "\n")+ gitdir, ok := strings.CutPrefix(strings.TrimSpace(line), "gitdir:")+ if !ok {+ return paths+ }+ gitdir = strings.TrimSpace(gitdir)+ if !filepath.IsAbs(gitdir) {+ gitdir = filepath.Join(root, gitdir)+ }+ resolved, err := resolveExistingPrefix(gitdir)+ if err != nil || !PathUnder(resolved, root) || samePath(resolved, root) {+ return paths+ }+ return append(paths, resolved)+}++// hasGitComponent reports whether any element of path is named .git. APFS+// ignores case, so .GIT is the same directory to git.+func hasGitComponent(path string) bool {+ for _, part := range strings.Split(filepath.ToSlash(path), "/") {+ if strings.EqualFold(part, ".git") {+ return true+ }+ }+ return false+}diff --git a/internal/localsandbox/core/policy_builder_test.go b/internal/localsandbox/core/policy_builder_test.goindex 1b45d89ec..194296a09 100644--- a/internal/localsandbox/core/policy_builder_test.go+++ b/internal/localsandbox/core/policy_builder_test.go@@ -1,6 +1,7 @@package coreimport (+ "os""path/filepath""testing"@@ -49,6 +50,32 @@ func TestBuildProtectsGitWhenWorkspaceAsksForIt(t *testing.T) {t.Fatal("workspace root missing from policy")}+// Submodules and nested repositories carry hooks too, and a .GIT created+// before git init is the same directory to git on APFS.+func TestBuildProtectsEveryGitDirInAProject(t *testing.T) {+ base, err := filepath.EvalSymlinks(t.TempDir())+ require.NoError(t, err)+ home := filepath.Join(base, "home")+ ws := Workspace{Kind: WorkspaceProject, Root: filepath.Join(home, "proj"), ProtectGit: true}+ require.NoError(t, os.MkdirAll(ws.Root, 0o755))+ b := NewPolicyBuilder(home, filepath.Join(home, "AppData"))++ p, err := b.Build(ModeAuto, ws)+ require.NoError(t, err)+ require.True(t, p.WritableRoots[0].ProtectGitDirs)++ guard := NewPathGuard(p)+ for _, path := range []string{+ filepath.Join(ws.Root, "vendor", "lib", ".git", "hooks", "pre-commit"),+ filepath.Join(ws.Root, ".GIT", "config"),+ } {+ _, err = guard.CheckWrite(path)+ require.ErrorIs(t, err, ErrPathDenied, path)+ }+ _, err = guard.CheckWrite(filepath.Join(ws.Root, "vendor", "lib", "main.go"))+ require.NoError(t, err)+}+// A session workspace's .git belongs to the agent, so it is not protected.func TestBuildDoesNotProtectGitForSessionWorkspace(t *testing.T) {b, ws := builderFixture(t)@@ -59,6 +86,7 @@ func TestBuildDoesNotProtectGitForSessionWorkspace(t *testing.T) {require.NoError(t, err)for _, r := range p.WritableRoots {require.Empty(t, r.ReadOnlySubpaths)+ require.False(t, r.ProtectGitDirs)}}@@ -188,32 +216,69 @@ func TestBuildIncludesPlatformRuntimeReadRoots(t *testing.T) {require.Contains(t, p.ReadableRoots, "/usr/lib")}-func TestRelaxAddsWritePathAndNetwork(t *testing.T) {+func TestRelaxAddsWritableRoot(t *testing.T) {b, ws := builderFixture(t)base, err := b.Build(ModeAuto, ws)require.NoError(t, err)extra := filepath.Join(b.homeDir, "Other Dir")- relaxed, err := b.Relax(base, Grant{WritePath: extra, AllowNetwork: true})+ require.NoError(t, os.MkdirAll(extra, 0o755))+ relaxed, err := b.Relax(base, Grant{Path: extra, Access: AccessWrite})require.NoError(t, err)+ resolved, err := filepath.EvalSymlinks(extra)+ require.NoError(t, err)var roots []stringfor _, r := range relaxed.WritableRoots {roots = append(roots, r.Path)}- require.Contains(t, roots, extra)- require.Equal(t, NetworkUnrestricted, relaxed.Network)+ require.Contains(t, roots, resolved)+ require.NotContains(t, relaxed.ReadableRoots, extra)+ require.Len(t, base.WritableRoots, 1, "Relax must not mutate the base policy")require.NotEqual(t, base.Fingerprint(), relaxed.Fingerprint())}+func TestRelaxAddsReadableRootOnly(t *testing.T) {+ b, ws := builderFixture(t)+ base, err := b.Build(ModeAuto, ws)+ require.NoError(t, err)++ extra := filepath.Join(b.homeDir, "Other Dir")+ require.NoError(t, os.MkdirAll(extra, 0o755))+ relaxed, err := b.Relax(base, Grant{Path: extra, Access: AccessRead})+ require.NoError(t, err)++ resolved, err := filepath.EvalSymlinks(extra)+ require.NoError(t, err)+ require.Contains(t, relaxed.ReadableRoots, resolved)+ require.NotContains(t, base.ReadableRoots, extra, "Relax must not mutate the base policy")+ require.Len(t, relaxed.WritableRoots, len(base.WritableRoots))+}++func TestRelaxRefusesUnknownAccess(t *testing.T) {+ b, ws := builderFixture(t)+ base, err := b.Build(ModeAuto, ws)+ require.NoError(t, err)++ _, err = b.Relax(base, Grant{Path: filepath.Join(b.homeDir, "Other Dir")})+ require.Error(t, err)+}+// Relaxation must never be able to unlock a denied credential directory.func TestRelaxRefusesToGrantDeniedPath(t *testing.T) {b, ws := builderFixture(t)base, err := b.Build(ModeAuto, ws)require.NoError(t, err)- _, err = b.Relax(base, Grant{WritePath: filepath.Join(b.homeDir, ".ssh")})- require.Error(t, err)+ for _, access := range []Access{AccessRead, AccessWrite} {+ _, err = b.Relax(base, Grant{Path: filepath.Join(b.homeDir, ".ssh"), Access: access})+ require.Error(t, err, access)+ }+}++func TestPolicyBuilderReportsHomeDir(t *testing.T) {+ b, _ := builderFixture(t)+ require.Equal(t, b.homeDir, b.HomeDir())}func TestBuildRefusesHomeAsWorkspace(t *testing.T) {@@ -310,7 +375,7 @@ func TestRelaxRefusesHomeWriteGrant(t *testing.T) {base, err := b.Build(ModeAuto, ws)require.NoError(t, err)- _, err = b.Relax(base, Grant{WritePath: b.homeDir})+ _, err = b.Relax(base, Grant{Path: b.homeDir, Access: AccessWrite})require.ErrorIs(t, err, ErrWorkspaceTooBroad)}@@ -319,7 +384,10 @@ func TestRelaxRefusesHomeLibraryDescendant(t *testing.T) {base, err := b.Build(ModeAuto, ws)require.NoError(t, err)- _, err = b.Relax(base, Grant{WritePath: filepath.Join(b.homeDir, "Library", "Application Support")})+ _, err = b.Relax(base, Grant{+ Path: filepath.Join(b.homeDir, "Library", "Application Support"),+ Access: AccessWrite,+ })require.ErrorIs(t, err, ErrWorkspaceTooBroad)}@@ -338,7 +406,7 @@ func TestRelaxRefusesToGrantAppData(t *testing.T) {base, err := b.Build(ModeAuto, ws)require.NoError(t, err)- _, err = b.Relax(base, Grant{WritePath: b.appDataDir})+ _, err = b.Relax(base, Grant{Path: b.appDataDir, Access: AccessRead})require.Error(t, err)}diff --git a/internal/localsandbox/core/workspace.go b/internal/localsandbox/core/workspace.goindex 6997b430d..74725bcc6 100644--- a/internal/localsandbox/core/workspace.go+++ b/internal/localsandbox/core/workspace.go@@ -9,7 +9,6 @@ import ("os""path/filepath""strings"- "time""github.com/Tencent/WeKnora/internal/logger")@@ -56,7 +55,8 @@ var ErrProjectDirRevoked = errors.New("localsandbox: session project directory i// DirLayout names the roots the resolver allocates under.type DirLayout struct {// SessionRoot is where session workspaces are created, by default- // ~/Documents/WeKnoraLite. It is user-visible on purpose.+ // ~/.weknora/sessions. Each one is <root>/session-<id>, so the path+ // follows from the session ID alone.SessionRoot string}@@ -68,13 +68,12 @@ type WorkspaceResolver interface {type workspaceResolver struct {layout DirLayoutprojects ProjectLookup- now func() time.Time}// NewWorkspaceResolver returns a resolver that prefers a bound project// directory and otherwise allocates under layout.SessionRoot.func NewWorkspaceResolver(layout DirLayout, projects ProjectLookup) WorkspaceResolver {- return &workspaceResolver{layout: layout, projects: projects, now: time.Now}+ return &workspaceResolver{layout: layout, projects: projects}}func (r *workspaceResolver) Resolve(ctx context.Context, sessionID string) (Workspace, error) {@@ -106,7 +105,6 @@ func (r *workspaceResolver) Resolve(ctx context.Context, sessionID string) (Work}}- day := r.now().Format("2006-01-02")seg := sanitizeSegment(sessionID)if existing, ok := r.existingSessionDir(seg); ok {logger.Infof(ctx, "[LocalSandbox] workspace session=%s kind=session root=%s", sessionID, existing)@@ -116,12 +114,18 @@ func (r *workspaceResolver) Resolve(ctx context.Context, sessionID string) (WorkProtectGit: false,}, nil}- root := filepath.Join(r.layout.SessionRoot, day, "session-"+seg)+ root := filepath.Join(r.layout.SessionRoot, "session-"+seg)if err := os.MkdirAll(root, 0o700); err != nil {logger.Errorf(ctx, "[LocalSandbox] create session workspace session=%s root=%s: %v",sessionID, root, err)return Workspace{}, fmt.Errorf("localsandbox: create session workspace: %w", err)}+ // MkdirAll accepts a symlink to a directory as already present.+ if info, err := os.Lstat(root); err != nil || info.Mode()&os.ModeSymlink != 0 {+ logger.Errorf(ctx, "[LocalSandbox] session workspace is not a real directory session=%s root=%s",+ sessionID, root)+ return Workspace{}, fmt.Errorf("localsandbox: session workspace %q is not a real directory", root)+ }if err := os.Chmod(root, 0o700); err != nil {return Workspace{}, fmt.Errorf("localsandbox: restrict session workspace: %w", err)}@@ -164,15 +168,14 @@ func (r *workspaceResolver) existingSessionDir(seg string) (string, bool) {if r.layout.SessionRoot == "" || seg == "" {return "", false}- matches, err := filepath.Glob(filepath.Join(r.layout.SessionRoot, "*", "session-"+seg))- if err != nil || len(matches) == 0 {- return "", false- }- info, err := os.Lstat(matches[0])+ // Only a real directory counts: a symlink planted in the session tree+ // must not redirect a workspace elsewhere.+ path := filepath.Join(r.layout.SessionRoot, "session-"+seg)+ info, err := os.Lstat(path)if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {return "", false}- resolved, err := filepath.EvalSymlinks(matches[0])+ resolved, err := filepath.EvalSymlinks(path)if err != nil {return "", false}diff --git a/internal/localsandbox/core/workspace_test.go b/internal/localsandbox/core/workspace_test.goindex 3b8a83bb1..7da93530a 100644--- a/internal/localsandbox/core/workspace_test.go+++ b/internal/localsandbox/core/workspace_test.go@@ -6,7 +6,6 @@ import ("path/filepath""strings""testing"- "time""github.com/stretchr/testify/require")@@ -79,13 +78,19 @@ func TestResolveProjectWorkspaceIsSharedAcrossSessions(t *testing.T) {require.Equal(t, a.Root, b.Root)}-func TestResolveSessionWorkspaceCreatesDatedDirectory(t *testing.T) {- ws, err := workspaceFixture(t, "").Resolve(context.Background(), "session-abcdef123456")+func TestResolveSessionWorkspaceSitsDirectlyUnderSessionRoot(t *testing.T) {+ base := t.TempDir()+ sessionRoot := filepath.Join(base, "Documents", "WeKnora")+ r := NewWorkspaceResolver(DirLayout{SessionRoot: sessionRoot}, fakeProjects{})+ ws, err := r.Resolve(context.Background(), "session-abcdef123456")require.NoError(t, err)require.Equal(t, WorkspaceSession, ws.Kind)require.DirExists(t, ws.Root)- require.Contains(t, ws.Root, "session-")+ resolvedRoot, err := filepath.EvalSymlinks(sessionRoot)+ require.NoError(t, err)+ require.Equal(t, resolvedRoot, filepath.Dir(ws.Root))+ require.Equal(t, "session-"+sanitizeSegment("session-abcdef123456"), filepath.Base(ws.Root))require.False(t, ws.ProtectGit)require.NoDirExists(t, filepath.Join(ws.Root, "input"))require.NoDirExists(t, filepath.Join(ws.Root, "output"))@@ -135,23 +140,29 @@ func TestResolveFailsClosedWhenBoundProjectIsRevoked(t *testing.T) {}}-func TestResolveSessionWorkspaceKeepsPathAfterMidnight(t *testing.T) {- base := t.TempDir()- r := NewWorkspaceResolver(DirLayout{- SessionRoot: filepath.Join(base, "Documents", "WeKnora"),- }, fakeProjects{}).(*workspaceResolver)-- day1 := time.Date(2026, 9, 20, 23, 0, 0, 0, time.UTC)- r.now = func() time.Time { return day1 }+func TestResolveSessionWorkspaceIsStable(t *testing.T) {+ r := workspaceFixture(t, "")first, err := r.Resolve(context.Background(), "sess-keep")require.NoError(t, err)-- r.now = func() time.Time { return day1.Add(2 * time.Hour) }second, err := r.Resolve(context.Background(), "sess-keep")require.NoError(t, err)require.Equal(t, first.Root, second.Root)}+func TestResolveSessionWorkspaceIgnoresPlantedSymlink(t *testing.T) {+ base := t.TempDir()+ sessionRoot := filepath.Join(base, "sessions")+ outside := filepath.Join(base, "outside")+ require.NoError(t, osMkdirAll(sessionRoot))+ require.NoError(t, osMkdirAll(outside))+ link := filepath.Join(sessionRoot, "session-"+sanitizeSegment("sess-link"))+ require.NoError(t, os.Symlink(outside, link))++ r := NewWorkspaceResolver(DirLayout{SessionRoot: sessionRoot}, fakeProjects{})+ _, err := r.Resolve(context.Background(), "sess-link")+ require.Error(t, err, "a symlink in place of the workspace must not be followed")+}+func TestResolveSessionWorkspaceUsesFullSessionID(t *testing.T) {r := workspaceFixture(t, "")a, err := r.Resolve(context.Background(), "session-abcdef123456")diff --git a/internal/localsandbox/seatbelt/backend.go b/internal/localsandbox/seatbelt/backend.goindex 157f94174..071eb4237 100644--- a/internal/localsandbox/seatbelt/backend.go+++ b/internal/localsandbox/seatbelt/backend.go@@ -158,7 +158,9 @@ func resolvePolicyPaths(p core.Policy) (core.Policy, error) {return core.Policy{}, err}}- out.WritableRoots[i] = core.WritableRoot{Path: path, ReadOnlySubpaths: subs}+ out.WritableRoots[i] = core.WritableRoot{+ Path: path, ReadOnlySubpaths: subs, ProtectGitDirs: root.ProtectGitDirs,+ }}out.ReadableRoots = make([]string, len(p.ReadableRoots))for i, root := range p.ReadableRoots {diff --git a/internal/localsandbox/seatbelt/backend_test.go b/internal/localsandbox/seatbelt/backend_test.goindex b5a86df94..c791850a0 100644--- a/internal/localsandbox/seatbelt/backend_test.go+++ b/internal/localsandbox/seatbelt/backend_test.go@@ -120,6 +120,44 @@ func TestSeatbeltDeniesRecreatingProtectedDirectory(t *testing.T) {require.NotEqual(t, 0, status.Code, out)}+// A second writable root that covers the workspace must not reopen its .git.+func TestSeatbeltCoveringRootKeepsGitReadOnly(t *testing.T) {+ backend, p, base := darwinFixture(t)+ p.WritableRoots = append(p.WritableRoots, core.WritableRoot{Path: base})++ status, out := runSandboxed(t, backend, p, `echo x > ./.git/config`)+ require.NotEqual(t, 0, status.Code, out)+ require.NoFileExists(t, filepath.Join(p.Cwd, ".git", "config"))++ status, out = runSandboxed(t, backend, p, `echo x > ../beside.txt`)+ require.Equal(t, 0, status.Code, out)+}++func TestSeatbeltProtectGitDirsDeniesEveryGitDirUnderTheRoot(t *testing.T) {+ backend, p, base := darwinFixture(t)+ other := filepath.Join(base, "Other Project")+ require.NoError(t, os.MkdirAll(filepath.Join(other, "app", ".git", "hooks"), 0o755))+ p.WritableRoots = append(p.WritableRoots, core.WritableRoot{Path: other, ProtectGitDirs: true})++ for _, script := range []string{+ `echo x > "` + filepath.Join(other, "app", ".git", "hooks", "pre-commit") + `"`,+ `rm -rf "` + filepath.Join(other, "app", ".git") + `"`,+ `mv "` + filepath.Join(other, "app", ".git") + `" "` + filepath.Join(other, "app", "moved") + `"`,+ `mkdir -p "` + filepath.Join(other, "new", ".git", "hooks") + `"`,+ `mkdir -p "` + filepath.Join(other, "upper", ".GIT") + `"`,+ } {+ status, out := runSandboxed(t, backend, p, script)+ require.NotEqual(t, 0, status.Code, script+"\n"+out)+ }+ require.DirExists(t, filepath.Join(other, "app", ".git", "hooks"))+ require.NoDirExists(t, filepath.Join(other, "new", ".git"))++ app := filepath.Join(other, "app")+ status, out := runSandboxed(t, backend, p,+ `echo x > "`+filepath.Join(app, "main.go")+`" && echo x > "`+filepath.Join(app, ".gitignore")+`"`)+ require.Equal(t, 0, status.Code, out)+}+func TestSeatbeltDeniesSymlinkEscapeToSecrets(t *testing.T) {backend, p, base := darwinFixture(t)status, out := runSandboxed(t, backend, p,@@ -161,6 +199,39 @@ func TestSeatbeltAllowsReadingWorkspaceInsidePrivateRoot(t *testing.T) {require.Contains(t, out, "body")}+func TestSeatbeltProjectFromBuilderKeepsEveryGitDirReadOnly(t *testing.T) {+ backend, err := New()+ require.NoError(t, err)+ require.NoError(t, backend.Available())++ home, err := filepath.EvalSymlinks(t.TempDir())+ require.NoError(t, err)+ project := filepath.Join(home, "Documents", "proj")+ submodule := filepath.Join(project, "vendor", "lib")+ require.NoError(t, os.MkdirAll(filepath.Join(submodule, ".git", "hooks"), 0o755))++ builder := core.NewPolicyBuilder(home, filepath.Join(home, "Library", "App"))+ p, err := builder.Build(core.ModeAuto, core.Workspace{+ Kind: core.WorkspaceProject, Root: project, ProtectGit: true,+ })+ require.NoError(t, err)++ for _, script := range []string{+ `mkdir ./.GIT`,+ `mkdir ./.git`,+ `echo x > ./vendor/lib/.git/hooks/pre-commit`,+ `rm -rf ./vendor/lib/.git`,+ } {+ status, out := runSandboxed(t, backend, p, script)+ require.NotEqual(t, 0, status.Code, script+"\n"+out)+ }+ require.NoDirExists(t, filepath.Join(project, ".GIT"))+ require.NoFileExists(t, filepath.Join(submodule, ".git", "hooks", "pre-commit"))++ status, out := runSandboxed(t, backend, p, `echo x > ./vendor/lib/main.go && echo x > ./.gitignore`)+ require.Equal(t, 0, status.Code, out)+}+// End-to-end through the real PolicyBuilder rather than a hand-written// policy: this is what actually ships, and `bash -lc` reading its startup// files under a denied home is the part most likely to regress.diff --git a/internal/localsandbox/seatbelt/compiler.go b/internal/localsandbox/seatbelt/compiler.goindex 511cfc2d0..84d4f567d 100644--- a/internal/localsandbox/seatbelt/compiler.go+++ b/internal/localsandbox/seatbelt/compiler.go@@ -83,6 +83,18 @@ func compileSeatbelt(p core.Policy) (seatbeltProgram, error) {denies = append(denies, fmt.Sprintf(`(deny file-write-unlink (require-all (literal (param %q)) (vnode-type DIRECTORY)))`,subParam))+ // require-not above only narrows this root's own allow. Another+ // writable root that covers the carve-out would reopen it.+ denies = append(denies,+ fmt.Sprintf("(deny file-write* (subpath (param %q)))", subParam),+ fmt.Sprintf("(deny file-write* (literal (param %q)))", subParam),+ )+ }+ if root.ProtectGitDirs {+ // The regex is a constant, so no path is inlined into the profile.+ denies = append(denies, fmt.Sprintf(+ `(deny file-write* (require-all (subpath (param %q)) (regex #"/\.[Gg][Ii][Tt](/|$)")))`,+ rootParam))}}diff --git a/internal/localsandbox/seatbelt/compiler_test.go b/internal/localsandbox/seatbelt/compiler_test.goindex 4fbec750d..02253e4e0 100644--- a/internal/localsandbox/seatbelt/compiler_test.go+++ b/internal/localsandbox/seatbelt/compiler_test.go@@ -118,6 +118,35 @@ func TestCompileSeatbeltAnchorsWritableRoot(t *testing.T) {`(deny file-write-unlink (require-all (literal (param "WRITABLE_ROOT_0")) (vnode-type DIRECTORY)))`)}+// Another writable root may cover a read-only subpath; its allow would+// reopen the carve-out, so the carve-out is also a final deny.+func TestCompileSeatbeltDeniesReadOnlySubpathAfterEveryAllow(t *testing.T) {+ prog, err := compileSeatbelt(seatbeltPolicy())+ require.NoError(t, err)++ lastAllow := strings.LastIndex(prog.Profile, "(allow ")+ for _, rule := range []string{+ `(deny file-write* (subpath (param "WRITABLE_ROOT_0_EXCLUDED_0")))`,+ `(deny file-write* (literal (param "WRITABLE_ROOT_0_EXCLUDED_0")))`,+ } {+ require.Greater(t, strings.Index(prog.Profile, rule), lastAllow, rule)+ }+}++func TestCompileSeatbeltDeniesGitDirsUnderAProtectedRoot(t *testing.T) {+ p := seatbeltPolicy()+ p.WritableRoots = append(p.WritableRoots, core.WritableRoot{+ Path: "/Users/dev/Other",+ ProtectGitDirs: true,+ })+ prog, err := compileSeatbelt(p)+ require.NoError(t, err)++ rule := `(deny file-write* (require-all (subpath (param "WRITABLE_ROOT_1")) (regex #"/\.[Gg][Ii][Tt](/|$)")))`+ require.Greater(t, strings.Index(prog.Profile, rule), strings.LastIndex(prog.Profile, "(allow "))+ require.NotContains(t, prog.Profile, `(subpath (param "WRITABLE_ROOT_0")) (regex`)+}+func TestCompileSeatbeltDeniesNetworkByDefault(t *testing.T) {prog, err := compileSeatbelt(seatbeltPolicy())require.NoError(t, err)diff --git a/internal/localsandbox/service.go b/internal/localsandbox/service.goindex 971c19884..b6f651bbc 100644--- a/internal/localsandbox/service.go+++ b/internal/localsandbox/service.go@@ -2,8 +2,11 @@ package localsandboximport ("context"+ "errors""fmt""io"+ "path/filepath"+ "slices""strings""sync""time"@@ -41,6 +44,7 @@ type Service struct {modes ModeLookupshell []stringroots *rootLocks+ sessions *sessionStates}// NewService constructs the application-facing sandbox facade.@@ -54,6 +58,7 @@ func NewService(modes: modes,shell: []string{"/bin/bash", "--noprofile", "--norc", "-c"},roots: newRootLocks(),+ sessions: newSessionStates(),}}@@ -68,6 +73,12 @@ type RunRequest struct {// pass only the keys this command needs (skill credentials, PATH tweaks).// Do not copy os.Environ() into it.Env map[string]string+ // ReviewCommand is the command as the model wrote it, before stdin or skill+ // wrapping. Approval reads it; empty means Command.+ ReviewCommand string+ // Approver asks the user. Nil means nobody can be asked, so every+ // question is answered no.+ Approver Approver}// RunResult is the captured outcome of one Run.@@ -76,6 +87,8 @@ type RunResult struct {Stderr stringExit ExitStatusDenial Denial+ // Notice is a sandbox note for the model, appended to stderr by the caller.+ Notice string}// workspaceFor resolves the session workspace and its policy.@@ -106,6 +119,16 @@ func (s *Service) workspaceFor(sessionID, mode, ws.Root, err)return Workspace{}, Policy{}, err}+ for _, g := range s.sessions.grants(sessionID) {+ relaxed, err := s.builder.Relax(policy, g)+ if err != nil {+ // A grant stops fitting when the session's project changes.+ logger.Warnf(ctx, "[LocalSandbox] drop session grant session=%s path=%s: %v",+ sessionID, g.Path, err)+ continue+ }+ policy = relaxed+ }logger.Debugf(ctx, "[LocalSandbox] workspace session=%s kind=%d root=%s mode=%s writable=%d",sessionID, ws.Kind, ws.Root, mode, len(policy.WritableRoots))return ws, policy, nil@@ -125,7 +148,19 @@ func (s *Service) GuardForSession(return NewPathGuard(policy), ws, nil}-// Run executes one shell command inside the session's workspace.+// SessionGrants returns the grants the user approved for the rest of a session.+func (s *Service) SessionGrants(sessionID string) []Grant {+ return s.sessions.grants(sessionID)+}++// ReleaseSession forgets every approval made in a session.+func (s *Service) ReleaseSession(sessionID string) {+ s.sessions.release(sessionID)+}++// Run executes one shell command inside the session's workspace. Approval+// waits happen outside the root lock so parallel tool calls are not stalled+// behind a user who has not answered yet.func (s *Service) Run(ctx context.Context, req RunRequest) (*RunResult, error) {if err := s.ensureBackend(ctx); err != nil {return nil, err@@ -134,7 +169,231 @@ func (s *Service) Run(ctx context.Context, req RunRequest) (*RunResult, error) {if err != nil {return nil, err}- return s.runPolicy(ctx, ws.Root, policy, req)+ cwd, err := commandCwd(policy, req.WorkDir)+ if err != nil {+ logger.Warnf(ctx, "[LocalSandbox] work_dir denied session=%s work_dir=%q: %v",+ req.SessionID, req.WorkDir, err)+ return nil, err+ }+ review := req.ReviewCommand+ if review == "" {+ review = req.Command+ }+ policy, refused := s.approveDelete(ctx, req, policy, review, cwd)+ if refused != nil {+ return refused, nil+ }+ res, err := s.runPolicy(ctx, ws.Root, policy, req)+ if err != nil || !res.Denial.IsDenied() {+ return res, err+ }+ return s.escalate(ctx, ws.Root, policy, cwd, review, req, res)+}++var errNoApprover = errors.New("nobody can approve it in this session")++// approveDelete asks before a delete runs. A delete outside the policy also+// needs its directory, so the same card asks for both and the command runs+// once with that access instead of failing first and asking again.+func (s *Service) approveDelete(+ ctx context.Context, req RunRequest, policy Policy, review, cwd string,+) (Policy, *RunResult) {+ segments := DeleteSegments(review, s.builder.HomeDir())+ if len(segments) == 0 {+ return policy, nil+ }+ dangerous := false+ opaque := false+ rules := make([]DeleteRule, 0, len(segments))+ for _, segment := range segments {+ dangerous = dangerous || segment.Dangerous+ opaque = opaque || segment.Opaque+ rules = append(rules, segment.Rule)+ }+ // The session remembers the shape of each delete, like a Codex prefix+ // rule, so the model may name other files or reorder options. Every+ // delete in the command must be covered. An opaque command hides a+ // delete no rule can name, so it is asked every time. Rules ignore+ // operands, so a delete that reaches past cwd or empties it is too.+ rememberable := !dangerous && !opaque && DeletesStayBelow(review, cwd, s.builder.HomeDir())+ proposed, needsDir := s.deleteGrant(policy, review, cwd)+ if rememberable && !needsDir && s.sessions.rulesCover(req.SessionID, cwd, rules) {+ return policy, nil+ }+ reason := ReasonDelete+ if dangerous {+ reason = ReasonDangerous+ }+ approval := ApprovalRequest{+ SessionID: req.SessionID,+ Command: review,+ Cwd: cwd,+ Reason: reason,+ AllowSession: rememberable,+ }+ if rememberable {+ approval.SessionRules = ruleLabels(rules)+ }+ if needsDir {+ approval.Proposed = &proposed+ }+ d, err := s.ask(ctx, req.Approver, approval)+ if err != nil || !d.Approved {+ return policy, &RunResult{Exit: ExitStatus{Code: 1}, Notice: refusalNotice("delete command", d, err)}+ }+ if needsDir {+ // A delete needs write access, so the card's read-only choice is ignored.+ relaxed, err := s.builder.Relax(policy, proposed)+ if err != nil {+ return policy, &RunResult{+ Exit: ExitStatus{Code: 1},+ Notice: fmt.Sprintf("[sandbox] could not widen the sandbox for %s: %v", proposed.Path, err),+ }+ }+ policy = relaxed+ logger.Infof(ctx, "[LocalSandbox] delete runs with grant session=%s path=%s session_scope=%t",+ req.SessionID, proposed.Path, d.Session)+ }+ if d.Session && rememberable {+ for _, rule := range rules {+ s.sessions.approveRule(req.SessionID, cwd, rule)+ }+ if needsDir {+ s.sessions.addGrant(req.SessionID, proposed)+ }+ }+ return policy, nil+}++// deleteGrant is the directory a delete needs when it removes something the+// policy cannot write. Removing an entry writes its parent, so the proposal is+// a target's parent directory; a grant on a directory being removed would+// leave its own rmdir blocked. Only the first grantable directory is offered;+// a second one is still asked after the run, like any other denial.+func (s *Service) deleteGrant(policy Policy, review, cwd string) (Grant, bool) {+ guard := NewPathGuard(policy)+ for _, target := range DeleteTargets(review, s.builder.HomeDir()) {+ if !filepath.IsAbs(target) {+ target = filepath.Join(cwd, target)+ }+ target = filepath.Clean(target)+ if _, err := guard.CheckWrite(target); err == nil {+ continue+ }+ parent := Denial{Reason: DenialPolicy, Path: filepath.Dir(target)}+ if g, ok := s.builder.ProposeGrant(policy, parent, cwd); ok {+ return g, true+ }+ }+ return Grant{}, false+}++func ruleLabels(rules []DeleteRule) []string {+ labels := make([]string, 0, len(rules))+ for _, rule := range rules {+ if label := rule.String(); label != "" && !slices.Contains(labels, label) {+ labels = append(labels, label)+ }+ }+ return labels+}++// maxEscalations is how many distinct directories one command may ask to+// widen. The first denial asks, the retry asks once more if it hits a+// different directory, and a further denial is returned as-is.+const maxEscalations = 2++func (s *Service) escalate(+ ctx context.Context, lockRoot string, policy Policy, cwd, review string, req RunRequest, res *RunResult,+) (*RunResult, error) {+ for range maxEscalations {+ proposed, ok := s.builder.ProposeGrant(policy, res.Denial, cwd)+ if !ok {+ res.Notice = blockedNotice(res.Denial)+ return res, nil+ }+ d, err := s.ask(ctx, req.Approver, ApprovalRequest{+ SessionID: req.SessionID,+ Command: review,+ Cwd: cwd,+ Reason: ReasonDenied,+ Proposed: &proposed,+ DenialSnippet: res.Denial.Snippet,+ FirstAttemptRan: true,+ AllowSession: true,+ })+ if err != nil || !d.Approved {+ res.Notice = blockedNotice(res.Denial) + "\n" + refusalNotice("access request", d, err)+ return res, nil+ }+ grant := narrowGrant(proposed, d.Grant)+ relaxed, err := s.builder.Relax(policy, grant)+ if err != nil {+ res.Notice = fmt.Sprintf("[sandbox] could not widen the sandbox for %s: %v", grant.Path, err)+ return res, nil+ }+ if d.Session {+ s.sessions.addGrant(req.SessionID, grant)+ }+ logger.Infof(ctx, "[LocalSandbox] re-running with grant session=%s path=%s access=%s session_scope=%t",+ req.SessionID, grant.Path, grant.Access, d.Session)+ next, err := s.runPolicy(ctx, lockRoot, relaxed, req)+ if err != nil {+ return nil, err+ }+ if !next.Denial.IsDenied() {+ return next, nil+ }+ policy = relaxed+ res = next+ }+ res.Notice = blockedNotice(res.Denial)+ return res, nil+}++func (s *Service) ask(ctx context.Context, approver Approver, req ApprovalRequest) (ApprovalDecision, error) {+ if approver == nil {+ return ApprovalDecision{}, errNoApprover+ }+ logger.Infof(ctx, "[LocalSandbox] approval requested session=%s reason=%s command=%q",+ req.SessionID, req.Reason, previewCommand(req.Command))+ d, err := approver.Approve(ctx, req)+ if err != nil {+ logger.Warnf(ctx, "[LocalSandbox] approval failed session=%s reason=%s: %v", req.SessionID, req.Reason, err)+ return ApprovalDecision{}, err+ }+ logger.Infof(ctx, "[LocalSandbox] approval answered session=%s reason=%s approved=%t session_scope=%t",+ req.SessionID, req.Reason, d.Approved, d.Session)+ return d, nil+}++// narrowGrant applies the user's choice. Only write to read is honoured; the+// path always stays the one proposed.+func narrowGrant(proposed Grant, chosen *Grant) Grant {+ if chosen != nil && chosen.Access == AccessRead {+ proposed.Access = AccessRead+ }+ return proposed+}++func blockedNotice(d Denial) string {+ if d.Path != "" {+ return fmt.Sprintf("[sandbox] blocked: %s is outside what this session may access", d.Path)+ }+ return "[sandbox] blocked by the workspace sandbox"+}++func refusalNotice(what string, d ApprovalDecision, err error) string {+ switch {+ case errors.Is(err, errNoApprover):+ return fmt.Sprintf("[sandbox] this %s needs the user's approval, and %v", what, err)+ case err != nil:+ return fmt.Sprintf("[sandbox] the approval request for this %s failed: %v", what, err)+ case d.Reason != "":+ return fmt.Sprintf("[sandbox] the user denied this %s: %q. Do not retry it another way.", what, d.Reason)+ default:+ return fmt.Sprintf("[sandbox] the user denied this %s. Do not retry it another way.", what)+ }}// RunWithPolicy runs one command under a policy the caller built. Skill@@ -166,17 +425,11 @@ func (s *Service) runPolicy(ctx context.Context, lockRoot string, policy Policy,unlock := s.LockRoot(lockRoot)defer unlock()- cwd := policy.Cwd- if req.WorkDir != "" {- // work_dir is a convenience for the model, not a privilege boundary;- // it is checked against the same guard the file tools use.- resolved, err := NewPathGuard(policy).CheckDir(req.WorkDir)- if err != nil {- logger.Warnf(ctx, "[LocalSandbox] work_dir denied session=%s work_dir=%q: %v",- req.SessionID, req.WorkDir, err)- return nil, err- }- cwd = resolved+ cwd, err := commandCwd(policy, req.WorkDir)+ if err != nil {+ logger.Warnf(ctx, "[LocalSandbox] work_dir denied session=%s work_dir=%q: %v",+ req.SessionID, req.WorkDir, err)+ return nil, err}timeout := req.Timeout@@ -251,6 +504,15 @@ func (s *Service) runPolicy(ctx context.Context, lockRoot string, policy Policy,}, nil}+func commandCwd(policy Policy, workDir string) (string, error) {+ if workDir == "" {+ return policy.Cwd, nil+ }+ // work_dir is a convenience for the model, not a privilege boundary;+ // it is checked against the same guard the file tools use.+ return NewPathGuard(policy).CheckDir(workDir)+}+func watchKill(ctx context.Context, done <-chan struct{}, proc Process) {select {case <-done:diff --git a/internal/localsandbox/service_approval_test.go b/internal/localsandbox/service_approval_test.gonew file mode 100644index 000000000..b71d66e33--- /dev/null+++ b/internal/localsandbox/service_approval_test.go@@ -0,0 +1,536 @@+package localsandbox++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "testing"++ "github.com/stretchr/testify/require"+)++type fakeApprover struct {+ decisions []ApprovalDecision+ err error+ requests []ApprovalRequest+}++func (a *fakeApprover) Approve(_ context.Context, req ApprovalRequest) (ApprovalDecision, error) {+ a.requests = append(a.requests, req)+ if a.err != nil {+ return ApprovalDecision{}, a.err+ }+ if len(a.decisions) == 0 {+ return ApprovalDecision{}, nil+ }+ d := a.decisions[0]+ a.decisions = a.decisions[1:]+ return d, nil+}++// deniedOnce makes the first spawn fail with stderr and every later spawn succeed.+func deniedOnce(backend *fakeBackend, stderr string) {+ spawns := 0+ backend.stderr = stderr+ backend.exit = ExitStatus{Code: 1}+ backend.onSpawn = func() {+ spawns+++ if spawns == 2 {+ backend.stderr = ""+ backend.exit = ExitStatus{Code: 0}+ }+ }+}++func TestRunAsksBeforeDelete(t *testing.T) {+ backend := &fakeBackend{}+ svc, root, _ := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true}}}++ res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "rm a.txt", Approver: approver})+ require.NoError(t, err)+ require.Equal(t, 0, res.Exit.Code)+ require.Len(t, backend.prepared, 1)+ require.Len(t, approver.requests, 1)+ req := approver.requests[0]+ require.Equal(t, ReasonDelete, req.Reason)+ require.Equal(t, "rm a.txt", req.Command)+ require.Equal(t, root, req.Cwd)+ require.True(t, req.AllowSession)+ require.Nil(t, req.Proposed, "a delete inside the workspace needs no directory")+}++// A quoted or escaped path after git -C must not hide the delete from the+// approval gate: the classifier still has to ask.+func TestRunAsksBeforeQuotedGitClean(t *testing.T) {+ backend := &fakeBackend{}+ svc, root, _ := approvalFixture(t, backend)++ for _, command := range []string{`git -C "my repo" clean -fd`, `git -C my\ repo clean -fd`} {+ backend.prepared = nil+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true}}}+ res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: command, Approver: approver})+ require.NoError(t, err, command)+ require.Equal(t, 0, res.Exit.Code, command)+ require.Len(t, approver.requests, 1, command)+ require.Len(t, backend.prepared, 1, "the delete must spawn only after approval: %s", command)+ req := approver.requests[0]+ require.Equal(t, ReasonDelete, req.Reason, command)+ require.Equal(t, command, req.Command)+ require.Equal(t, root, req.Cwd)+ require.True(t, req.AllowSession, command)+ }+}++func TestRunRefusesDeleteWithoutApprover(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, _ := approvalFixture(t, backend)++ res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "rm a.txt"})+ require.NoError(t, err)+ require.Equal(t, 1, res.Exit.Code)+ require.Contains(t, res.Notice, "needs the user's approval")+ require.Empty(t, backend.prepared)+}++func TestRunDeleteRejectedDoesNotSpawn(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, _ := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: false, Reason: "keep it"}}}++ res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "rm a.txt", Approver: approver})+ require.NoError(t, err)+ require.Contains(t, res.Notice, "keep it")+ require.Empty(t, backend.prepared)+}++func TestRunApproverErrorRefusesDelete(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, _ := approvalFixture(t, backend)+ approver := &fakeApprover{err: errors.New("the approval request timed out")}++ res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "rm a.txt", Approver: approver})+ require.NoError(t, err)+ require.Contains(t, res.Notice, "timed out")+ require.Empty(t, backend.prepared)+}++func TestRunRemembersSessionDeleteApprovalPerCwd(t *testing.T) {+ backend := &fakeBackend{}+ svc, root, _ := approvalFixture(t, backend)+ sub := filepath.Join(root, "sub")+ require.NoError(t, os.MkdirAll(sub, 0o755))+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true, Session: true}, {Approved: true}}}+ ctx := context.Background()++ for i := 0; i < 2; i++ {+ _, err := svc.Run(ctx, RunRequest{SessionID: "s1", Command: "rm a.txt", Approver: approver})+ require.NoError(t, err)+ }+ require.Len(t, approver.requests, 1)++ _, err := svc.Run(ctx, RunRequest{SessionID: "s1", Command: "rm a.txt", WorkDir: sub, Approver: approver})+ require.NoError(t, err)+ require.Len(t, approver.requests, 2, "a different cwd must ask again")+}++func runAll(t *testing.T, svc *Service, approver *fakeApprover, commands ...string) {+ t.Helper()+ for _, command := range commands {+ _, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: command, Approver: approver})+ require.NoError(t, err, command)+ }+}++// The model rarely repeats a command word for word. The session remembers the+// shape of each delete (program and options), so other files, another order+// of options, or other commands around it still match.+func TestRunSessionDeleteApprovalCoversTheSameRule(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, _ := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true, Session: true}}}++ runAll(t, svc, approver, "rm -rf build")+ require.Len(t, approver.requests, 1)+ require.Equal(t, []string{"rm -f -r"}, approver.requests[0].SessionRules)++ runAll(t, svc, approver, "rm -fr dist", "ls && rm -r -f out", "sudo rm -rf x", "rm a.txt")+ require.Len(t, approver.requests, 1, "the approved rule covers these")++ for _, command := range []string{"rm -rfv y", "git clean -fd", "rmdir d"} {+ before := len(approver.requests)+ runAll(t, svc, approver, command)+ require.Len(t, approver.requests, before+1, command)+ }+}++func TestRunSessionDeleteApprovalDoesNotWidenOptions(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, _ := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true, Session: true}}}++ runAll(t, svc, approver, "rm a.txt", "rm -rf dir")+ require.Len(t, approver.requests, 2, "a plain rm approval must not cover rm -rf")+}++func TestRunSessionDeleteApprovalNeedsEveryDeleteCovered(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, _ := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true, Session: true}}}++ runAll(t, svc, approver, "rm a.txt", "rm b.txt && rmdir d")+ require.Len(t, approver.requests, 2)+ require.Equal(t, []string{"rm", "rmdir"}, approver.requests[1].SessionRules)+}++// A substitution hides a delete the rule cannot name; an approved rm next to+// it must not let it through.+func TestRunHiddenDeleteIsNotCoveredByAnApprovedRule(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, _ := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true, Session: true}}}++ runAll(t, svc, approver, "rm a.txt", "rm a.txt; echo $(rm -rf .)")+ require.Len(t, approver.requests, 2)+ require.False(t, approver.requests[1].AllowSession)+ require.Empty(t, approver.requests[1].SessionRules)+}++func TestRunShellScriptDeleteCannotBeRememberedForTheSession(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, _ := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true, Session: true}}}++ _, err := svc.Run(context.Background(), RunRequest{+ SessionID: "s1", Command: "rm a.txt; bash -c 'rm -rf .'", Approver: approver,+ })+ require.NoError(t, err)+ require.Len(t, approver.requests, 1)+ require.False(t, approver.requests[0].AllowSession)+}++func TestRunDangerousDeleteIsNeverRemembered(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, _ := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true, Session: true}, {Approved: true}}}+ ctx := context.Background()++ for i := 0; i < 2; i++ {+ _, err := svc.Run(ctx, RunRequest{SessionID: "s1", Command: "rm -rf ~", Approver: approver})+ require.NoError(t, err)+ }+ require.Len(t, approver.requests, 2)+ require.Equal(t, ReasonDangerous, approver.requests[0].Reason)+ require.False(t, approver.requests[0].AllowSession)+ require.Empty(t, approver.requests[0].SessionRules)+}++// shell_exec wraps stdin and skill environments around the command; the+// wrapper must not hide a delete from the approval check.+func TestRunReviewsOriginalCommand(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, _ := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true}}}++ _, err := svc.Run(context.Background(), RunRequest{+ SessionID: "s1",+ Command: "printf %s cm0gYS50eHQ= | base64 -d | /bin/bash --noprofile --norc -c 'sh'",+ ReviewCommand: "rm a.txt",+ Approver: approver,+ })+ require.NoError(t, err)+ require.Len(t, approver.requests, 1)+ require.Equal(t, "rm a.txt", approver.requests[0].Command)+}++func TestRunEscalatesOutsideWriteAndRetriesOnce(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ deniedOnce(backend, "touch: "+filepath.Join(other, "a")+": Operation not permitted")+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true}}}++ res, err := svc.Run(context.Background(), RunRequest{+ SessionID: "s1", Command: "touch " + filepath.Join(other, "a"), Approver: approver,+ })+ require.NoError(t, err)+ require.Equal(t, 0, res.Exit.Code)+ require.Len(t, backend.prepared, 2)+ require.NotEqual(t, backend.prepared[0], backend.prepared[1])+ require.Len(t, approver.requests, 1)+ req := approver.requests[0]+ require.Equal(t, ReasonDenied, req.Reason)+ require.Equal(t, &Grant{Path: other, Access: AccessWrite}, req.Proposed)+ require.True(t, req.FirstAttemptRan)+ require.Empty(t, svc.SessionGrants("s1"), "a one-time approval must not stick")+}++func TestRunEscalationRetriesAtMostOnce(t *testing.T) {+ backend := &fakeBackend{exit: ExitStatus{Code: 1}}+ svc, _, other := approvalFixture(t, backend)+ backend.stderr = "touch: " + filepath.Join(other, "a") + ": Operation not permitted"+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true}, {Approved: true}}}++ res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "touch x", Approver: approver})+ require.NoError(t, err)+ require.Len(t, backend.prepared, 2)+ require.Len(t, approver.requests, 1)+ require.Contains(t, res.Notice, "[sandbox] blocked")+}++func TestRunEscalationAsksAgainForASecondDirectory(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ second := filepath.Join(filepath.Dir(other), "second")+ require.NoError(t, os.MkdirAll(second, 0o755))+ denials := []string{+ "touch: " + filepath.Join(other, "a") + ": Operation not permitted",+ "touch: " + filepath.Join(second, "b") + ": Operation not permitted",+ }+ spawns := 0+ backend.onSpawn = func() {+ if spawns < len(denials) {+ backend.stderr = denials[spawns]+ backend.exit = ExitStatus{Code: 1}+ } else {+ backend.stderr = ""+ backend.exit = ExitStatus{Code: 0}+ }+ spawns+++ }+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true}, {Approved: true}}}++ res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "touch x", Approver: approver})+ require.NoError(t, err)+ require.Equal(t, 0, res.Exit.Code)+ require.Len(t, approver.requests, 2)+ require.Equal(t, other, approver.requests[0].Proposed.Path)+ require.Equal(t, second, approver.requests[1].Proposed.Path)+ require.Len(t, backend.prepared, 3)+}++func TestRunDoesNotEscalateWhenExitIsZero(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ path := filepath.Join(other, "a")+ backend.onSpawn = func() {+ backend.stderr = "bash: " + path + ": Operation not permitted"+ backend.exit = ExitStatus{Code: 0}+ }+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true}}}++ res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "touch x", Approver: approver})+ require.NoError(t, err)+ require.Equal(t, 0, res.Exit.Code)+ require.Empty(t, res.Notice)+ require.Empty(t, approver.requests)+ require.Len(t, backend.prepared, 1)+}++// A delete outside the workspace asks once, before it runs, for both the+// delete and the directory, and then runs a single time with that access.+func TestRunOutsideDeleteAsksOnceWithTheDirectory(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ target := filepath.Join(other, "test.txt")+ require.NoError(t, os.WriteFile(target, []byte("x"), 0o644))+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true}}}++ runAll(t, svc, approver, "ls", "rm "+target)++ require.Len(t, approver.requests, 1)+ req := approver.requests[0]+ require.Equal(t, ReasonDelete, req.Reason)+ require.Equal(t, &Grant{Path: other, Access: AccessWrite}, req.Proposed)+ require.False(t, req.FirstAttemptRan)+ require.Len(t, backend.prepared, 2, "the delete must run once")+ require.NotEqual(t, backend.prepared[0], backend.prepared[1], "the delete must run with the directory open")+ require.Empty(t, svc.SessionGrants("s1"), "a one-time approval must not stick")+}++// A session rule is keyed by cwd and ignores operands, so a delete outside+// cwd is asked every time and does not leave its directory open.+func TestRunOutsideDeleteCannotBeRememberedForTheSession(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true, Session: true}, {Approved: true}}}++ runAll(t, svc, approver, "rm "+filepath.Join(other, "a.txt"), "rm "+filepath.Join(other, "b.txt"))++ require.Len(t, approver.requests, 2)+ require.False(t, approver.requests[0].AllowSession)+ require.Empty(t, approver.requests[0].SessionRules)+ require.Empty(t, svc.SessionGrants("s1"))+ require.Len(t, backend.prepared, 2)+}++// A rule approved for one delete must not cover one that empties cwd or+// reaches a directory the session opened for something else.+func TestRunSessionDeleteRuleStaysBelowCwd(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ deniedOnce(backend, "touch: "+filepath.Join(other, "a")+": Operation not permitted")+ approver := &fakeApprover{decisions: []ApprovalDecision{+ {Approved: true, Session: true},+ {Approved: true, Session: true},+ }}++ runAll(t, svc, approver, "touch "+filepath.Join(other, "a"))+ require.Equal(t, []Grant{{Path: other, Access: AccessWrite}}, svc.SessionGrants("s1"))+ runAll(t, svc, approver, "rm -rf build")+ require.Len(t, approver.requests, 2)++ for _, command := range []string{+ "rm -rf " + filepath.Join(other, "x"),+ "rm -rf *",+ "rm -rf .",+ "rm -rf ../proj",+ } {+ before := len(approver.requests)+ approver.decisions = []ApprovalDecision{{Approved: false}}+ runAll(t, svc, approver, command)+ require.Len(t, approver.requests, before+1, command)+ require.False(t, approver.requests[before].AllowSession, command)+ }+}++// Removing a directory writes its parent; a grant on the directory itself+// would leave rmdir blocked by the writable-root anchor.+func TestRunOutsideDirectoryDeleteGrantsTheParent(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ dir := filepath.Join(other, "dir")+ require.NoError(t, os.MkdirAll(dir, 0o755))+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true}}}++ runAll(t, svc, approver, "rm -rf "+dir)++ require.Len(t, approver.requests, 1)+ require.Equal(t, &Grant{Path: other, Access: AccessWrite}, approver.requests[0].Proposed)+}++// A session-approved rule skips the delete question, but the directory was+// never opened; that is still one card, not a run that fails first.+func TestRunApprovedDeleteRuleStillAsksOnceForANewDirectory(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true, Session: true}, {Approved: true}}}++ runAll(t, svc, approver, "rm a.txt", "rm "+filepath.Join(other, "b.txt"))++ require.Len(t, approver.requests, 2)+ require.Nil(t, approver.requests[0].Proposed)+ require.Equal(t, ReasonDelete, approver.requests[1].Reason)+ require.Equal(t, &Grant{Path: other, Access: AccessWrite}, approver.requests[1].Proposed)+ require.Len(t, backend.prepared, 2)+}++func TestRunOutsideDeleteCannotBeNarrowedToRead(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{+ Approved: true, Session: true, Grant: &Grant{Path: other, Access: AccessRead},+ }}}++ runAll(t, svc, approver, "rm "+filepath.Join(other, "a.txt"))++ _, base, err := svc.workspaceFor(context.Background(), "s1")+ require.NoError(t, err)+ want, err := svc.builder.Relax(base, Grant{Path: other, Access: AccessWrite})+ require.NoError(t, err)+ require.Equal(t, []string{want.Fingerprint()}, backend.prepared)+}++func TestRunDeleteOfAnUngrantableTargetOffersNoDirectory(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, _ := approvalFixture(t, backend)+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true}}}++ runAll(t, svc, approver, "rm ~/.ssh/id_rsa")++ require.Len(t, approver.requests, 1)+ require.Nil(t, approver.requests[0].Proposed)+}++func TestRunRejectedDirectoryAsksAgainOnALaterDelete(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ target := filepath.Join(other, "a")+ backend.stderr = "touch: " + target + ": Operation not permitted"+ backend.exit = ExitStatus{Code: 1}+ approver := &fakeApprover{decisions: []ApprovalDecision{+ {Approved: false, Reason: "no"},+ {Approved: true},+ {Approved: false, Reason: "no"},+ }}+ ctx := context.Background()++ res, err := svc.Run(ctx, RunRequest{SessionID: "s1", Command: "touch x", Approver: approver})+ require.NoError(t, err)+ require.Contains(t, res.Notice, `"no"`)+ require.Equal(t, ReasonDenied, approver.requests[0].Reason)++ res, err = svc.Run(ctx, RunRequest{SessionID: "s1", Command: "rm " + target, Approver: approver})+ require.NoError(t, err)+ require.Len(t, approver.requests, 2)+ require.Equal(t, ReasonDelete, approver.requests[1].Reason)+ require.Equal(t, other, approver.requests[1].Proposed.Path)+ require.NotContains(t, res.Notice, "already denied")+}++func TestRunSessionGrantCoversNextCommand(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ deniedOnce(backend, "touch: "+filepath.Join(other, "a")+": Operation not permitted")+ approver := &fakeApprover{decisions: []ApprovalDecision{{Approved: true, Session: true}}}+ ctx := context.Background()++ _, err := svc.Run(ctx, RunRequest{SessionID: "s1", Command: "touch x", Approver: approver})+ require.NoError(t, err)+ require.Equal(t, []Grant{{Path: other, Access: AccessWrite}}, svc.SessionGrants("s1"))++ guard, _, err := svc.GuardForSession(ctx, "s1")+ require.NoError(t, err)+ _, err = guard.CheckWrite(filepath.Join(other, "b"))+ require.NoError(t, err, "file tools must see the session grant too")+}++func TestRunNarrowsGrantToRead(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ deniedOnce(backend, "cat: "+filepath.Join(other, "a")+": Operation not permitted")+ approver := &fakeApprover{decisions: []ApprovalDecision{{+ Approved: true, Session: true, Grant: &Grant{Path: "/ignored", Access: AccessRead},+ }}}++ _, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "cat x", Approver: approver})+ require.NoError(t, err)+ require.Equal(t, []Grant{{Path: other, Access: AccessRead}}, svc.SessionGrants("s1"))+}++func TestRunDoesNotEscalateInsideWorkspace(t *testing.T) {+ backend := &fakeBackend{}+ svc, root, _ := approvalFixture(t, backend)+ backend.stderr = "touch: " + filepath.Join(root, "a") + ": Permission denied"+ backend.exit = ExitStatus{Code: 1}+ approver := &fakeApprover{}++ res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "touch a", Approver: approver})+ require.NoError(t, err)+ require.Empty(t, approver.requests)+ require.Len(t, backend.prepared, 1)+ require.Contains(t, res.Notice, "[sandbox] blocked")+}++func TestRunEscalationWithoutApproverOnlyReports(t *testing.T) {+ backend := &fakeBackend{}+ svc, _, other := approvalFixture(t, backend)+ backend.stderr = "touch: " + filepath.Join(other, "a") + ": Operation not permitted"+ backend.exit = ExitStatus{Code: 1}++ res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "touch x"})+ require.NoError(t, err)+ require.Len(t, backend.prepared, 1)+ require.Contains(t, res.Notice, "[sandbox] blocked")+ require.Contains(t, res.Notice, "nobody can approve")+}diff --git a/internal/localsandbox/session_state.go b/internal/localsandbox/session_state.gonew file mode 100644index 000000000..0b2ae5441--- /dev/null+++ b/internal/localsandbox/session_state.go@@ -0,0 +1,97 @@+package localsandbox++import (+ "slices"+ "sync"+)++type sessionState struct {+ grants []Grant+ // rules are the delete rules approved for the session, by cwd.+ rules map[string][]DeleteRule+}++// sessionStates holds what the user approved in each session. It lives in+// memory only: after a restart the user is asked again, which is the+// conservative default for something that widens the sandbox.+type sessionStates struct {+ mu sync.Mutex+ byID map[string]*sessionState+}++func newSessionStates() *sessionStates {+ return &sessionStates{byID: make(map[string]*sessionState)}+}++func (s *sessionStates) stateLocked(id string) *sessionState {+ st, ok := s.byID[id]+ if !ok {+ st = &sessionState{+ rules: make(map[string][]DeleteRule),+ }+ s.byID[id] = st+ }+ return st+}++func (s *sessionStates) grants(id string) []Grant {+ s.mu.Lock()+ defer s.mu.Unlock()+ st, ok := s.byID[id]+ if !ok {+ return nil+ }+ return append([]Grant(nil), st.grants...)+}++func (s *sessionStates) addGrant(id string, g Grant) {+ s.mu.Lock()+ defer s.mu.Unlock()+ st := s.stateLocked(id)+ for _, existing := range st.grants {+ if existing == g {+ return+ }+ }+ st.grants = append(st.grants, g)+}++// rulesCover reports whether every rule is covered by one approved in cwd.+// An empty list is not approved: there is nothing to skip an ask for.+func (s *sessionStates) rulesCover(id, cwd string, rules []DeleteRule) bool {+ if len(rules) == 0 {+ return false+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ st, ok := s.byID[id]+ if !ok {+ return false+ }+ approved := st.rules[cwd]+ for _, rule := range rules {+ if !slices.ContainsFunc(approved, func(a DeleteRule) bool { return a.Covers(rule) }) {+ return false+ }+ }+ return true+}++func (s *sessionStates) approveRule(id, cwd string, rule DeleteRule) {+ if rule.Program == "" {+ return+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ st := s.stateLocked(id)+ if slices.ContainsFunc(st.rules[cwd], func(a DeleteRule) bool { return a.Covers(rule) }) {+ return+ }+ st.rules[cwd] = append(st.rules[cwd], rule)+}++func (s *sessionStates) release(id string) {+ s.mu.Lock()+ defer s.mu.Unlock()+ delete(s.byID, id)+}diff --git a/internal/localsandbox/session_state_test.go b/internal/localsandbox/session_state_test.gonew file mode 100644index 000000000..39ece5c0a--- /dev/null+++ b/internal/localsandbox/session_state_test.go@@ -0,0 +1,76 @@+package localsandbox++import (+ "context"+ "os"+ "path/filepath"+ "testing"++ "github.com/stretchr/testify/require"+)++// approvalFixture resolves the temp dir first: macOS hands out /var/folders+// paths that PathGuard sees as /private/var after EvalSymlinks.+func approvalFixture(t *testing.T, backend *fakeBackend) (*Service, string, string) {+ t.Helper()+ base, err := filepath.EvalSymlinks(t.TempDir())+ require.NoError(t, err)+ home := filepath.Join(base, "home")+ root := filepath.Join(home, "proj")+ other := filepath.Join(base, "other")+ require.NoError(t, os.MkdirAll(root, 0o755))+ require.NoError(t, os.MkdirAll(other, 0o755))+ resolver := NewWorkspaceResolver(DirLayout{+ SessionRoot: filepath.Join(home, "Documents", "WeKnora"),+ }, fixedProject(root))+ builder := NewPolicyBuilder(home, filepath.Join(home, "AppData"))+ return NewService(backend, resolver, builder, fixedMode(ModeAuto)), root, other+}++func TestSessionStatesTrackApprovalsPerSession(t *testing.T) {+ s := newSessionStates()+ g := Grant{Path: "/x", Access: AccessWrite}++ s.addGrant("s1", g)+ s.addGrant("s1", g)+ require.Equal(t, []Grant{g}, s.grants("s1"))+ require.Empty(t, s.grants("s2"))++ rf := DeleteRule{Program: "rm", Flags: []string{"-f", "-r"}}+ plain := DeleteRule{Program: "rm"}+ require.False(t, s.rulesCover("s1", "/w", []DeleteRule{plain}))+ s.approveRule("s1", "/w", rf)+ s.approveRule("s1", "/w", rf)+ require.True(t, s.rulesCover("s1", "/w", []DeleteRule{plain, rf}))+ require.False(t, s.rulesCover("s1", "/other", []DeleteRule{plain}))+ require.False(t, s.rulesCover("s1", "/w", nil), "nothing to cover is not an approval")+ require.False(t, s.rulesCover("s1", "/w", []DeleteRule{plain, {Program: "rmdir"}}))++ s.release("s1")+ require.Empty(t, s.grants("s1"))+ require.False(t, s.rulesCover("s1", "/w", []DeleteRule{plain}))+}++func TestSessionGrantWidensGuardUntilReleased(t *testing.T) {+ svc, _, other := approvalFixture(t, &fakeBackend{})+ ctx := context.Background()+ target := filepath.Join(other, "b.txt")++ guard, _, err := svc.GuardForSession(ctx, "s1")+ require.NoError(t, err)+ _, err = guard.CheckWrite(target)+ require.ErrorIs(t, err, ErrPathDenied)++ svc.sessions.addGrant("s1", Grant{Path: other, Access: AccessWrite})+ require.Equal(t, []Grant{{Path: other, Access: AccessWrite}}, svc.SessionGrants("s1"))+ guard, _, err = svc.GuardForSession(ctx, "s1")+ require.NoError(t, err)+ _, err = guard.CheckWrite(target)+ require.NoError(t, err)++ svc.ReleaseSession("s1")+ guard, _, err = svc.GuardForSession(ctx, "s1")+ require.NoError(t, err)+ _, err = guard.CheckWrite(target)+ require.ErrorIs(t, err, ErrPathDenied)+}diff --git a/internal/sandbox/command_approval.go b/internal/sandbox/command_approval.gonew file mode 100644index 000000000..de840e3b8--- /dev/null+++ b/internal/sandbox/command_approval.go@@ -0,0 +1,63 @@+package sandbox++import "context"++// CommandApprovalRequest is one question for the user about a Lite host+// command. Reason is "delete", "dangerous" or "sandbox_denied".+type CommandApprovalRequest struct {+ SessionID string+ Command string+ Cwd string+ Reason string+ // GrantPath and GrantAccess describe the widening asked for: after a+ // "sandbox_denied" block, or with a delete outside the workspace.+ GrantPath string+ GrantAccess string+ DenialSnippet string+ FirstAttemptRan bool+ AllowSession bool+ // SessionRules is what a session approval of a delete remembers, such as+ // "rm -f -r"; later deletes these rules cover are not asked again.+ SessionRules []string+}++// CommandApprovalDecision is the user's answer. Access may only narrow the+// proposed grant from "write" to "read".+type CommandApprovalDecision struct {+ Approved bool+ Session bool+ Access string+ Reason string+}++// CommandApprover asks the user about a host command and blocks for the answer.+type CommandApprover interface {+ ApproveCommand(ctx context.Context, req CommandApprovalRequest) (CommandApprovalDecision, error)+}++// CommandApproval travels with one shell_exec call on a host workspace.+type CommandApproval struct {+ // Approver is nil when nobody can be asked; the host sandbox then treats+ // every question as refused.+ Approver CommandApprover+ // Command is what the model wrote, before stdin or skill wrapping.+ Command string+}++type commandApprovalKey struct{}++// WithCommandApproval attaches the approval port for one host command.+func WithCommandApproval(ctx context.Context, approval CommandApproval) context.Context {+ return context.WithValue(ctx, commandApprovalKey{}, approval)+}++// CommandApprovalFrom returns the approval port attached to ctx, if any.+func CommandApprovalFrom(ctx context.Context) (CommandApproval, bool) {+ approval, ok := ctx.Value(commandApprovalKey{}).(CommandApproval)+ return approval, ok+}++// SessionStateReleaser forgets per-session approvals when a chat is deleted.+type SessionStateReleaser interface {+ ReleaseSessionState(ctx context.Context, sessionID string)+}diff --git a/internal/sandbox/command_approval_test.go b/internal/sandbox/command_approval_test.gonew file mode 100644index 000000000..55e3eca51--- /dev/null+++ b/internal/sandbox/command_approval_test.go@@ -0,0 +1,19 @@+package sandbox++import (+ "context"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestCommandApprovalRoundTripsThroughContext(t *testing.T) {+ _, ok := CommandApprovalFrom(context.Background())+ require.False(t, ok)++ ctx := WithCommandApproval(context.Background(), CommandApproval{Command: "rm a"})+ got, ok := CommandApprovalFrom(ctx)+ require.True(t, ok)+ require.Equal(t, "rm a", got.Command)+ require.Nil(t, got.Approver)+}diff --git a/internal/types/agent.go b/internal/types/agent.goindex 42bb3154d..46b72a4f5 100644--- a/internal/types/agent.go+++ b/internal/types/agent.go@@ -509,7 +509,10 @@ type AgentStep struct {ReasoningSignature string `json:"reasoning_signature,omitempty"`ReasoningMetadata ProviderMetadata `json:"reasoning_metadata,omitempty"`ToolCalls []ToolCall `json:"tool_calls"` // Tools called in this step (Act phase)- Timestamp time.Time `json:"timestamp"` // When this step occurred+ // Approvals is the user decision for tools in this step. It is stored with+ // the step so a reloaded transcript can show what was allowed or refused.+ Approvals []ToolApprovalRecord `json:"approvals,omitempty"`+ Timestamp time.Time `json:"timestamp"` // When this step occurred// Truncated marks the round the completion-token cap cut off. It rides in// the agent_steps JSON so a reloaded, shared or re-opened conversation can// still show that the answer stops mid-sentence by design, rather than@@ -518,6 +521,39 @@ type AgentStep struct {Truncated bool `json:"truncated,omitempty"`}+// HostApprovalSnapshot is the Lite host card stored with a tool approval.+type HostApprovalSnapshot struct {+ Reason string `json:"reason"`+ Command string `json:"command,omitempty"`+ Cwd string `json:"cwd,omitempty"`+ GrantPath string `json:"grant_path,omitempty"`+ GrantAccess string `json:"grant_access,omitempty"`+ DenialSnippet string `json:"denial_snippet,omitempty"`+ FirstAttemptRan bool `json:"first_attempt_ran,omitempty"`+ AllowSession bool `json:"allow_session"`+ SessionRules []string `json:"session_rules,omitempty"`+}++// ToolApprovalRecord is one human approval attached to an agent step.+type ToolApprovalRecord struct {+ PendingID string `json:"pending_id"`+ ToolCallID string `json:"tool_call_id,omitempty"`+ Kind string `json:"kind,omitempty"`+ ServiceName string `json:"service_name,omitempty"`+ MCPToolName string `json:"mcp_tool_name,omitempty"`+ Description string `json:"description,omitempty"`+ ArgsJSON string `json:"args_json,omitempty"`+ TimeoutSeconds int `json:"timeout_seconds,omitempty"`+ RequestedAt int64 `json:"requested_at,omitempty"`+ Host *HostApprovalSnapshot `json:"host,omitempty"`+ Resolved bool `json:"resolved,omitempty"`+ Approved bool `json:"approved,omitempty"`+ Reason string `json:"reason,omitempty"`+ TimedOut bool `json:"timed_out,omitempty"`+ Canceled bool `json:"canceled,omitempty"`+ Scope string `json:"scope,omitempty"`+}+// GetObservations returns observations from all tool calls in this step// This is a convenience method to maintain backward compatibilityfunc (s *AgentStep) GetObservations() []string {diff --git a/internal/types/agent_prompt.go b/internal/types/agent_prompt.goindex 8a47fbede..23195cfcf 100644--- a/internal/types/agent_prompt.go+++ b/internal/types/agent_prompt.go@@ -225,6 +225,10 @@ type ToolApprovalPromptResponse struct {Reason string `json:"reason,omitempty"`// AllowInSession approves later calls with the request's Grant too.AllowInSession bool `json:"allow_in_session,omitempty"`+ // Scope is "once" or "session" for Lite host approvals; empty means once.+ Scope string `json:"scope,omitempty"`+ // Access narrows a host grant to "read"; empty keeps the proposal.+ Access string `json:"access,omitempty"`}// MCPOAuthPromptRequest is the Request of an AgentPromptKindMCPOAuth.diff --git a/website-docs/03-features/22-skills-sandbox.md b/website-docs/03-features/22-skills-sandbox.mdindex 7eaf26495..a2d4b51a2 100644--- a/website-docs/03-features/22-skills-sandbox.md+++ b/website-docs/03-features/22-skills-sandbox.md@@ -95,7 +95,7 @@ Cube/E2B 的 `config.network` 同时用于对话沙箱、技能安装和完整自 v0.8.2 起,[Lite 桌面版](../05-clients/05-desktop.md)在 macOS 上用系统 Seatbelt 隔离运行智能体的命令和文件工具。智能体选了 Docker、E2B 或 Cube 配置时仍走远程沙箱;没有选沙箱配置时才使用本机沙箱。Windows 和 Linux 暂不提供该能力,此时未选配置的智能体不能执行命令。-- **工作目录**:在新对话页点「选择项目」,通过系统目录选择框选定项目文件夹,对话标题栏会显示项目名。不选时显示「临时工作区」,自动在 `~/Documents/WeKnoraLite/<日期>/session-*` 下创建会话目录。不能选择主目录本身、包含主目录的目录或 `~/Library` 下的目录。+- **工作目录**:在新对话页点「选择项目」,通过系统目录选择框选定项目文件夹,对话标题栏会显示项目名。不选时显示「临时工作区」,自动在 `~/.weknora/sessions/session-*` 下创建会话目录。不能选择主目录本身、包含主目录的目录或 `~/Library` 下的目录。- **路径**:工作区是真实的本机路径,没有 `/workspace`、`/workspace/input` 和 `/workspace/output`。智能体直接在项目中修改文件,这些文件不会进入对话的产物列表;删除对话也不会删除本机目录。- **限制**:命令默认不能联网,只能写入项目目录,项目内的 `.git` 为只读。主目录中除常用开发工具链(如 `.nvm`、`.pyenv`、`.cargo`)外的内容不可读,`.ssh`、`.aws`、钥匙串等凭据位置始终不可读。- **回退**:对话回退不会还原本机项目文件,需要时请自行用 Git 管理。