diff --git a/pkgs/mcpx/docs/compare/register/code-mode.md b/pkgs/mcpx/docs/compare/register/code-mode.md index 9e22fa7098..527e826033 100644 --- a/pkgs/mcpx/docs/compare/register/code-mode.md +++ b/pkgs/mcpx/docs/compare/register/code-mode.md @@ -38,7 +38,7 @@ Status column: **mcpx @ 05c78b2**. Legend and citation conventions: [../README.m | CODE-13 | Progress token requested so long calls outlive the timeout | `opencode v1 has` `opencode v2 has` `mcpx missing` | v1 token and reset · v2 token, no reset · lootbox, mcpx none | partial — sends a token when the host did and relays progress (#212); the daemon's own timeout does not reset on it | + med | S | med | | CODE-14 | CPU-time and subrequest caps per invocation | `does not match mcpx's goal` | CF `cpuMs`, `subRequests` · others wall clock only | n/a — wall clock only | − marginal | M | low | | CODE-15 | Tool-call budget per execution | `opencode v1 has` `opencode v2 has` | v1/v2 knob, unset by host · lootbox, mcpx, CF none | ✗ — only the timeout bounds a looping script | + low | S | low | -| CODE-16 | Cap on the size of returned output | `opencode v1 has` `opencode v2 has` `mcpx missing` | v1/v2 knob · CF 6,000 tokens · lootbox, mcpx whole stdout | ✗ — stdout returned whole; only stderr is bounded (#216) | + high | S | med | +| CODE-16 | Cap on the size of returned output | `opencode v1 has` `opencode v2 has` `mcpx has` | v1/v2 knob · CF 6,000 tokens · lootbox whole stdout, mcpx capped at `exec.maxOutputBytes` | ✓ — returned stdout capped at the execsvc Result boundary (default 64KiB): head kept, in-band marker names dropped bytes, `stdoutTruncated` set; full record unchanged (#1937) | + high | S | med | | CODE-17 | Concurrent tool calls within one program | `opencode v1 has` | v1 8 · v2 unrestricted · lootbox, mcpx, CF no cap | n/a — per-server pool max 4, no per-run cap | + low | S | low | | CODE-18 | Upstream call cancelled when the script times out or dies | `has better replacement` | mcpx ✓ · v1/v2 ✓ · lootbox ✗ · CF unverified | ✓ — context cancel sends `notifications/cancelled` | + low | S | low | | CODE-19 | Final top-level expression becomes the result | `opencode v2 has` `mcpx missing` | v2 ✓ · CF ✓ · v1 `null` · lootbox none · mcpx stdout | ✗ — result is stdout, `emit()` or a default export (#216) | + med | M | low | @@ -441,6 +441,7 @@ Status column: **mcpx @ 05c78b2**. Legend and citation conventions: [../README.m the whole envelope; plugin-API register, PLG-40), floods the caller's context, which is exactly what code mode exists to prevent. - **Effort.** S — an `exec.maxOutputBytes` setting that truncates with a marker and sets `truncated`. +- **As built (#1937, 2026-10-31).** Landed as specified: setting `exec.maxOutputBytes` (KindBytes, default `64KiB`, defaults.json `exec.stdoutLimit` following the `stderrLimit` pattern), wired into `execsvc.Limits.StdoutLimit` by both the daemon (`/v1/exec`) and the CLI local path. The cap is applied once, at the end of `execsvc.Service.Run` where the `Result` is handed back, so every returning surface sees the same capped `Stdout`: the head is kept (UTF-8-boundary safe), the returned string never exceeds the cap, it ends with a marker naming kept/total/dropped bytes, and `Result.StdoutTruncated` (`stdoutTruncated`) is set. Internal consumers (the JSON answer parse, hooks) still see the full text, and the full output is unchanged wherever a full record already exists. 0 disables the cap. Tests: `internal/execsvc/stdout_limit_test.go` (over-cap capped+marker, under-cap and exact-cap byte-identical, 0 disables, UTF-8 boundary). - **Risk.** Without it, one chatty script can cost more tokens than the direct call it replaced. - **Detail.** v1's README tells hosts without their own truncation to set it, "or oversized results silently flood model context" (`v1:packages/codemode/README.md:268`). v2 gives warnings a separate budget equal to `maxOutputBytes` diff --git a/pkgs/mcpx/docs/configuration.md b/pkgs/mcpx/docs/configuration.md index 66710db6f0..f2cc11ae44 100644 --- a/pkgs/mcpx/docs/configuration.md +++ b/pkgs/mcpx/docs/configuration.md @@ -411,6 +411,7 @@ and a switch to turn the report off would have kept it quiet. | setting | kind | default | scope | hot | flag | variable | governs | | --- | --- | --- | --- | --- | --- | --- | --- | +| `exec.maxOutputBytes` | bytes | `64KiB` | call | yes | `--exec-max-output-bytes` | `MCPX_EXEC_MAX_OUTPUT_BYTES` | cap the stdout a run returns, with a truncation marker | | `exec.output` | enum | `text` | call | yes | `--exec-output`, `--output` | `MCPX_EXEC_OUTPUT` | text for a terminal, structured for one document, stream for frames | | `exec.timeout` | duration | `120s` | call | yes | `--exec-timeout` | `MCPX_EXEC_TIMEOUT` | kill a script after this long | | `exec.where` | enum | `auto` | call | yes | `--exec-where` | `MCPX_EXEC_WHERE` | in this process, or on the daemon | @@ -695,7 +696,7 @@ and a switch to turn the report off would have kept it quiet. | setting | kind | default | scope | hot | flag | variable | governs | | --- | --- | --- | --- | --- | --- | --- | --- | | `tasks.resultWait` | duration | `2m0s` | call | yes | `--tasks-result-wait` | `MCPX_TASKS_RESULT_WAIT` | how long collecting a task result blocks before giving up | -| `tasks.ttl` | duration | `10m0s` | daemon | yes | `--tasks-ttl` | `MCPX_TASKS_TTL` | how long a finished task's result is kept, measured from when the task finishes; a still-running task is never expired by it | +| `tasks.ttl` | duration | `10m0s` | daemon | yes | `--tasks-ttl` | `MCPX_TASKS_TTL` | how long a finished task's result is kept | ### transport diff --git a/pkgs/mcpx/internal/cli/commands.go b/pkgs/mcpx/internal/cli/commands.go index 1552988d9e..0f26844682 100644 --- a/pkgs/mcpx/internal/cli/commands.go +++ b/pkgs/mcpx/internal/cli/commands.go @@ -1121,7 +1121,11 @@ func (a *App) runScript(ctx context.Context, args []string, inline bool) error { if err != nil { return err } - env := runEnvelope(res, out.String(), collected, streamed) + // The envelope carries the service's capped stdout + // (res.Stdout), not the raw stream captured in out: the raw + // copy would hand back output the exec.maxOutputBytes cap + // already cut, with no truncation indication. + env := runEnvelope(res, res.Stdout, collected, streamed) if s := errOut.String(); s != "" { env["stderr"] = s } @@ -1191,6 +1195,9 @@ func runEnvelope(res *execsvc.Result, stdout string, logs []logging.Record, stre if res.TimedOut { env["timedOut"] = true } + if res.StdoutTruncated { + env["stdoutTruncated"] = true + } // A script whose stdout is JSON almost always means it as its result, so // offer it parsed as well as raw rather than making every caller re-parse. if trimmed := strings.TrimSpace(stdout); trimmed != "" { diff --git a/pkgs/mcpx/internal/cli/exec.go b/pkgs/mcpx/internal/cli/exec.go index 5f07e86d2a..a4535ed1bb 100644 --- a/pkgs/mcpx/internal/cli/exec.go +++ b/pkgs/mcpx/internal/cli/exec.go @@ -179,6 +179,7 @@ func (a *App) localService(store *artifacts.Store, socket string) *execsvc.Servi lim.InlineMaxBytes = set.Bytes("artifacts.inlineMaxBytes") lim.ChunkBytes = set.Bytes("artifacts.chunkBytes") lim.InterceptImages = set.Bool("artifacts.interceptImages") + lim.StdoutLimit = set.Bytes("exec.maxOutputBytes") return &execsvc.Service{ Store: store, // The script runs in this process's machine, and the daemon whose diff --git a/pkgs/mcpx/internal/daemon/exec_stdout_limit_test.go b/pkgs/mcpx/internal/daemon/exec_stdout_limit_test.go new file mode 100644 index 0000000000..ef5cfba6d4 --- /dev/null +++ b/pkgs/mcpx/internal/daemon/exec_stdout_limit_test.go @@ -0,0 +1,41 @@ +package daemon + +import ( + "io" + "log" + "net/http" + "net/http/httptest" + "testing" + + "github.com/dezren39/mcpx/internal/settings" +) + +// #1937 (CODE-16) Codex finding: exec.maxOutputBytes is call-scoped, but +// the daemon's handleExec built its service from cached startup +// settings, so a per-request --exec-max-output-bytes was silently +// ignored for remote executions. handleExec now applies +// s.callSettings(r).Bytes("exec.maxOutputBytes") to the service it runs; +// this pins the resolution that assignment relies on: the header value +// wins for the one request, and without a header the daemon's own +// (default) value stands. +func TestCallSettingsExecMaxOutputBytes(t *testing.T) { + sch, err := settings.New(settings.Registry()) + if err != nil { + t.Fatal(err) + } + s := &Server{ + set: settings.NewSet(sch), + logger: log.New(io.Discard, "", 0), + } + + req := httptest.NewRequest(http.MethodPost, "/v1/exec", nil) + req.Header.Set(CallSettingsHeader, `{"exec.maxOutputBytes":"1024"}`) + if got := s.callSettings(req).Bytes("exec.maxOutputBytes"); got != 1024 { + t.Errorf("request-scoped exec.maxOutputBytes = %d, want 1024", got) + } + + bare := httptest.NewRequest(http.MethodPost, "/v1/exec", nil) + if got := s.callSettings(bare).Bytes("exec.maxOutputBytes"); got != 64*1024 { + t.Errorf("default exec.maxOutputBytes = %d, want %d (64KiB)", got, 64*1024) + } +} diff --git a/pkgs/mcpx/internal/daemon/routes_exec.go b/pkgs/mcpx/internal/daemon/routes_exec.go index 374fe0704b..4bc05705ab 100644 --- a/pkgs/mcpx/internal/daemon/routes_exec.go +++ b/pkgs/mcpx/internal/daemon/routes_exec.go @@ -185,6 +185,7 @@ func (s *Server) ExecService() *execsvc.Service { lim.InlineMaxBytes = set.Bytes("artifacts.inlineMaxBytes") lim.ChunkBytes = set.Bytes("artifacts.chunkBytes") lim.InterceptImages = set.Bool("artifacts.interceptImages") + lim.StdoutLimit = set.Bytes("exec.maxOutputBytes") svc := &execsvc.Service{ Calls: s.callRegistry(), @@ -251,6 +252,12 @@ func (s *Server) handleExec(w http.ResponseWriter, r *http.Request) { return } svc := s.ExecService() + // exec.maxOutputBytes is call-scoped (settings/exec.go), so a value the + // client sent for this one request (--exec-max-output-bytes, forwarded + // via X-Mcpx-Settings) must govern this execution. ExecService builds + // from the daemon's cached startup settings and cannot see it; apply + // the request-resolved value to the service this request runs through. + svc.Limits.StdoutLimit = s.callSettings(r).Bytes("exec.maxOutputBytes") // A task is a handle now and the result later, which is the right shape // for a script that takes minutes: holding a request open that long diff --git a/pkgs/mcpx/internal/defaults/defaults.go b/pkgs/mcpx/internal/defaults/defaults.go index 1aed062cee..5605415a03 100644 --- a/pkgs/mcpx/internal/defaults/defaults.go +++ b/pkgs/mcpx/internal/defaults/defaults.go @@ -189,6 +189,7 @@ type Defaults struct { Programs int `json:"programs"` Entries int `json:"entries"` StderrLimit int `json:"stderrLimit"` + StdoutLimit int `json:"stdoutLimit"` Output string `json:"output"` RemoteOutput string `json:"remoteOutput"` Delivery string `json:"delivery"` @@ -679,6 +680,11 @@ var ( // explain the failure. Unbounded, a script looping on stderr would be // held in memory in full, by the daemon, on someone else's behalf. ExecStderrLimit = builtin.Exec.StderrLimit + // ExecStdoutLimit bounds how much of a run's stdout the returned + // Result carries (CODE-16, #1937). The full output still exists in + // the run record/artifacts where one is kept; this bounds only what + // is handed back into a caller's context. + ExecStdoutLimit = builtin.Exec.StdoutLimit // ExecWorkDirs bounds how many content-addressed client directories are // kept. One per distinct catalogue; without a bound it grows forever. ExecWorkDirs = builtin.Exec.WorkDirs diff --git a/pkgs/mcpx/internal/defaults/defaults.json b/pkgs/mcpx/internal/defaults/defaults.json index 0ffa7d79e0..0718841d55 100644 --- a/pkgs/mcpx/internal/defaults/defaults.json +++ b/pkgs/mcpx/internal/defaults/defaults.json @@ -164,6 +164,7 @@ "programs": 64, "entries": 8, "stderrLimit": 65536, + "stdoutLimit": 65536, "output": "text", "remoteOutput": "structured", "delivery": "reference" diff --git a/pkgs/mcpx/internal/execsvc/execsvc.go b/pkgs/mcpx/internal/execsvc/execsvc.go index 370cccd7a6..7e5a03190e 100644 --- a/pkgs/mcpx/internal/execsvc/execsvc.go +++ b/pkgs/mcpx/internal/execsvc/execsvc.go @@ -32,6 +32,7 @@ import ( "strings" "sync" "time" + "unicode/utf8" "github.com/dezren39/mcpx/internal/artifacts" "github.com/dezren39/mcpx/internal/defaults" @@ -356,17 +357,21 @@ type LogRecord struct { // Result is the structured answer. type Result struct { - RunID string `json:"runId"` - Result any `json:"result,omitempty"` - Emits []json.RawMessage `json:"emits"` - Logs []LogRecord `json:"logs"` - Stdout string `json:"stdout"` - Artifacts []Artifact `json:"artifacts"` - ExitCode int `json:"exitCode"` - DurationMs int64 `json:"durationMs"` - Runtime string `json:"runtime,omitempty"` - TimedOut bool `json:"timedOut,omitempty"` - Error string `json:"error,omitempty"` + RunID string `json:"runId"` + Result any `json:"result,omitempty"` + Emits []json.RawMessage `json:"emits"` + Logs []LogRecord `json:"logs"` + Stdout string `json:"stdout"` + // StdoutTruncated is set when Stdout was capped at + // Limits.StdoutLimit (exec.maxOutputBytes, CODE-16); the end of + // Stdout itself carries the marker naming the dropped byte count. + StdoutTruncated bool `json:"stdoutTruncated,omitempty"` + Artifacts []Artifact `json:"artifacts"` + ExitCode int `json:"exitCode"` + DurationMs int64 `json:"durationMs"` + Runtime string `json:"runtime,omitempty"` + TimedOut bool `json:"timedOut,omitempty"` + Error string `json:"error,omitempty"` } // Source supplies the generated client the script is run against. @@ -401,6 +406,8 @@ type Limits struct { InlineMaxBytes int64 ChunkBytes int64 InterceptImages bool + // StdoutLimit caps the stdout a Result returns (bytes); <= 0 is no cap. + StdoutLimit int64 } // DefaultLimits are the built-in values, before any configuration. @@ -414,6 +421,7 @@ func DefaultLimits() Limits { InlineMaxBytes: defaults.ArtifactInlineMaxBytes, ChunkBytes: defaults.ArtifactChunkBytes, InterceptImages: defaults.ArtifactInterceptImages, + StdoutLimit: int64(defaults.ExecStdoutLimit), } } @@ -798,11 +806,16 @@ func (s *Service) RunWith(ctx context.Context, ropts runner.Options, opts Option // A script whose stdout is JSON almost always means it as its answer, so // it is offered parsed as well as raw. The same rule `mcpx --json run` - // has always followed, kept identical so the two agree. + // has always followed, kept identical so the two agree. The parsed + // value is remembered so the truncation below can tell a + // stdout-derived Result from a hook replacement. + var stdoutParsed any + haveStdoutParsed := false if trimmed := strings.TrimSpace(res.Stdout); trimmed != "" { var parsed any if json.Unmarshal([]byte(trimmed), &parsed) == nil { res.Result = parsed + stdoutParsed, haveStdoutParsed = parsed, true } } @@ -871,6 +884,30 @@ func (s *Service) RunWith(ctx context.Context, ropts runner.Options, opts Option if deliveryOf(opts, s.Limits) == DeliveryStream { s.streamBodies(res, opts, emitFrame) } + + // CODE-16 (#1937): the Result boundary is where returned stdout is + // capped, so every surface that returns a run -- CLI, /v1, MCP -- + // sees the same capped stdout. Internal consumers above (the JSON + // answer parse, hooks) worked on the full text; only what is + // handed back is bounded. Full output is unchanged wherever a + // full record already exists. + if capped, truncated := truncateStdout(res.Stdout, s.Limits.StdoutLimit); truncated { + res.Stdout = capped + res.StdoutTruncated = true + // A Result that is still the stdout parse must not survive + // as a side channel around the cap: renderers (renderExec) + // treat a Result that no longer matches stdout as a hook + // replacement and re-present it in full. A hook replacement + // -- a value that differs from the stdout parse -- is the + // hook's own answer and is preserved. + if haveStdoutParsed && res.Result != nil { + if rb, err := json.Marshal(res.Result); err == nil { + if pb, err := json.Marshal(stdoutParsed); err == nil && string(rb) == string(pb) { + res.Result = nil + } + } + } + } return res, sinkErr } @@ -1145,6 +1182,65 @@ func ArtifactsDirFor(cwd, dir string) string { // // The tail rather than the head: a stack trace ends with the line that // matters, and a script that floods stderr floods it from the start. +// truncateStdout caps s at limit bytes, keeping the head and ending +// with a marker that names the dropped byte count, so truncation is +// visible, never silent. The returned string is at most limit bytes +// for EVERY positive limit, including one smaller than the marker +// itself (then the marker prefix alone fills the budget). A limit +// <= 0, or a string that already fits, is returned unchanged with +// truncated=false. The cut backs off to a UTF-8 rune boundary so it +// never splits a multi-byte rune. +func truncateStdout(s string, limit int64) (string, bool) { + if limit <= 0 || int64(len(s)) <= limit { + return s, false + } + marker := func(kept int) string { + return fmt.Sprintf("\n[mcpx: stdout truncated -- kept %d of %d bytes, dropped %d bytes; raise exec.maxOutputBytes to see more]", kept, len(s), len(s)-kept) + } + // The limit is a hard bound: when it cannot hold even the marker + // (kept = 0 is the shortest form), the marker's own prefix is the + // most informative thing that fits. + if int(limit) <= len(marker(0)) { + return marker(0)[:int(limit)], true + } + kept := int(limit) - len(marker(int(limit))) + // The marker's own length depends on kept's digit count; settle + // it. Each step is O(1): runeBoundary inspects only the last few + // bytes (see below), never the whole prefix. + for i := 0; i < 8; i++ { + kept = runeBoundary(s, kept) + want := int(limit) - len(marker(kept)) + if want == kept { + break + } + kept = want + } + kept = runeBoundary(s, kept) + for kept > 0 && kept+len(marker(kept)) > int(limit) { + kept = runeBoundary(s, kept-1) + } + return s[:kept] + marker(kept), true +} + +// runeBoundary returns kept, reduced by at most a few bytes so the +// cut does not split a multi-byte rune at the end of s[:kept]. It +// decodes only the last rune: an invalid byte EARLIER in s must not +// drag the cut back over the whole prefix (validating the shrinking +// prefix per dropped byte is quadratic on the arbitrary non-UTF-8 +// bytes a subprocess can emit). +func runeBoundary(s string, kept int) int { + for i := 0; i < utf8.UTFMax && kept > 0; i++ { + if s[kept-1] < utf8.RuneSelf { + break // ASCII: the cut is already on a boundary + } + if _, size := utf8.DecodeLastRuneInString(s[:kept]); size > 1 { + break // the last rune is complete (or a real U+FFFD) + } + kept-- // split rune or stray byte: retreat one byte + } + return kept +} + type tailBuffer struct { limit int buf []byte diff --git a/pkgs/mcpx/internal/execsvc/stdout_limit_service_test.go b/pkgs/mcpx/internal/execsvc/stdout_limit_service_test.go new file mode 100644 index 0000000000..78ac51d0af --- /dev/null +++ b/pkgs/mcpx/internal/execsvc/stdout_limit_service_test.go @@ -0,0 +1,54 @@ +package execsvc_test + +import ( + "strings" + "testing" + + "github.com/dezren39/mcpx/internal/execsvc" +) + +// CODE-16 (#1937), Codex P2 on PR 2979: when large JSON stdout is +// capped, the parsed Result must not survive as a side channel that +// lets a renderer re-present the uncapped answer in full. +func TestTruncatedJSONStdoutClearsStdoutDerivedResult(t *testing.T) { + svc := service(t, store(t)) + svc.Limits.StdoutLimit = 200 + res, _ := run(t, svc, ` +import { installGlobals } from "./mcpx-client.ts"; +installGlobals(); +console.log(JSON.stringify({ data: "x".repeat(5000) })); +`, execsvc.Options{}) + + if !res.StdoutTruncated { + t.Fatal("expected StdoutTruncated") + } + if len(res.Stdout) > 200 { + t.Fatalf("capped stdout is %d bytes, over the 200-byte cap", len(res.Stdout)) + } + if res.Result != nil { + t.Fatalf("stdout-derived Result survived truncation: %#v", res.Result) + } +} + +// Under the cap the stdout-derived Result is offered parsed, as +// before: the clearing above must only fire on truncation. +func TestUntruncatedJSONStdoutKeepsResult(t *testing.T) { + svc := service(t, store(t)) + svc.Limits.StdoutLimit = 200 + res, _ := run(t, svc, ` +import { installGlobals } from "./mcpx-client.ts"; +installGlobals(); +console.log(JSON.stringify({ total: 2 })); +`, execsvc.Options{}) + + if res.StdoutTruncated { + t.Fatal("under-cap output marked truncated") + } + m, ok := res.Result.(map[string]any) + if !ok || m["total"] != float64(2) { + t.Fatalf("JSON on stdout should be offered parsed, got %#v", res.Result) + } + if !strings.Contains(res.Stdout, "total") { + t.Fatalf("stdout = %q", res.Stdout) + } +} diff --git a/pkgs/mcpx/internal/execsvc/stdout_limit_test.go b/pkgs/mcpx/internal/execsvc/stdout_limit_test.go new file mode 100644 index 0000000000..1b281fe6b2 --- /dev/null +++ b/pkgs/mcpx/internal/execsvc/stdout_limit_test.go @@ -0,0 +1,106 @@ +package execsvc + +import ( + "strings" + "testing" +) + +// CODE-16 (#1937): returned stdout is capped at exec.maxOutputBytes +// with a visible marker; under-cap output is byte-identical. + +func TestTruncateStdoutOverCap(t *testing.T) { + full := strings.Repeat("a", 1000) + out, truncated := truncateStdout(full, 200) + if !truncated { + t.Fatal("expected truncated=true") + } + if len(out) > 200 { + t.Fatalf("capped output is %d bytes, over the 200-byte cap", len(out)) + } + if !strings.HasPrefix(out, strings.Repeat("a", 50)) { + t.Fatal("capped output does not keep the head of the original") + } + if !strings.Contains(out, "stdout truncated") { + t.Fatalf("capped output carries no truncation marker: %q", out[len(out)-120:]) + } + // The marker names how much was dropped: 1000 total, kept is + // whatever prefix survived, dropped = 1000 - kept. + if !strings.Contains(out, "of 1000 bytes") { + t.Fatalf("marker does not name the original size: %q", out) + } +} + +func TestTruncateStdoutUnderCapUnchanged(t *testing.T) { + in := "short answer\n" + out, truncated := truncateStdout(in, 200) + if truncated || out != in { + t.Fatalf("under-cap output changed: truncated=%v out=%q", truncated, out) + } +} + +func TestTruncateStdoutExactCapUnchanged(t *testing.T) { + in := strings.Repeat("b", 200) + out, truncated := truncateStdout(in, 200) + if truncated || out != in { + t.Fatalf("exact-cap output changed: truncated=%v len=%d", truncated, len(out)) + } +} + +func TestTruncateStdoutZeroLimitDisables(t *testing.T) { + in := strings.Repeat("c", 5000) + out, truncated := truncateStdout(in, 0) + if truncated || out != in { + t.Fatal("limit 0 must disable the cap") + } +} + +func TestTruncateStdoutSmallLimitHardBound(t *testing.T) { + // A positive limit smaller than the marker itself is still a + // hard bound (Codex P2 on PR 2979: limit 1 or 64 returned the + // full 108-byte marker). + full := strings.Repeat("a", 1000) + for _, limit := range []int64{1, 10, 64, 100} { + out, truncated := truncateStdout(full, limit) + if !truncated { + t.Fatalf("limit %d: expected truncated=true", limit) + } + if int64(len(out)) > limit { + t.Fatalf("limit %d: capped output is %d bytes, over the cap", limit, len(out)) + } + } +} + +func TestTruncateStdoutInvalidByteInPrefix(t *testing.T) { + // An invalid UTF-8 byte inside the retained prefix must not drag + // the cut back to before it (Codex P2 on PR 2979: the old code + // validated the whole shrinking prefix per dropped byte -- + // quadratic -- and silently dropped everything after the byte). + in := strings.Repeat("a", 500) + "\xff" + strings.Repeat("b", 500) + out, truncated := truncateStdout(in, 800) + if !truncated { + t.Fatal("expected truncated=true") + } + if len(out) > 800 { + t.Fatalf("capped output is %d bytes, over the 800-byte cap", len(out)) + } + if !strings.Contains(out, "stdout truncated") { + t.Fatal("no marker in capped output") + } + if !strings.Contains(out, strings.Repeat("b", 50)) { + t.Fatal("content after the invalid byte was dropped") + } +} + +func TestTruncateStdoutUTF8Boundary(t *testing.T) { + in := strings.Repeat("é", 500) // 2 bytes each, 1000 bytes total + out, truncated := truncateStdout(in, 201) + if !truncated { + t.Fatal("expected truncated=true") + } + if len(out) > 201 { + t.Fatalf("capped output is %d bytes, over the 201-byte cap", len(out)) + } + if !strings.Contains(out, "stdout truncated") { + t.Fatal("no marker in capped output") + } +} diff --git a/pkgs/mcpx/internal/settings/effect.go b/pkgs/mcpx/internal/settings/effect.go index dcd691386e..8e8b910c99 100644 --- a/pkgs/mcpx/internal/settings/effect.go +++ b/pkgs/mcpx/internal/settings/effect.go @@ -86,6 +86,7 @@ var EffectExemptions = map[string]string{ "script.onError": "script launcher pipeline: its effect needs a runtime, profile, or launcher fixture exercising that exact stage, which the harness script fixtures do not yet provide", "script.suffix": "script launcher pipeline: its effect needs a runtime, profile, or launcher fixture exercising that exact stage, which the harness script fixtures do not yet provide", "exec.timeout": "call-scoped exec behaviour with no dedicated with/without probe yet; the exec e2e tests exercise the surface only at its defaults", + "exec.maxOutputBytes": "call-scoped exec behaviour with no dedicated with/without probe yet; the exec e2e tests exercise the surface only at its defaults", "exec.output": "call-scoped exec behaviour with no dedicated with/without probe yet; the exec e2e tests exercise the surface only at its defaults", "exec.where": "call-scoped exec behaviour with no dedicated with/without probe yet; the exec e2e tests exercise the surface only at its defaults", "artifacts.enabled": "artifact store behaviour: its effect needs artifact-producing calls plus volume or time (ttl, quota, gc) that the fake server's fixtures do not drive", @@ -249,7 +250,7 @@ var EffectExemptions = map[string]string{ // EffectExemptionPin is the ratchet: the exemption count at the time // the guard landed. It may only ever be lowered, and only in the PR // that removes an exemption by adding the probe that replaces it. -const EffectExemptionPin = 182 // raised by one for policy.write (#1979), in the elicitation-flow exemption style of elicit.confirmDestructive +const EffectExemptionPin = 183 // raised by one for exec.maxOutputBytes (CODE-16, #1937), in the call-scoped exec exemption style of exec.timeout; previously raised by one for policy.write (#1979) // CheckEffectCoverage returns one violation per way the probe and // exemption maps fail to cover reg exactly: a setting with neither, diff --git a/pkgs/mcpx/internal/settings/exec.go b/pkgs/mcpx/internal/settings/exec.go index 7643f67f00..fa174da00d 100644 --- a/pkgs/mcpx/internal/settings/exec.go +++ b/pkgs/mcpx/internal/settings/exec.go @@ -35,6 +35,21 @@ func execRunSettings() []Setting { "what lets a consumer read the result and stop before downloading " + "artifacts it does not want.", }, + { + Path: "exec.maxOutputBytes", Scope: ScopeCall, Hot: true, Commands: runCommands, Kind: KindBytes, Default: "64KiB", + Name: "Max returned stdout bytes", + Short: "cap the stdout a run returns, with a truncation marker", + Long: "Applied at the execsvc Result boundary, so the CLI, /v1/exec " + + "and the MCP tool all return the same capped stdout. When a " + + "run's stdout exceeds the cap, the returned stdout keeps the " + + "first bytes that fit and ends with a marker naming how many " + + "bytes were dropped, and the result sets stdoutTruncated. " + + "The full output is unchanged wherever a full record already " + + "exists (run record / artifacts). 0 disables the cap. Stdout " + + "is the script's answer; one chatty script must not be able " + + "to dump unbounded output into the caller's context, which " + + "is the exact cost code mode exists to avoid (CODE-16).", + }, { Path: "exec.where", Scope: ScopeCall, Hot: true, Commands: runCommands, Kind: KindEnum, Default: "auto", Enum: []string{"auto", "local", "remote"},