Files
thotam ce9e7af3fb fix(tools): price out-of-band media by measured duration, not by its bytes (#1564)
read_video called with a url parameter always failed under an agent budget:

    tool:read_video: cannot verify streamed native media against the agent
    context budget (no in-memory payload to count); refusing to send

read_audio and read_document appeared to work but only for very small files.
Both symptoms share one root cause.

5ca433b8 introduced the complete-input invariant and, to keep out-of-band
media honest, appended the standard-base64 encoding of the payload as a
synthetic guard-only message. That message is counted as text. Measured against
the bundled BudgetCounter, base64 costs 0.956 tokens per raw byte, so an 11.6 MB
video counted 11,161,058 tokens and exceeded a 200k, a 1M and a 2M window alike.
The practical ceiling was roughly 200 KB at a 200k window while videoMaxBytes is
100 MB. The read_video URL transport streams to the File API without buffering,
so it had no bytes to count at all and was routed to a helper that refused to
send whenever an agent budget was present.

Media is now priced by what a provider actually bills for it. Every number below
is either a published per-unit rate or a published provider limit; none is
derived from a byte size, because a static-image video compresses arbitrarily
small and no bitrate floor exists. An earlier revision of this branch tried one
and a 120-second, 20,627-byte clip priced at 526 tokens against a true 31,560.

  internal/mediabudget prices one payload:
  - Video and audio: ffprobe measures duration. 263 tokens/second for video,
    32 for audio, both published for static processing at 1 FPS.
  - PDF: pdfinfo counts pages at 258 tokens/page. When the page count cannot be
    read, the charge is the proven ceiling of 1000 pages, which is the most a
    provider will accept and therefore the most it can bill.
  - Video and audio that cannot be measured are refused. Upstream already
    refused unverifiable native media for every URL on the Gemini streamed path;
    this narrows that refusal from every URL to only what genuinely cannot be
    measured, rather than removing it. PDF differs because its page count is
    cheaply measurable and its ceiling is small enough to stay usable.

A remote video is measured without downloading it: two ranged GETs, 512 KB from
the head and 512 KB from the tail, written into a sparse temp file sized to the
declared total and handed to ffprobe. The tail matters because every container
that puts its index at the end keeps it there: head-only probing under-reports
mpeg by 98% and ogg by 79%, and a plain prefix makes ffprobe under-report a
30-second WAV as 0.74 seconds because it clamps to the bytes it can see. Sizing
the temp file to the real total fixes that. Verified end to end on an 11,673,105
byte MP4 served by nginx: 1 MB of ranged reads yielded duration 40.000000,
identical to ffprobe reading the whole URL, for a charge of 10,520 tokens. Those
requests reuse the existing SSRF-safe path, security.WithPinnedIP plus
security.NewSafeClient(0), and no URL is ever handed to an external binary.

Beyond the reported bug, two pre-existing gaps let large media reach a provider
almost unpriced. ExecuteWithChain treated every callProvider error as a provider
failure and advanced to the next entry, and the non-Gemini branches of read_video
and read_document reserved without pricing their payload at all. Measured under a
20,000-token window before this change, a 40 MB video and a 1000-page PDF each
reached a provider charged about 1,600 tokens. Budget refusals are now terminal
in the chain and every media branch prices its payload, so both reach no provider
at all. Genuine provider failures still fail over.

Known limits, stated rather than discovered:
- The /Type /Page scan that guards against a forged /Count is a floor, not a
  bound. Pages inside a compressed object stream are invisible to it, and a
  9,484-byte PDF built that way is charged 258 tokens for 1000 pages. A real
  pdfinfo reads such files correctly; the scan only ever raises a probed count.
- A video URL whose origin does not serve byte ranges is now refused on the
  non-Gemini path too, and the refusal is terminal. Upstream forwarded such URLs
  unpriced. A HEAD giving only a size is not enough to price one.
- read_video and read_audio require ffprobe. Docker images install it by default
  except the base variant; bare binaries and the desktop build do not ship it.
- A hostile origin can craft a container ffprobe reads as about one second.
  Reservation.Reconcile overwrites the estimate with the provider's reported
  usage, so this weakens the gate rather than defeating it.

Byte ceilings videoMaxBytes, audioMaxBytes and documentMaxBytes are unchanged.
No new module dependency; ffprobe and pdfinfo are optional runtime probes.
2026-09-12 10:31:12 +07:00

234 lines
7.3 KiB
Go

package tools
import (
"context"
"fmt"
"io"
"log/slog"
"net"
"os"
"path/filepath"
"strings"
"time"
"github.com/nextlevelbuilder/goclaw/internal/providers"
"github.com/nextlevelbuilder/goclaw/internal/security"
usagecaps "github.com/nextlevelbuilder/goclaw/internal/usage/caps"
)
// --- Context helpers for media video ---
const ctxMediaVideoRefs toolContextKey = "tool_media_video_refs"
// WithMediaVideoRefs stores video MediaRefs in context for read_video tool access.
func WithMediaVideoRefs(ctx context.Context, refs []providers.MediaRef) context.Context {
return context.WithValue(ctx, ctxMediaVideoRefs, refs)
}
// MediaVideoRefsFromCtx retrieves stored video MediaRefs from context.
func MediaVideoRefsFromCtx(ctx context.Context) []providers.MediaRef {
v, _ := ctx.Value(ctxMediaVideoRefs).([]providers.MediaRef)
return v
}
// --- ReadVideoTool ---
// videoMaxBytes is the max file size for video analysis (100MB).
const videoMaxBytes = 100 * 1024 * 1024
const videoURLPinnedIPParam = "_pinned_ip"
// videoLocalPathParam forwards the resolved local file path so the budget probe can read the real file.
const videoLocalPathParam = "_local_path"
// videoProviderPriority is the order in which providers are tried for video analysis.
// OpenAI excluded — no native video upload in chat completions.
var videoProviderPriority = []string{"gemini", "openrouter"}
// videoModelDefaults maps provider names to preferred video-capable models.
var videoModelDefaults = map[string]string{
"gemini": "gemini-2.5-flash",
"openrouter": "google/gemini-2.5-flash",
}
// ReadVideoTool uses a video-capable provider to analyze video files
// attached to the current conversation.
type ReadVideoTool struct {
registry *providers.Registry
mediaLoader MediaPathLoader
usageCaps *usagecaps.Service
// streamToGemini is injected per instance rather than through a package
// global, so parallel tests cannot race each other over one seam.
streamToGemini geminiStreamFn
}
// geminiStreamFn is the upload a gate-passing URL is handed to.
type geminiStreamFn func(ctx context.Context, apiKey, model, prompt string, reader io.Reader, contentLength int64, mime string, httpTimeout time.Duration) (*providers.ChatResponse, error)
func NewReadVideoTool(registry *providers.Registry, mediaLoader MediaPathLoader) *ReadVideoTool {
return &ReadVideoTool{registry: registry, mediaLoader: mediaLoader, streamToGemini: geminiFileAPICallStream}
}
// setStreamToGeminiForTest observes what reaches the upload without contacting a provider.
func (t *ReadVideoTool) setStreamToGeminiForTest(fn geminiStreamFn) {
t.streamToGemini = fn
}
func (t *ReadVideoTool) SetUsageCapService(svc *usagecaps.Service) {
t.usageCaps = svc
}
func (t *ReadVideoTool) Name() string { return "read_video" }
func (t *ReadVideoTool) Description() string {
return "Analyze video files attached to the conversation. " +
"Use when you see <media:video> tags and need to describe, summarize, or analyze video content. " +
"A workspace-relative path such as inputs/clip.mp4 may also be provided. Specify what you want to extract or analyze."
}
func (t *ReadVideoTool) Parameters() map[string]any {
return map[string]any{
"type": "object",
"properties": map[string]any{
"prompt": map[string]any{
"type": "string",
"description": "What to analyze. E.g. 'Describe what happens in this video', 'Summarize the key scenes', 'What text appears on screen?'",
},
"media_id": map[string]any{
"type": "string",
"description": "Optional: specific media_id from <media:video> tag. If omitted, uses most recent video.",
},
"url": map[string]any{
"type": "string",
"description": "Optional URL to a video file. Use this to analyze videos hosted online.",
},
"path": map[string]any{
"type": "string",
"description": "Optional workspace-relative video path. Delegated inputs use inputs/<name>.",
},
},
"required": []string{"prompt"},
}
}
func (t *ReadVideoTool) Execute(ctx context.Context, args map[string]any) *Result {
prompt, _ := args["prompt"].(string)
if prompt == "" {
prompt = "Analyze this video and describe its contents."
}
mediaID, _ := args["media_id"].(string)
videoURL, _ := args["url"].(string)
videoArg, _ := args["path"].(string)
sourceCount := 0
for _, source := range []string{mediaID, videoURL, videoArg} {
if source != "" {
sourceCount++
}
}
if sourceCount > 1 {
if videoArg == "" && mediaID != "" && videoURL != "" {
return ErrorResult("Both 'media_id' and 'url' parameters cannot be specified. Choose only one.")
}
return ErrorResult("Only one of 'media_id', 'url', or 'path' may be specified.")
}
var data []byte
var videoMime string
var videoPath string
var pinnedIP net.IP
if videoURL != "" {
validatedURL, validatedIP, err := security.Validate(videoURL)
if err != nil {
return ErrorResult(fmt.Sprintf("Invalid video URL: %v", err))
}
pinnedIP = validatedIP
// Infer MIME type from URL extension
ext := filepath.Ext(validatedURL.Path)
videoMime = mimeFromVideoExt(ext)
} else {
var mime string
var err error
if videoArg != "" {
videoPath, err = resolveStructuredMediaPath(ctx, videoArg, "video")
mime = mimeFromVideoExt(filepath.Ext(videoPath))
} else {
videoPath, mime, err = t.resolveVideoFile(ctx, mediaID)
}
if err != nil {
return ErrorResult(err.Error())
}
videoMime = mime
slog.Info("read_video: resolved file", "mime", videoMime, "media_id", mediaID, "logical_path", videoArg)
fileData, err := os.ReadFile(videoPath)
if err != nil {
if videoArg != "" && IsDelegationArtifactRun(ctx) {
return ErrorResult("Failed to read delegation video input")
}
return ErrorResult(fmt.Sprintf("Failed to read video file: %v", err))
}
slog.Info("read_video: file loaded", "size_bytes", len(fileData))
if len(fileData) > videoMaxBytes {
return ErrorResult(fmt.Sprintf("Video too large: %d bytes (max %d)", len(fileData), videoMaxBytes))
}
data = fileData
}
chain := ResolveMediaProviderChain(ctx, "read_video", "", "",
videoProviderPriority, videoModelDefaults, t.registry)
for i := range chain {
if chain[i].Params == nil {
chain[i].Params = make(map[string]any)
}
chain[i].Params["prompt"] = prompt
chain[i].Params["data"] = data
chain[i].Params["url"] = videoURL
chain[i].Params["mime"] = videoMime
chain[i].Params[videoLocalPathParam] = videoPath
if pinnedIP != nil {
chain[i].Params[videoURLPinnedIPParam] = pinnedIP
}
}
chainResult, err := ExecuteWithChain(ctx, chain, t.registry, t.callProvider)
if err != nil {
return ErrorResult(fmt.Sprintf("Video analysis failed: %v", err))
}
result := NewResult(string(chainResult.Data))
result.Usage = chainResult.Usage
result.Provider = chainResult.Provider
result.Model = chainResult.Model
return result
}
// mimeFromVideoExt returns MIME type for video file extensions.
func mimeFromVideoExt(ext string) string {
switch strings.ToLower(ext) {
case ".mp4":
return "video/mp4"
case ".webm":
return "video/webm"
case ".mov":
return "video/quicktime"
case ".avi":
return "video/x-msvideo"
case ".mkv":
return "video/x-matroska"
case ".wmv":
return "video/x-ms-wmv"
case ".flv":
return "video/x-flv"
case ".3gp":
return "video/3gpp"
case ".mpeg", ".mpg":
return "video/mpeg"
default:
return "video/mp4"
}
}