feat(agentexec): record each agent run's transcript and show it per step (#1718)

The loop runner hooks every model call and tool call and reports ordered,
redacted, clipped entries. Each is persisted as an agent_transcript task
event through InsertEvent, left out of the timeline read, and served per
attempt at /api/tasks/{id}/transcript. The step run view shows it with Trace.
This commit is contained in:
sam committed 2026-11-01 22:09:53 +11:00
1 parent d6ca6a72a5
commit 6f10ecc04f
35 files changed
+791 -68

No files matched your search

+1 -1
View File
@@ -52,7 +52,7 @@ type HarnessStages struct {
Spec agentrun.HarnessSpec
}
func (r HarnessStages) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.ToolCallReporter) (agentrun.Result, error) {
func (r HarnessStages) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.Reporter) (agentrun.Result, error) {
spec := r.Spec
req.Harness = &spec
return r.Runner.Run(ctx, workspace, req, report)
+1 -1
View File
@@ -34,7 +34,7 @@ func TestHarnessRequiresMCPInitialization(t *testing.T) {
if !central {
req.CaptureTools = []agentrun.CaptureTool{{Name: "capture_result", Parameters: json.RawMessage(`{"type":"object"}`)}}
}
result, err := NewHarnessRunner(nil).Run(t.Context(), workspace, req, nil)
result, err := NewHarnessRunner(nil).Run(t.Context(), workspace, req, agentrun.Reporter{})
if err != nil {
t.Fatal(err)
}
+7 -9
View File
@@ -28,7 +28,7 @@ func newClaudeCodeHarnessOutput() *claudeCodeHarnessOutput {
}
}
func (o *claudeCodeHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
func (o *claudeCodeHarnessOutput) Line(line []byte, report agentrun.Reporter) {
var event struct {
Type string `json:"type"`
SessionID string `json:"session_id"`
@@ -55,7 +55,7 @@ func (o *claudeCodeHarnessOutput) Line(line []byte, report agentrun.ToolCallRepo
}
}
func (o *claudeCodeHarnessOutput) assistant(raw json.RawMessage, _ agentrun.ToolCallReporter) {
func (o *claudeCodeHarnessOutput) assistant(raw json.RawMessage, _ agentrun.Reporter) {
var message struct {
ID string `json:"id"`
Usage json.RawMessage `json:"usage"`
@@ -79,7 +79,7 @@ func (o *claudeCodeHarnessOutput) assistant(raw json.RawMessage, _ agentrun.Tool
}
}
func (o *claudeCodeHarnessOutput) user(raw json.RawMessage, report agentrun.ToolCallReporter) {
func (o *claudeCodeHarnessOutput) user(raw json.RawMessage, report agentrun.Reporter) {
var message struct {
Content []struct {
Type string `json:"type"`
@@ -100,12 +100,10 @@ func (o *claudeCodeHarnessOutput) user(raw json.RawMessage, report agentrun.Tool
continue
}
delete(o.pending, block.ToolUseID)
if report != nil {
report(agentrun.ToolCallReport{
Tool: tool, Detail: ClipToolCallDetail(claudeResultContent(block.Content)),
Failed: block.IsError,
})
}
report.ReportToolCall(agentrun.ToolCallReport{
Tool: tool, Detail: ClipToolCallDetail(claudeResultContent(block.Content)),
Failed: block.IsError,
})
}
}
+3 -3
View File
@@ -15,7 +15,7 @@ type codexHarnessOutput struct {
usage agentrun.Usage
}
func (o *codexHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
func (o *codexHarnessOutput) Line(line []byte, report agentrun.Reporter) {
var event struct {
Type string `json:"type"`
ThreadID string `json:"thread_id"`
@@ -43,8 +43,8 @@ func (o *codexHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter)
})
}
case "item.completed":
if call, ok := event.Item.report(); ok && report != nil {
report(call)
if call, ok := event.Item.report(); ok {
report.ReportToolCall(call)
}
}
}
+2 -4
View File
@@ -18,7 +18,7 @@ func newCopilotHarnessOutput() *copilotHarnessOutput {
return &copilotHarnessOutput{pending: make(map[string]string)}
}
func (o *copilotHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
func (o *copilotHarnessOutput) Line(line []byte, report agentrun.Reporter) {
var event struct {
Type string `json:"type"`
SessionID string `json:"sessionId"`
@@ -52,9 +52,7 @@ func (o *copilotHarnessOutput) Line(line []byte, report agentrun.ToolCallReporte
return
}
delete(o.pending, event.Data.ToolCallID)
if report != nil {
report(agentrun.ToolCallReport{Tool: tool, Detail: ClipToolCallDetail(event.Data.Result.Content), Failed: !event.Data.Success})
}
report.ReportToolCall(agentrun.ToolCallReport{Tool: tool, Detail: ClipToolCallDetail(event.Data.Result.Content), Failed: !event.Data.Success})
}
}
+3 -3
View File
@@ -15,7 +15,7 @@ type piHarnessOutput struct {
usage agentrun.Usage
}
func (o *piHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
func (o *piHarnessOutput) Line(line []byte, report agentrun.Reporter) {
var event struct {
Type string `json:"type"`
ID string `json:"id"`
@@ -49,7 +49,7 @@ func (o *piHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
o.usage = addUsage(o.usage, usageFromFields(u.Input, u.Output, u.CacheRead, u.CacheWrite))
}
case "tool_execution_end":
if event.ToolName == "" || report == nil {
if event.ToolName == "" {
return
}
texts := make([]string, 0, len(event.Result.Content))
@@ -58,7 +58,7 @@ func (o *piHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
texts = append(texts, block.Text)
}
}
report(agentrun.ToolCallReport{Tool: event.ToolName, Detail: ClipToolCallDetail(strings.Join(texts, "\n")), Failed: event.IsError})
report.ReportToolCall(agentrun.ToolCallReport{Tool: event.ToolName, Detail: ClipToolCallDetail(strings.Join(texts, "\n")), Failed: event.IsError})
}
}
+7 -7
View File
@@ -45,7 +45,7 @@ const (
// knows its CLI's stream format; it reports tool calls as they complete and
// the session to resume.
type HarnessOutput interface {
Line(line []byte, report agentrun.ToolCallReporter)
Line(line []byte, report agentrun.Reporter)
SessionID() string
Usage() agentrun.Usage
}
@@ -67,7 +67,7 @@ func NewHarnessRunner(newOutput func() HarnessOutput) *HarnessRunner {
return &HarnessRunner{newOutput: newOutput}
}
func (r *HarnessRunner) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.ToolCallReporter) (agentrun.Result, error) {
func (r *HarnessRunner) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.Reporter) (agentrun.Result, error) {
if err := validateHarness(req); err != nil {
return agentrun.Result{}, err
}
@@ -95,7 +95,7 @@ func (r *HarnessRunner) Run(ctx context.Context, workspace string, req agentrun.
return res, err
}
func (r *HarnessRunner) run(ctx context.Context, workspace string, req agentrun.Request, mcpConfig string, report agentrun.ToolCallReporter) (agentrun.Result, error) {
func (r *HarnessRunner) run(ctx context.Context, workspace string, req agentrun.Request, mcpConfig string, report agentrun.Reporter) (agentrun.Result, error) {
res := agentrun.Result{Version: agentrun.ProtocolVersion, TaskID: req.TaskID, Attempt: req.Attempt, Stage: req.Stage}
before, err := snapshotRepo(workspace)
if err != nil {
@@ -244,7 +244,7 @@ func resumeVerb(h *agentrun.HarnessSpec, sessionID string) []string {
// invoke runs one harness invocation in its own process group, feeding
// stdout to out line by line. Cancelling ctx kills the whole group, so a
// CLI's children cannot outlive the step.
func invoke(ctx context.Context, workspace string, h *agentrun.HarnessSpec, argv []string, out HarnessOutput, report agentrun.ToolCallReporter) error {
func invoke(ctx context.Context, workspace string, h *agentrun.HarnessSpec, argv []string, out HarnessOutput, report agentrun.Reporter) error {
cmd := exec.CommandContext(ctx, argv[0], argv[1:]...)
cmd.Dir = workspace
cmd.WaitDelay = killGrace
@@ -467,9 +467,9 @@ func policyViolation(before, after repoState, changes []string, req agentrun.Req
type silentOutput struct{}
func (silentOutput) Line([]byte, agentrun.ToolCallReporter) {}
func (silentOutput) SessionID() string { return "" }
func (silentOutput) Usage() agentrun.Usage { return agentrun.Usage{} }
func (silentOutput) Line([]byte, agentrun.Reporter) {}
func (silentOutput) SessionID() string { return "" }
func (silentOutput) Usage() agentrun.Usage { return agentrun.Usage{} }
// tailBuffer keeps the last stderrTailBytes written to it.
type tailBuffer struct{ buf bytes.Buffer }
+1 -1
View File
@@ -18,7 +18,7 @@ func TestHarnessLiveOutput(t *testing.T) {
if os.Geteuid() == 0 {
user = "65534"
}
err := invoke(t.Context(), "/tmp", &agentrun.HarnessSpec{User: user}, []string{"sh", "-c", `printf '%s\n' '{"type":"thread.started","thread_id":"live-thread"}'; printf '%s\n' 'live diagnostic' >&2`}, adapter, nil)
err := invoke(t.Context(), "/tmp", &agentrun.HarnessSpec{User: user}, []string{"sh", "-c", `printf '%s\n' '{"type":"thread.started","thread_id":"live-thread"}'; printf '%s\n' 'live diagnostic' >&2`}, adapter, agentrun.Reporter{})
if err != nil {
t.Fatal(err)
}
+11 -3
View File
@@ -53,7 +53,7 @@ func NewLoopRunner(
// work on the chat workspace and bypass ReadOnly and ProtectPaths.
const workspaceToolset = "workspace"
func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.ToolCallReporter) (agentrun.Result, error) {
func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.Reporter) (agentrun.Result, error) {
if err := req.Validate(); err != nil {
return agentrun.Result{}, err
}
@@ -67,12 +67,18 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Req
notes := &memoryNotes{initial: req.Notes}
captures := make(map[string][]json.RawMessage)
toolOpts := r.Limits.Options(workspaceToolset)
toolOpts.OnToolCall = report
toolOpts.OnToolCall = report.ToolCall
centralTools, err := BuildToolSet(r.tools, toolOpts)
if err != nil {
return agentrun.Result{}, fmt.Errorf("build central tool set: %w", err)
}
captureTools := captureToolSet(req.CaptureTools, captures)
var modelHooks []core.ModelHook
var toolHooks []core.ToolHook
if report.Transcript != nil {
recorder := newTranscript(report.Transcript)
modelHooks, toolHooks = []core.ModelHook{recorder}, []core.ToolHook{recorder}
}
res, err := r.run(ctx, agentloop.Config{
Runtime: r.runtime,
ModelRef: req.Model,
@@ -101,7 +107,9 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Req
allowedTools(centralTools, r.AllowTools),
captureTools,
),
Logger: r.logger(req),
ModelHooks: modelHooks,
ToolHooks: toolHooks,
Logger: r.logger(req),
})
result := resultFromRun(req, res, notes.appended, captures)
if cause := context.Cause(ctx); cause != nil {
+1 -1
View File
@@ -74,7 +74,7 @@ type ToolSetOptions struct {
// OnToolCall, when non-nil, is notified once per completed tool call.
// LoopRunner populates it so a workflow stage can surface tool activity on
// the task timeline. Nil means no one is listening.
OnToolCall agentrun.ToolCallReporter
OnToolCall func(agentrun.ToolCallReport)
}
// reportToolCallCompletion notifies opts.OnToolCall, if set, of one
+176
View File
@@ -0,0 +1,176 @@
package modelloop
import (
"context"
"encoding/json"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/archie-core/internal/domain/agentrun"
"github.com/samcharles93/archie-core/internal/webhookguard"
)
// transcriptFieldLimit caps each recorded text field, in bytes.
const transcriptFieldLimit = 32 << 10
// compactionPrefix starts the instruction agentloop sends to summarise the
// history, which marks a model call as a compaction rather than a step.
const compactionPrefix = "Compact the conversation history above"
// transcript records one agent run's conversation through agentloop's model
// and tool hooks. Tool hooks run concurrently, so entries are numbered and
// reported under one lock to keep their order.
type transcript struct {
report func(agentrun.TranscriptEntry)
mu sync.Mutex
seq int
prompted bool
lastUser string
started map[string]time.Time
}
func newTranscript(report func(agentrun.TranscriptEntry)) *transcript {
return &transcript{report: report, started: map[string]time.Time{}}
}
func (t *transcript) add(entry agentrun.TranscriptEntry) {
t.seq++
entry.Seq = t.seq
t.report(entry)
}
func (t *transcript) ModelCallStarted(context.Context, chat.Request) {}
func (t *transcript) ModelCallFinished(_ context.Context, req chat.Request, resp *chat.Response, err error, latency time.Duration, usage *chat.Usage) {
t.mu.Lock()
defer t.mu.Unlock()
entry := agentrun.TranscriptEntry{Kind: agentrun.TranscriptModel, LatencyMS: latency.Milliseconds(), Usage: transcriptUsage(usage)}
if isCompaction(req) {
entry.Kind = agentrun.TranscriptCompaction
} else {
t.recordInput(req.Messages)
}
if err != nil {
entry.Error = clip(err.Error(), nil)
}
if resp != nil {
entry.Text = clip(resp.Content, &entry.TextBytes)
entry.FinishReason = resp.FinishReason
for _, call := range resp.ToolCalls {
recorded := agentrun.TranscriptToolCall{ID: call.ID, Name: call.Name}
recorded.Args = clipArgs(call.Arguments, &recorded.ArgsBytes)
entry.ToolCalls = append(entry.ToolCalls, recorded)
}
}
t.add(entry)
}
// recordInput records the prompt on the first call, and after that each user
// message the loop appended since the model last answered: gate feedback,
// recovery nudges. Assistant and tool messages are recorded from the response
// and the tool hooks instead.
func (t *transcript) recordInput(messages []chat.Message) {
if !t.prompted {
t.prompted = true
for _, message := range messages {
t.recordMessage(message)
}
return
}
start := len(messages)
for start > 0 && messages[start-1].Role == chat.RoleUser {
start--
}
for _, message := range messages[start:] {
if message.Content != t.lastUser {
t.recordMessage(message)
}
}
}
func (t *transcript) recordMessage(message chat.Message) {
kind := agentrun.TranscriptUser
switch message.Role {
case chat.RoleSystem:
kind = agentrun.TranscriptSystem
case chat.RoleUser:
t.lastUser = message.Content
default:
return
}
entry := agentrun.TranscriptEntry{Kind: kind}
entry.Text = clip(message.Content, &entry.TextBytes)
t.add(entry)
}
func (t *transcript) BeforeToolExecute(_ context.Context, call *core.ToolCall) (*core.Skip, error) {
t.mu.Lock()
t.started[call.ToolCallID] = time.Now()
t.mu.Unlock()
return nil, nil
}
func (t *transcript) AfterToolExecute(_ context.Context, call core.ToolCall, result *core.ToolResult) {
t.mu.Lock()
defer t.mu.Unlock()
entry := agentrun.TranscriptEntry{Kind: agentrun.TranscriptTool, CallID: call.ToolCallID, Tool: call.ToolName}
if started, ok := t.started[call.ToolCallID]; ok {
entry.LatencyMS = time.Since(started).Milliseconds()
delete(t.started, call.ToolCallID)
}
entry.Args = clipArgs(call.Input, &entry.ArgsBytes)
entry.Output = clip(result.Output, &entry.OutputBytes)
entry.Error = clip(result.Error, nil)
t.add(entry)
}
func isCompaction(req chat.Request) bool {
n := len(req.Messages)
return n > 0 && req.Messages[n-1].Role == chat.RoleUser && strings.HasPrefix(req.Messages[n-1].Content, compactionPrefix)
}
func transcriptUsage(usage *chat.Usage) *agentrun.Usage {
if usage == nil {
return nil
}
return &agentrun.Usage{
PromptTokens: usage.PromptTokens,
CompletionTokens: usage.CompletionTokens,
TotalTokens: usage.TotalTokens,
CachedTokens: usage.CachedTokens,
CacheCreationTokens: usage.CacheCreationTokens,
}
}
// clipArgs redacts tool arguments by key when they are JSON, then clips them.
func clipArgs(args string, full *int) string {
if json.Valid([]byte(args)) {
if redacted, err := webhookguard.RedactPayload([]byte(args)); err == nil {
args = string(redacted)
}
}
return clip(args, full)
}
// clip redacts secret-shaped spans and cuts text to transcriptFieldLimit on a
// rune boundary, storing the original size in full when it cuts.
func clip(text string, full *int) string {
text = webhookguard.RedactText(text)
if len(text) <= transcriptFieldLimit {
return text
}
if full != nil {
*full = len(text)
}
cut := transcriptFieldLimit
for cut > 0 && !utf8.RuneStart(text[cut]) {
cut--
}
return text[:cut]
}
@@ -0,0 +1,71 @@
package modelloop
import (
"strings"
"testing"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/archie-core/internal/domain/agentrun"
)
func TestTranscriptToolEntryRedactsAndClips(t *testing.T) {
const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhcmNoaWUifQ.c2lnbmF0dXJlc2lnbmF0dXJl"
const pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIEow\n-----END RSA PRIVATE KEY-----"
long := strings.Repeat("x", transcriptFieldLimit+10)
tests := []struct {
name string
input string
output string
wantArgs string
wantOutput string
wantBytes int
}{
{
name: "secret key in arguments, token inside output",
input: `{"path":"a.txt","api_key":"plain-value"}`,
output: "curl -H 'Authorization: Bearer " + jwt + "' done",
wantArgs: `{"api_key":"[redacted]","path":"a.txt"}`,
wantOutput: "curl -H 'Authorization: Bearer [redacted]' done",
},
{
name: "private key block inside output",
input: `{}`,
output: "before\n" + pem + "\nafter",
wantArgs: `{}`,
wantOutput: "before\n[redacted]\nafter",
},
{
name: "oversized output keeps its full size",
input: `{}`,
output: long,
wantArgs: `{}`,
wantOutput: long[:transcriptFieldLimit],
wantBytes: len(long),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got []agentrun.TranscriptEntry
recorder := newTranscript(func(entry agentrun.TranscriptEntry) { got = append(got, entry) })
call := core.ToolCall{ToolCallID: "c1", ToolName: "shell", Input: tt.input}
if _, err := recorder.BeforeToolExecute(t.Context(), &call); err != nil {
t.Fatal(err)
}
recorder.AfterToolExecute(t.Context(), call, &core.ToolResult{Output: tt.output})
if len(got) != 1 {
t.Fatalf("entries = %d, want 1", len(got))
}
entry := got[0]
if entry.Args != tt.wantArgs {
t.Errorf("args = %q, want %q", entry.Args, tt.wantArgs)
}
if entry.Output != tt.wantOutput {
t.Errorf("output = %q, want %q", entry.Output, tt.wantOutput)
}
if entry.OutputBytes != tt.wantBytes {
t.Errorf("output bytes = %d, want %d", entry.OutputBytes, tt.wantBytes)
}
})
}
}