feat(sandbox): stream live shell and install command output

Publish a bounded stdout/stderr tail for pending shell_exec and skill installs without putting partial logs into the model context.
main
wizardchen 2026-09-12 10:06:37 +08:00 committed by lyingbug
parent 3db7fd5389
commit a799f23b26
29 changed files with 561 additions and 18 deletions

View File

@ -0,0 +1,85 @@
<template>
<section class="sandbox-command" aria-live="off" :aria-busy="!progress.done"
:aria-label="!progress.done ? $t('settings.sandbox.installCommandRunning') : undefined">
<div class="sandbox-command-heading">
<code class="sandbox-command-code" :class="{ 'is-running': !progress.done }" :title="progress.command">{{ progress.command }}</code>
<span class="sandbox-command-elapsed">{{ commandElapsed }}</span>
</div>
<pre v-if="progress.output">{{ progress.output }}</pre>
</section>
</template>
<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue'
const props = defineProps<{
progress: { command: string; started_at: string; output: string; done: boolean }
}>()
const clock = ref(Date.now())
let timer: ReturnType<typeof setInterval> | undefined
const commandElapsed = computed(() => {
const started = Date.parse(props.progress.started_at)
const seconds = Number.isFinite(started) ? Math.max(0, Math.floor((clock.value - started) / 1000)) : 0
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`
})
watch(() => props.progress.done, done => {
clearInterval(timer)
clock.value = Date.now()
if (!done) timer = setInterval(() => { clock.value = Date.now() }, 1000)
}, { immediate: true })
onUnmounted(() => clearInterval(timer))
</script>
<style scoped lang="less">
@import './css/chat-timeline-loading.less';
.sandbox-command {
min-width: 0;
margin: 8px 0;
padding: 8px 10px;
border-radius: 4px;
background: var(--td-bg-color-secondarycontainer, #f7f7f7);
color: var(--td-text-color-secondary, #666);
font-size: 12px;
line-height: 1.5;
code, pre {
font-family: var(--td-font-family-code, monospace);
font-size: 11px;
line-height: 1.6;
}
code {
display: block;
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
pre {
max-height: 160px;
margin: 8px 0 0;
padding-top: 8px;
overflow: auto;
overscroll-behavior: contain;
border-top: 1px solid var(--td-component-stroke, #e7e7e7);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
}
.sandbox-command-heading {
display: flex;
align-items: center;
gap: 8px;
}
.sandbox-command-elapsed {
flex-shrink: 0;
color: var(--td-text-color-placeholder, #999);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
</style>

View File

@ -96,3 +96,34 @@ test('verification refuses live sends and a finished run reinstalls with instruc
assert.equal(calls[0][2], 'Install from the official guide')
assert.deepEqual(h.emitted, ['restarted'])
})
test('live output renders before tool completion and ignores a previous run', async () => {
const progressLogic = source.slice(source.indexOf('const commandOutput ='), source.indexOf('const loading ='))
const followLogic = source.slice(source.indexOf('async function follow('), source.indexOf('function wait('))
const js = ts.transpileModule(`${progressLogic}\n${followLogic}`, {
compilerOptions: { target: ts.ScriptTarget.ES2022 },
}).outputText
let handlers
const modelChunks = []
const h = vm.runInNewContext(`${js}\n({ follow, commandOutput, changeRun: () => { openRun++ } })`, {
props: { live: true, configId: 'cfg', skillId: 'skill' },
ref: value => ({ value }), computed: get => ({ get value() { return get() } }),
watch() {}, onUnmounted() {}, clearInterval() {},
getApiBaseUrl: () => '', configSkillTranscriptUrl: () => '/transcript',
localStorage: { getItem: () => null }, AbortController,
controller: null, openRun: 1, i18n: { global: {} }, generateRandomString: () => 'request',
fetchEventSource: async (_url, options) => { handlers = options; await options.onopen({ ok: true }) },
applyPrompt() {}, processStreamChunk: frame => modelChunks.push(frame),
})
assert.equal(await h.follow(1), true)
const frame = data => handlers.onmessage({ data: JSON.stringify({ response_type: 'install_output', data }) })
const started = new Date('2026-09-10T12:00:00Z').toISOString()
frame({ command: 'uv pip install -r requirements.lock', started_at: started, output: 'Downloading numpy', done: false })
assert.equal(h.commandOutput.value.output, 'Downloading numpy')
assert.equal(modelChunks.length, 0)
frame({ command: 'uv pip install -r requirements.lock', started_at: started, output: 'Installed', done: true })
assert.equal(h.commandOutput.value.done, true)
h.changeRun()
frame({ command: 'old command', output: 'late output', done: false })
assert.equal(h.commandOutput.value.output, 'Installed')
})

View File

@ -8,7 +8,8 @@
: $t('settings.sandbox.skillTranscriptEmpty') }}
</p>
<template v-else>
<div v-for="(msg, index) in messages" :key="msg.id || index" class="skill-timeline__turn">
<div v-for="(msg, index) in messages" :key="msg.id || index" class="skill-timeline__turn"
:class="{ 'skill-timeline__turn--command': index === messages.length - 1 && live && commandOutput && !commandOutput.done }">
<pre v-if="msg.role === 'user'" class="skill-timeline__prompt">{{ msg.content }}</pre>
<AgentStreamDisplay
v-else
@ -19,6 +20,11 @@
/>
</div>
</template>
<SandboxCommandProgress
v-if="live && commandOutput && !commandOutput.done"
:progress="commandOutput"
class="skill-timeline__command"
/>
<div v-for="item in guidance.messages" :key="item.id" class="skill-timeline__guidance-message">
<span>{{ $t(`settings.sandbox.skillGuidance.${item.status}`) }}</span>
<p>{{ item.content }}</p>
@ -55,6 +61,7 @@ import { configSkillTranscriptUrl, getConfigSkillGuidance, steerConfigSkill, rei
import { getApiBaseUrl } from '@/utils/api-base'
import { generateRandomString } from '@/utils/index'
import { makeSteerClientId } from '@/utils/steerId'
import SandboxCommandProgress from './SandboxCommandProgress.vue'
import AgentStreamDisplay from '@/views/chat/components/AgentStreamDisplay.vue'
import i18n from '@/i18n'
@ -144,6 +151,7 @@ watch(
onUnmounted(() => { guidanceEpoch++; clearTimeout(guidanceTimer) })
const messages = reactive<any[]>([])
const commandOutput = ref<{ command: string; started_at: string; output: string; done: boolean } | null>(null)
const loading = ref(false)
const isReplying = ref(false)
const currentAssistantMessageId = ref('')
@ -244,6 +252,10 @@ async function follow(run: number): Promise<boolean> {
} catch {
return
}
if (frame.response_type === 'install_output') {
commandOutput.value = frame.data || null
return
}
if (frame.response_type === 'install_prompt') {
applyPrompt(frame.content || '')
return
@ -269,6 +281,7 @@ async function open() {
const run = ++openRun
closed = false
messages.splice(0, messages.length)
commandOutput.value = null
const stale = () => run !== openRun || closed
try {
// A finished install already has durable rows. Replaying the event log
@ -453,4 +466,11 @@ onUnmounted(stop)
.skill-timeline--compact :deep(.agent-stream-display .answer-content.markdown-content h3) {
font-size: 12px;
}
.skill-timeline__turn--command {
// AgentStreamDisplay also renders an empty inline image-viewer trigger.
// Stack its roots so that trigger cannot create a blank text line above the command.
display: flex;
flex-direction: column;
}
.skill-timeline__command { margin: 4px 0 8px 42px; }
</style>

View File

@ -38,14 +38,16 @@
// In-progress step / thinking / tool-call titles shimmer while pending. Both the
// agent timeline (.action-pending) and the RAG pipeline (.is-running) opt in.
.action-card.action-pending .action-name,
.action-name.is-running {
.action-name.is-running,
.sandbox-command-code.is-running {
.chat-stream-shimmer-text();
}
@media (prefers-reduced-motion: reduce) {
.action-card.action-pending .action-name,
.action-name.is-running {
.action-name.is-running,
.sandbox-command-code.is-running {
animation: none;
background-image: none;
-webkit-text-fill-color: var(--td-text-color-secondary);

View File

@ -7,6 +7,28 @@ import { resetSteerTurnForReplay } from '../utils/steerStreamFork.ts'
const source = readFileSync(new URL('./useChatStreamHandler.ts', import.meta.url), 'utf8')
test('command output updates only its pending tool and cannot replace a final result', () => {
const start = source.indexOf("case 'command_output': {")
const block = source.slice(start, source.indexOf("case 'tool_result':", start))
const command = { type: 'tool_call', tool_name: 'shell_exec', tool_call_id: 'a', pending: true }
const other = { type: 'tool_call', tool_name: 'shell_exec', tool_call_id: 'b', pending: true }
const message = { agentEventStream: [command, other] }
const process = vm.runInNewContext(ts.transpile(`(dataPayload) => { switch ('command_output') { ${block} } }`), { message })
process({ tool_call_id: 'a', output: 'Reading CSV', done: false })
assert.equal(command.command_output.output, 'Reading CSV')
assert.equal(command.pending, true)
assert.equal(other.command_output, undefined)
process({ tool_call_id: 'missing', output: 'unmatched' })
assert.equal(message.agentEventStream.length, 2)
process({ tool_call_id: 'a', output: 'Finished', done: true })
process({ tool_call_id: 'a', output: 'late chunk', done: false })
assert.equal(command.command_output.output, 'Finished')
command.pending = false
command.output = 'Final tool result'
process({ tool_call_id: 'a', output: 'more late output', done: false })
assert.equal(command.output, 'Final tool result')
})
test('replaying agent_query binds the first segment and preserves distinct row IDs', () => {
const messagesList = [
{ id: 'a', role: 'assistant', request_id: 'r', steerForked: true, is_completed: true },

View File

@ -809,6 +809,19 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
}
break
}
case 'command_output': {
const toolCallId = dataPayload?.tool_call_id as string | undefined
if (!toolCallId) break
const tool = (message.agentEventStream as ChatMessage[] | undefined)?.find(
event => event.type === 'tool_call' && event.tool_call_id === toolCallId,
)
// Late progress must not resurrect a completed command or attach to
// another concurrent call just because it uses the same tool name.
if (tool?.pending && tool.tool_name === 'shell_exec' && !(tool.command_output as ChatMessage | undefined)?.done) {
tool.command_output = dataPayload
}
break
}
case 'tool_result':
case 'error': {
if (dataPayload) {
@ -1118,6 +1131,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
data.response_type === 'thinking' ||
data.response_type === 'tool_call' ||
data.response_type === 'tool_result' ||
data.response_type === 'command_output' ||
data.response_type === 'reflection' ||
data.response_type === 'artifacts_pending' ||
data.response_type === 'context_compacted' ||

View File

@ -51,6 +51,15 @@ test('critical runtime i18n trees are present', () => {
assert.deepEqual(missing, [], missing.join('\n'))
})
test('installer command progress messages resolve in the settings namespace', () => {
for (const [locale, bundle] of Object.entries(LOCALE_BUNDLES)) {
for (const name of ['installCommandRunning', 'installCommandWaiting']) {
const key = `settings.sandbox.${name}`
assert.equal(typeof getLocaleValueAtPath(bundle, key), 'string', `${locale}: missing ${key}`)
}
}
})
test('referenced i18n keys used in app code exist in every locale', () => {
const failures = findUsedKeysMissingInLocales(referencedKeys, localeKeysByName)
assert.deepEqual(failures, [], failures.slice(0, 20).join('\n'))

View File

@ -1548,6 +1548,8 @@ export default {
},
skillTranscriptEmpty: 'This install left no transcript.',
skillTranscriptWaiting: 'Install has started. Waiting for the process log…',
installCommandRunning: "Command running",
installCommandWaiting: "Waiting for command output. Elapsed time continues to update.",
skillFiles: 'View files',
skillFilesTitle: 'Files',
skillFilesEmpty: 'This skill has no files to browse yet.',

View File

@ -1548,6 +1548,8 @@ export default {
},
skillTranscriptEmpty: 'このインストールには記録が残っていません。',
skillTranscriptWaiting: 'インストールを開始しました。処理ログを待っています…',
installCommandRunning: "コマンド実行中",
installCommandWaiting: "出力を待っています。経過時間は更新されます。",
skillFiles: 'ファイルを表示',
skillFilesTitle: 'ファイル',
skillFilesEmpty: 'このスキルには参照できるファイルがまだありません。',

View File

@ -5684,6 +5684,8 @@ export default {
},
skillTranscriptEmpty: 'This install left no transcript.',
skillTranscriptWaiting: 'Install has started. Waiting for the process log…',
installCommandRunning: "명령 실행 중",
installCommandWaiting: "명령 출력을 기다리는 중입니다. 경과 시간은 계속 업데이트됩니다.",
skillFiles: '파일 보기',
skillFilesTitle: '파일',
skillFilesEmpty: '이 스킬에서 볼 수 있는 파일이 아직 없습니다.',

View File

@ -5684,6 +5684,8 @@ export default {
},
skillTranscriptEmpty: 'This install left no transcript.',
skillTranscriptWaiting: 'Install has started. Waiting for the process log…',
installCommandRunning: "Команда выполняется",
installCommandWaiting: "Ожидание вывода команды. Время выполнения обновляется.",
skillFiles: 'Просмотреть файлы',
skillFilesTitle: 'Файлы',
skillFilesEmpty: 'У этого навыка пока нет файлов для просмотра.',

View File

@ -5686,6 +5686,8 @@ export default {
},
skillTranscriptEmpty: '这次安装没有留下记录。',
skillTranscriptWaiting: '安装已开始,正在等待过程记录…',
installCommandRunning: "命令执行中",
installCommandWaiting: "等待命令输出,耗时持续更新。",
skillFiles: '查看文件',
skillFilesTitle: '文件',
skillFilesEmpty: '该技能还没有可查看的文件。',

View File

@ -204,6 +204,11 @@
<div class="results-summary-text" v-html="getKnowledgeChunksSummary(event.tool_data)"></div>
</div>
<SandboxCommandProgress
v-if="event.tool_name === 'shell_exec' && event.pending && event.command_output && !event.command_output.done"
:progress="event.command_output"
/>
<div v-if="!event.pending && event.tool_name === 'attachment_parsing'"
class="search-results-summary-fixed attachment-parsing-summary">
<div class="results-summary-text" v-html="getAttachmentParsingSummary(event)"></div>
@ -495,6 +500,11 @@
<div class="results-summary-text" v-html="getKnowledgeChunksSummary(event.tool_data)"></div>
</div>
<SandboxCommandProgress
v-if="event.tool_name === 'shell_exec' && event.pending && event.command_output && !event.command_output.done"
:progress="event.command_output"
/>
<div v-if="!event.pending && event.tool_name === 'attachment_parsing'"
class="search-results-summary-fixed attachment-parsing-summary">
<div class="results-summary-text" v-html="getAttachmentParsingSummary(event)"></div>
@ -597,6 +607,7 @@ import { ref, computed, watch, onMounted, onBeforeUnmount, onUpdated, nextTick }
import { useRouter, useRoute } from 'vue-router';
import { marked } from 'marked';
import 'katex/dist/katex.min.css';
import SandboxCommandProgress from '@/components/SandboxCommandProgress.vue';
import ToolResultRenderer from './ToolResultRenderer.vue';
import ToolApprovalCard from './ToolApprovalCard.vue';
import McpOAuthCard from './McpOAuthCard.vue';

View File

@ -0,0 +1,85 @@
package tools
import (
"context"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/Tencent/WeKnora/internal/event"
"github.com/google/uuid"
)
// Shell tools publish this bounded, human-facing preview. It is not
// appended to the model conversation and does not change the final tool result.
func shellCommandOutput(ctx context.Context, command string) (func(string, []byte), func()) {
meta, ok := ToolExecFromContext(ctx)
if !ok || meta.EventBus == nil {
return nil, func() {}
}
started := time.Now()
var mu sync.Mutex
var tail string
var last time.Time
var flushTimer *time.Timer
sentOutput := false
closed := false
emit := func(done bool) {
last = time.Now()
_ = meta.EventBus.Emit(ctx, event.Event{
ID: uuid.NewString(), Type: event.EventAgentCommandOutput, SessionID: meta.SessionID,
Data: event.CommandOutputData{
ToolCallID: meta.ToolCallID,
Command: maskCommandAssignments(command), StartedAt: started,
Output: strings.ToValidUTF8(tail, ""), Done: done,
},
})
}
emit(false)
appendOutput := func(_ string, chunk []byte) {
mu.Lock()
defer mu.Unlock()
if closed {
return
}
tail += string(chunk)
const limit = 8192
if len(tail) > limit {
tail = tail[len(tail)-limit:]
for len(tail) > 0 && !utf8.RuneStart(tail[0]) {
tail = tail[1:]
}
}
if !sentOutput || time.Since(last) >= 500*time.Millisecond {
if flushTimer != nil {
flushTimer.Stop()
flushTimer = nil
}
sentOutput = true
emit(false)
} else if flushTimer == nil {
flushTimer = time.AfterFunc(500*time.Millisecond-time.Since(last), func() {
mu.Lock()
defer mu.Unlock()
flushTimer = nil
if !closed {
emit(false)
}
})
}
}
finish := func() {
mu.Lock()
defer mu.Unlock()
if !closed {
closed = true
if flushTimer != nil {
flushTimer.Stop()
flushTimer = nil
}
emit(true)
}
}
return appendOutput, finish
}

View File

@ -0,0 +1,74 @@
package tools
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/event"
"github.com/stretchr/testify/require"
)
func TestShellCommandOutputIsBoundedAndFinishes(t *testing.T) {
bus := event.NewEventBus()
updates := make(chan event.CommandOutputData, 16)
bus.On(event.EventAgentCommandOutput, func(_ context.Context, e event.Event) error {
updates <- e.Data.(event.CommandOutputData)
return nil
})
next := func() event.CommandOutputData {
select {
case update := <-updates:
return update
case <-time.After(3 * time.Second):
t.Fatal("missing progress event")
return event.CommandOutputData{}
}
}
ctx := WithToolExecContext(context.Background(), &ToolExecContext{
EventBus: bus, ToolCallID: "cmd-1", SessionID: "session",
})
output, finish := shellCommandOutput(ctx, "uv pip install -r requirements.lock")
defer finish()
start := next()
require.Equal(t, "cmd-1", start.ToolCallID)
require.False(t, start.Done)
output("stdout", []byte(strings.Repeat("x", 16000)))
first := next()
require.LessOrEqual(t, len(first.Output), 8192)
output("stderr", []byte("\ndownloading wheel"))
// A short burst followed by a long silent download must still flush before completion.
progress := next()
require.Contains(t, progress.Output, "downloading wheel")
require.False(t, progress.Done)
finish()
finish()
require.True(t, next().Done)
output("stdout", []byte("late callback"))
require.Empty(t, updates)
}
func TestShellExecPublishesCommandProgress(t *testing.T) {
bus := event.NewEventBus()
var updates []event.CommandOutputData
bus.On(event.EventAgentCommandOutput, func(_ context.Context, e event.Event) error {
updates = append(updates, e.Data.(event.CommandOutputData))
return nil
})
executor := &fakeShellExecutor{}
tool := NewShellExecTool(executor, nil)
ctx := WithToolExecContext(context.Background(), &ToolExecContext{
EventBus: bus, SessionID: "session", ToolCallID: "call",
})
result, err := tool.Execute(ctx, json.RawMessage(`{"command":"cat","stdin":"private input"}`))
require.NoError(t, err)
require.True(t, result.Success)
require.Len(t, updates, 2)
require.Equal(t, "call", updates[0].ToolCallID)
require.Equal(t, "cat", updates[0].Command, "progress shows the requested command, not the encoded stdin wrapper")
require.False(t, updates[0].Done)
require.True(t, updates[1].Done)
}

View File

@ -491,7 +491,12 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ
" | base64 -d | /bin/bash --noprofile --norc -c " + sandbox.ShellQuote(execCommand)
}
beforeOutputs, inspectedOutputs := sandboxOutputSnapshot(ctx, t.executor, sessionID)
res, err := t.executor.ExecShellCommand(ctx, sessionID, execCommand, workDir, timeout, env)
output, finishOutput := shellCommandOutput(ctx, command)
defer finishOutput()
// Observe only the requested command, not skill staging or artifact probes.
execCtx := sandbox.WithCommandOutput(ctx, output)
res, err := t.executor.ExecShellCommand(execCtx, sessionID, execCommand, workDir, timeout, env)
finishOutput()
noteSandboxMutation()
if err != nil {
logger.Warnf(ctx, "[Tool][ShellExec] execution error: session=%s err=%v", sessionID, err)

View File

@ -155,6 +155,7 @@ func (tr *installTranscript) Subscribe() {
}
tr.bus.On(event.EventAgentThought, tr.onThought)
tr.bus.On(event.EventAgentToolCall, tr.onToolCall)
tr.bus.On(event.EventAgentCommandOutput, tr.onInstallOutput)
tr.bus.On(event.EventAgentToolResult, tr.onToolResult)
tr.bus.On(event.EventAgentFinalAnswer, tr.onAnswer)
tr.bus.On(event.EventError, tr.onError)
@ -560,3 +561,24 @@ func asymptoticInstallPercent(k int) int {
}
return p
}
func (tr *installTranscript) onInstallOutput(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.CommandOutputData)
if !ok {
return nil
}
tr.mu.Lock()
closed := tr.closed
tr.mu.Unlock()
if closed {
return nil
}
tr.append(interfaces.StreamEvent{
ID: evt.ID, Type: types.ResponseTypeInstallOutput, Timestamp: time.Now(),
Data: map[string]interface{}{
"tool_call_id": data.ToolCallID, "command": data.Command,
"started_at": data.StartedAt, "output": data.Output, "done": data.Done,
},
})
return nil
}

View File

@ -453,3 +453,24 @@ func TestInstallTranscriptWithoutActivityPublisherStaysSilent(t *testing.T) {
require.Equal(t, []types.ResponseType{types.ResponseTypeToolCall, types.ResponseTypeComplete},
streams.types(), "the transcript itself is unchanged by progress being unwired")
}
func TestInstallTranscriptProjectsOutputWithoutCompletingTool(t *testing.T) {
streams := &transcriptStreams{}
bus := event.NewEventBus()
tr := newInstallTranscript(context.Background(), bus, streams, nil, "session", "message", nil)
tr.Subscribe()
require.NoError(t, bus.Emit(context.Background(), event.Event{
ID: "chunk", Type: event.EventAgentCommandOutput,
Data: event.CommandOutputData{ToolCallID: "tool", Output: "Downloading polars", Done: false},
}))
require.Len(t, streams.events, 1)
require.Equal(t, types.ResponseTypeInstallOutput, streams.events[0].Type)
require.Equal(t, "tool", streams.events[0].Data["tool_call_id"])
require.Equal(t, "Downloading polars", streams.events[0].Data["output"])
require.False(t, streams.events[0].Done)
tr.closed = true
require.NoError(t, tr.onInstallOutput(context.Background(), event.Event{
Data: event.CommandOutputData{Output: "late"},
}))
require.Len(t, streams.events, 1)
}

View File

@ -49,12 +49,13 @@ const (
EventAgentComplete EventType = "agent.complete" // Agent 完成
// Agent streaming events (for real-time feedback)
EventAgentThought EventType = "thought" // Agent 思考过程
EventAgentToolCall EventType = "tool_call" // 工具调用通知
EventAgentToolResult EventType = "tool_result" // 工具结果
EventAgentReflection EventType = "reflection" // Agent 反思
EventAgentReferences EventType = "references" // 知识引用
EventAgentFinalAnswer EventType = "final_answer" // 最终答案
EventAgentThought EventType = "thought" // Agent 思考过程
EventAgentCommandOutput EventType = "command_output" // bounded command output
EventAgentToolCall EventType = "tool_call" // 工具调用通知
EventAgentToolResult EventType = "tool_result" // 工具结果
EventAgentReflection EventType = "reflection" // Agent 反思
EventAgentReferences EventType = "references" // 知识引用
EventAgentFinalAnswer EventType = "final_answer" // 最终答案
// MCP tool human approval (issue #1173)
EventToolApprovalRequired EventType = "tool_approval_required"

View File

@ -1,5 +1,7 @@
package event
import "time"
// EventData contains common event data structures for different stages
// QueryData represents query-related event data
@ -303,3 +305,13 @@ type MCPOAuthResolvedData struct {
TimedOut bool `json:"timed_out,omitempty"`
Canceled bool `json:"canceled,omitempty"`
}
// CommandOutputData is a cumulative tail, so reconnect/replay needs no
// byte offsets and a missed update does not corrupt the displayed log.
type CommandOutputData struct {
ToolCallID string `json:"tool_call_id"`
Command string `json:"command"`
StartedAt time.Time `json:"started_at"`
Output string `json:"output"`
Done bool `json:"done"`
}

View File

@ -114,6 +114,7 @@ func (h *AgentStreamHandler) Subscribe() {
h.eventBus.On(event.EventAgentThought, h.handleThought)
h.eventBus.On(event.EventAgentToolCall, h.handleToolCall)
h.eventBus.On(event.EventAgentToolResult, h.handleToolResult)
h.eventBus.On(event.EventAgentCommandOutput, h.handleCommandOutput)
h.eventBus.On(event.EventAgentReferences, h.handleReferences)
h.eventBus.On(event.EventMemoryRecalled, h.handleMemoryRecalled)
h.eventBus.On(event.EventContextCompacted, h.handleContextCompacted)
@ -877,3 +878,19 @@ func publicArtifactViews(list types.MessageArtifacts) []map[string]interface{} {
}
return out
}
// handleCommandOutput forwards UI-only progress without adding partial output
// to the model conversation or completing the tool call.
func (h *AgentStreamHandler) handleCommandOutput(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.CommandOutputData)
if !ok || data.ToolCallID == "" {
return nil
}
return h.streamManager.AppendEvent(h.ctx, h.sessionID, h.assistantMessageID, interfaces.StreamEvent{
ID: evt.ID, Type: types.ResponseTypeCommandOutput, Timestamp: time.Now(),
Data: map[string]interface{}{
"tool_call_id": data.ToolCallID, "command": data.Command,
"started_at": data.StartedAt, "output": data.Output, "done": data.Done,
},
})
}

View File

@ -0,0 +1,39 @@
package session
import (
"context"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
func TestCommandOutputReachesChatStreamWithoutCompletingTool(t *testing.T) {
ctx := context.Background()
bus := event.NewEventBus()
streams := &completionEventRecorder{}
message := &types.Message{ID: "message"}
h := NewAgentStreamHandler(ctx, "session", "message", "request", 1, time.Now(), message, streams, bus, nil)
h.Subscribe()
for _, done := range []bool{false, true} {
require.NoError(t, bus.Emit(ctx, event.Event{
Type: event.EventAgentCommandOutput,
Data: event.CommandOutputData{
ToolCallID: "call-1", Command: "python analysis.py", Output: "reading CSV", Done: done,
},
}))
}
require.Len(t, streams.events, 2)
for _, e := range streams.events {
require.Equal(t, types.ResponseTypeCommandOutput, e.Type)
require.False(t, e.Done, "command progress is not a completed assistant turn")
frame := buildStreamResponse(e, "request")
require.Equal(t, "call-1", frame.Data["tool_call_id"])
require.Equal(t, "reading CSV", frame.Data["output"])
}
require.Equal(t, true, streams.events[1].Data["done"])
require.Empty(t, message.Content)
require.Empty(t, message.AgentSteps)
}

View File

@ -0,0 +1,19 @@
package sandbox
import "context"
type commandOutputKey struct{}
// WithCommandOutput observes the command executed with this context. It does
// not grant installer privileges or change the final command result.
func WithCommandOutput(ctx context.Context, callback func(string, []byte)) context.Context {
return context.WithValue(ctx, commandOutputKey{}, callback)
}
func commandOutputCallback(ctx context.Context, explicit func(string, []byte)) func(string, []byte) {
if explicit != nil {
return explicit
}
callback, _ := ctx.Value(commandOutputKey{}).(func(string, []byte))
return callback
}

View File

@ -692,7 +692,7 @@ func (c *DockerRemoteClient) Exec(
}
start := time.Now()
stdout, stderr, err := c.streamExec(execCtx, created.ID, req.Stdin)
stdout, stderr, err := c.streamExec(execCtx, created.ID, req.Stdin, req.OnOutput)
if err != nil {
return nil, err
}
@ -724,6 +724,7 @@ func (c *DockerRemoteClient) streamExec(
ctx context.Context,
execID string,
stdin string,
output ...func(string, []byte),
) (string, string, error) {
attached, err := c.api.ExecAttach(ctx, execID, client.ExecAttachOptions{})
if err != nil {
@ -753,7 +754,12 @@ func (c *DockerRemoteClient) streamExec(
var stdout, stderr bytes.Buffer
done := make(chan error, 1)
go func() {
_, copyErr := stdcopy.StdCopy(&stdout, &stderr, attached.Reader)
var out, errOut io.Writer = &stdout, &stderr
if len(output) > 0 && output[0] != nil {
out = io.MultiWriter(&stdout, remoteOutputWriter{stream: "stdout", callback: output[0]})
errOut = io.MultiWriter(&stderr, remoteOutputWriter{stream: "stderr", callback: output[0]})
}
_, copyErr := stdcopy.StdCopy(out, errOut, attached.Reader)
done <- copyErr
}()
@ -1288,3 +1294,11 @@ var (
_ RemoteSandboxClient = (*DockerRemoteClient)(nil)
_ RemoteSnapshotManager = (*DockerRemoteClient)(nil)
)
// remoteOutputWriter observes bytes without changing buffered exec results.
type remoteOutputWriter struct {
stream string
callback func(string, []byte)
}
func (w remoteOutputWriter) Write(p []byte) (int, error) { w.callback(w.stream, p); return len(p), nil }

View File

@ -1201,3 +1201,18 @@ func TestDockerSessionCreateRequestDeletesIdleSandboxes(t *testing.T) {
require.Equal(t, RemoteOnTimeoutKill, request.Timeout.Action,
"pausing a container keeps its memory on the host, so it reclaims nothing")
}
func TestDockerExecObservesBothOutputStreamsWithoutChangingResult(t *testing.T) {
engine := newFakeDockerEngine()
engine.execStdout = "download started\n"
engine.execStderr = "download progress\n"
docker := newTestDockerClient(t, engine)
observed := map[string]string{}
result, err := docker.Exec(context.Background(), testHandle("container-1"), RemoteExecRequest{
Command: "echo", Timeout: time.Second,
OnOutput: func(stream string, p []byte) { observed[stream] += string(p) },
})
require.NoError(t, err)
require.Equal(t, result.Stdout, observed["stdout"])
require.Equal(t, result.Stderr, observed["stderr"])
}

View File

@ -812,6 +812,10 @@ func (c *E2BRemoteClient) Exec(
start := time.Now()
options := []e2b.RunOption{}
if request.OnOutput != nil {
options = append(options, e2b.WithOnStdout(func(p []byte) { request.OnOutput("stdout", p) }),
e2b.WithOnStderr(func(p []byte) { request.OnOutput("stderr", p) }))
}
if request.WorkDir != "" {
options = append(options, e2b.WithCwd(request.WorkDir))
}

View File

@ -297,6 +297,10 @@ type RemoteListFilter struct {
// RemoteExecRequest describes a single command invocation. See the
// RemoteSandboxClient.Exec contract for how Shell interacts with Args.
type RemoteExecRequest struct {
// OnOutput receives stdout/stderr chunks while the command runs. It is an
// observation hook only; callers must not retain the supplied bytes.
OnOutput func(stream string, chunk []byte) `json:"-"`
// Command is the executable name (Shell=false) or the shell expression
// (Shell=true).
Command string

View File

@ -685,6 +685,8 @@ func (m *SessionBoundManager) WriteSessionFile(
// flags select the installer working-directory allowlist and bootstrap. Both
// ordinary and install calls currently execute as root.
type ShellExecOptions struct {
OnOutput func(stream string, chunk []byte)
WorkDir string
Timeout time.Duration
Env map[string]string
@ -776,12 +778,13 @@ func (m *SessionBoundManager) ExecShellCommandWithOptions(
start := time.Now()
execResult, execErr := m.client.Exec(ctx, handle, RemoteExecRequest{
Command: command,
Shell: true,
Env: opts.Env,
WorkDir: workDir,
User: user,
Timeout: timeout,
Command: command,
OnOutput: commandOutputCallback(ctx, opts.OnOutput),
Shell: true,
Env: opts.Env,
WorkDir: workDir,
User: user,
Timeout: timeout,
})
duration := time.Since(start)
return remoteExecuteResult(execResult, execErr, duration), nil

View File

@ -221,6 +221,10 @@ const (
ResponseTypeToolCall ResponseType = "tool_call"
// Tool result response type (for agent tool results)
ResponseTypeToolResult ResponseType = "tool_result"
// ResponseTypeInstallOutput carries installer progress without completing a tool.
ResponseTypeInstallOutput ResponseType = "install_output"
// ResponseTypeCommandOutput updates the pending tool card without completing it.
ResponseTypeCommandOutput ResponseType = "command_output"
// Error response type
ResponseTypeError ResponseType = "error"
// Reflection response type (for agent reflection)