Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions docs/execution-pkg-detail.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,26 +150,31 @@ explicitly in `config.skills.config` for both thread start and resume; arbitrary
native config-file contents are never forwarded. Unsupported writes, malformed
responses and state mismatches fail closed without starting or resuming a thread.
Ambient apps, cloud and bundled Skills, plugins, project instructions and MCP
configuration are replaced by the explicit request configuration. Images,
forks, tool-free execution,
configuration are replaced by the explicit request configuration. Up to four
validated images are sent inline after the task text, in caller order; optional
names are separate safely quoted text items. Forks, tool-free execution,
extraction, restricted reads and tool allowlists remain unsupported on this path.

App-server raw callbacks carry `NativeProtocol="codex-app-server"` and preserve
the original JSON-RPC method and params. Matching thread/turn completion is the
only success terminal. Model evidence comes from thread start/resume and native
reroute notifications; missing model, usage and cost remain unavailable. On
cancellation Offload first requests `turn/interrupt`, then closes and reaps the
same owned process group under the normal worker bounds.
protocol metadata. Returned image data-URL payloads are replaced, before parsing
or retention, by their digest and byte count; malformed or oversized image-bearing
frames become bounded omission records. This applies to observers, transcript
captures, diagnostics and fresh or resumed history results. Matching thread/turn
completion is the only success terminal. Model evidence comes from thread
start/resume and native reroute notifications; missing model, usage and cost remain
unavailable. On cancellation Offload first requests `turn/interrupt`, then closes
and reaps the same owned process group under the normal worker bounds.
The initialize request opts into the experimental API required by explicit Skill
roots. Native app-server responses may omit the optional `jsonrpc` member; an
explicit version other than `2.0` is rejected.
Completed agent-message items are authoritative final text when deltas or terminal
turn items are absent. Malformed response envelopes fail before dispatch, and a
failed turn retains only a bounded single-line provider diagnostic.

For Native calls, callbacks retain complete events up to 32 MiB (bounded image
envelopes included), including a final unterminated line. Larger events fail
explicitly. The default 256 KiB callback contract is unchanged for other callers.
For Native calls, callbacks retain complete events up to 32 MiB (with Codex
app-server image payloads redacted first), including a final unterminated line.
Larger events fail explicitly. The default 256 KiB callback contract is unchanged
for other callers.
After process exit, idle pipe reads are bounded independently of callback time.
Native caller-context cancellation freezes and stops the owned descendant tree,
including native Bash children in separate sessions; it never selects by command
Expand Down
7 changes: 4 additions & 3 deletions docs/execution-pkg.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,10 @@ a normalized or complete UI transcript.

Optional `Request.Native` controls let an embedding Host preserve Claude session
IDs/forks, exact MCP and Skills mounts, permissions, structured extraction and
image input through the same worker. `CallerContext` keeps caller-supplied
instructions and task separate from Offload's delegation role. Set `Caller` and
`CallerRunID` on business and internal requests so history keeps attribution.
image input through the same worker. Codex image input requires its explicit
app-server mode; legacy Codex execution still rejects it. `CallerContext` keeps
caller-supplied instructions and task separate from Offload's delegation role.
Set `Caller` and `CallerRunID` on business and internal requests so history keeps attribution.
Unsupported backend controls fail before launch; ordinary Codex requests remain
supported. This adds no Host policy, message routing or automatic session adoption.

Expand Down
19 changes: 17 additions & 2 deletions internal/worker/codex_app_server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package worker

import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
Expand All @@ -18,6 +19,8 @@ import (

const codexAppServerProtocol = "codex-app-server"

const codexAppServerMaxFrame = 32 << 20

type appServerMessage struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Expand Down Expand Up @@ -227,7 +230,7 @@ func (p *appServerParser) write(v any) error {
if err != nil {
return err
}
if len(b) > maxLineKept {
if len(b) > codexAppServerMaxFrame {
return errors.New("Codex app-server request exceeds frame limit")
}
b = append(b, '\n')
Expand Down Expand Up @@ -304,7 +307,7 @@ func (p *appServerParser) initialize() error {
p.threadID, p.s.Session = thread.Thread.ID, thread.Thread.ID
p.s.ObservedModel = firstNonEmpty(thread.Model, thread.Thread.Model)
p.mu.Unlock()
turn := map[string]any{"threadId": thread.Thread.ID, "input": []any{map[string]any{"type": "text", "text": p.o.Task}}, "cwd": p.o.Dir, "runtimeWorkspaceRoots": roots}
turn := appServerTurnParams(p.o, thread.Thread.ID, roots)
if p.o.Native.JSONSchema != "" {
var schema any
_ = json.Unmarshal([]byte(p.o.Native.JSONSchema), &schema)
Expand All @@ -328,6 +331,18 @@ func (p *appServerParser) initialize() error {
return nil
}

func appServerTurnParams(o Opts, threadID string, roots []string) map[string]any {
input := []any{map[string]any{"type": "text", "text": o.Task}}
for _, image := range o.Native.Images {
if image.Name != "" {
name, _ := json.Marshal(image.Name)
input = append(input, map[string]any{"type": "text", "text": "Image name: " + string(name)})
}
input = append(input, map[string]any{"type": "image", "url": "data:" + image.MediaType + ";base64," + base64.StdEncoding.EncodeToString(image.Data)})
}
return map[string]any{"threadId": threadID, "input": input, "cwd": o.Dir, "runtimeWorkspaceRoots": roots}
}

func (p *appServerParser) initializeExactSkills() error {
manifest, err := exactSkillManifest(p.o.Native.SkillRoots)
if err != nil {
Expand Down
231 changes: 231 additions & 0 deletions internal/worker/codex_app_server_image_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
package worker

import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)

type imageRecordingCapture struct{ lines []string }

func (*imageRecordingCapture) AddSecrets(...string) {}
func (*imageRecordingCapture) BeginAttempt(string, string) {}
func (c *imageRecordingCapture) Line(line []byte) {
c.lines = append(c.lines, string(line))
}
func (*imageRecordingCapture) Skipped(string, int) {}

func TestCodexAppServerTurnCarriesOrderedImagesOnFreshAndResume(t *testing.T) {
images := []NativeImage{
{Name: "first \"label\".png", MediaType: "image/png", Data: []byte{0, 1, 2, 3}},
{MediaType: "image/webp", Data: []byte("exact second image")},
}
for _, resume := range []bool{false, true} {
name := "fresh"
if resume {
name = "resume"
}
t.Run(name, func(t *testing.T) {
bin, log := appServerFixture(t, "", completedAppServerTail)
o := appServerOpts(t, t.TempDir())
o.Native.SkillRoots, o.Native.JSONSchema, o.Native.Images = nil, "", images
if resume {
o.Resume = "existing-thread"
}
a := runAttempt(context.Background(), bin, o, "", "", o.Timeout, nil, hooks{})
if a.runErr != nil || a.s.Result == nil {
t.Fatalf("%+v", a)
}
input := capturedTurnInput(t, log)
if len(input) != 4 || input[0].Type != "text" || input[0].Text != o.Task || input[1].Type != "text" || input[1].Text != `Image name: "first \"label\".png"` {
t.Fatalf("unexpected ordered input: %+v", input)
}
for index, position := range []int{2, 3} {
got := input[position]
want := images[index]
prefix := "data:" + want.MediaType + ";base64,"
if got.Type != "image" || !strings.HasPrefix(got.URL, prefix) || strings.Contains(got.URL, "http://") || strings.Contains(got.URL, "https://") {
t.Fatalf("image %d was not inline: %+v", index, got)
}
decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(got.URL, prefix))
if err != nil || string(decoded) != string(want.Data) {
t.Fatalf("image %d bytes changed: %x %v", index, decoded, err)
}
}
})
}
}

type capturedUserInput struct {
Type string `json:"type"`
Text string `json:"text"`
URL string `json:"url"`
}

func capturedTurnInput(t *testing.T, path string) []capturedUserInput {
t.Helper()
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
for _, line := range strings.Split(string(raw), "\n") {
var request struct {
Method string `json:"method"`
Params struct {
Input []capturedUserInput `json:"input"`
} `json:"params"`
}
if json.Unmarshal([]byte(line), &request) == nil && request.Method == "turn/start" {
return request.Params.Input
}
}
t.Fatalf("turn/start missing from %s", raw)
return nil
}

func TestCodexImageValidationPreservesBoundsAndLegacyRejection(t *testing.T) {
valid := NativeImage{Name: "image.png", MediaType: "image/png", Data: []byte("x")}
base := NativeControls{CallerContext: true, CodexAppServer: true, PermissionMode: "bypassPermissions"}
for _, tc := range []struct {
name string
change func(*NativeControls)
}{
{name: "too many", change: func(n *NativeControls) { n.Images = []NativeImage{valid, valid, valid, valid, valid} }},
{name: "too large", change: func(n *NativeControls) {
n.Images = []NativeImage{{MediaType: "image/png", Data: make([]byte, (5<<20)+1)}}
}},
{name: "unsupported MIME", change: func(n *NativeControls) { n.Images = []NativeImage{{MediaType: "image/svg+xml", Data: []byte("x")}} }},
{name: "invalid name", change: func(n *NativeControls) {
n.Images = []NativeImage{{Name: string([]byte{0xff}), MediaType: "image/png", Data: []byte("x")}}
}},
{name: "legacy", change: func(n *NativeControls) { n.CodexAppServer = false; n.Images = []NativeImage{valid} }},
} {
t.Run(tc.name, func(t *testing.T) {
n := base
tc.change(&n)
if err := n.Validate("codex", "", false); err == nil {
t.Fatal("invalid image controls accepted")
}
})
}
}

func TestCodexAppServerMaximalValidImagesFitOutboundFrame(t *testing.T) {
data := bytes.Repeat([]byte{0xa5}, 5<<20)
images := make([]NativeImage, 4)
for i := range images {
images[i] = NativeImage{MediaType: "image/png", Data: data}
}
o := Opts{Task: "maximal images", Dir: "/workspace", Native: &NativeControls{Images: images}}
params := appServerTurnParams(o, "thread-max", []string{"/workspace"})
var output bytes.Buffer
parser := newAppServerParser(discardWriteCloser{&output}, o)
if err := parser.write(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "turn/start", "params": params}); err != nil {
t.Fatal(err)
}
if output.Len() <= maxLineKept || output.Len() > codexAppServerMaxFrame+1 {
t.Fatalf("serialized frame size=%d, want (%d,%d]", output.Len(), maxLineKept, codexAppServerMaxFrame+1)
}
var request struct {
Method string `json:"method"`
Params struct {
Input []capturedUserInput `json:"input"`
} `json:"params"`
}
if err := json.Unmarshal(bytes.TrimSpace(output.Bytes()), &request); err != nil || request.Method != "turn/start" || len(request.Params.Input) != 5 {
t.Fatalf("invalid maximal turn request: method=%q input=%d err=%v", request.Method, len(request.Params.Input), err)
}
for index, item := range request.Params.Input[1:] {
payload := strings.TrimPrefix(item.URL, "data:image/png;base64,")
decoded, err := base64.StdEncoding.DecodeString(payload)
if item.Type != "image" || err != nil || !bytes.Equal(decoded, data) {
t.Fatalf("image %d did not round trip: type=%q bytes=%d err=%v", index, item.Type, len(decoded), err)
}
}
}

func TestCodexAppServerRedactsImageFromRecordObserverAndTranscript(t *testing.T) {
root := t.TempDir()
skill := filepath.Join(root, "SKILL.md")
if err := os.WriteFile(skill, []byte("fixture"), 0600); err != nil {
t.Fatal(err)
}
secret := []byte("history-private-image-bytes")
dataURL := "data:image/png;base64," + base64.StdEncoding.EncodeToString(secret)
nested, err := json.Marshal(map[string]any{"type": "image", "url": dataURL})
if err != nil {
t.Fatal(err)
}
turnStarted := mustTestJSON(t, map[string]any{
"method": "turn/started",
"params": map[string]any{"threadId": "thread-native", "turn": map[string]any{"id": "turn-native"}},
})
started := mustTestJSON(t, map[string]any{
"method": "item/started",
"params": map[string]any{
"threadId": "thread-native", "turnId": "turn-native",
"item": map[string]any{"id": "user", "type": "userMessage", "content": []any{map[string]any{"type": "image", "url": dataURL}}},
},
})
completed := mustTestJSON(t, map[string]any{
"method": "item/completed",
"params": map[string]any{
"threadId": "thread-native", "turnId": "turn-native",
"item": map[string]any{"id": "answer", "type": "agentMessage", "text": string(nested)},
},
})
turnCompleted := mustTestJSON(t, map[string]any{
"method": "turn/completed",
"params": map[string]any{
"threadId": "thread-native",
"turn": map[string]any{"id": "turn-native", "status": "completed", "items": []any{}, "error": nil},
},
})
tail := fmt.Sprintf("printf '%%s\\n' '%s'\nprintf '%%s\\n' '%s'\nprintf '%%s\\n' '%s'\nprintf '%%s\\n' '%s'", turnStarted, started, completed, turnCompleted)
bin, _ := appServerFixture(t, skill, tail)
source := t.TempDir()
if err := os.WriteFile(filepath.Join(source, "auth.json"), []byte(`{"token":"fixture"}`), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("CODEX_HOME", source)
t.Setenv("OFFLOAD_CODEX", bin)
t.Setenv("XDG_STATE_HOME", t.TempDir())
o := appServerOpts(t, root)
o.CodexHome = ""
o.Native.JSONSchema = ""
o.MaxWorkers = 1
transcript := &imageRecordingCapture{}
o.Transcript = transcript
var observed []string
o.OnLine = func(line []byte) error {
observed = append(observed, string(line))
return nil
}
record, err := Run(context.Background(), o)
if err != nil || record.Status != "ok" || record.Session != "thread-native" {
t.Fatalf("record=%+v err=%v observed=%q transcript=%q", record, err, observed, transcript.lines)
}
recordJSON, err := json.Marshal(record)
if err != nil {
t.Fatal(err)
}
encodedSecret := base64.StdEncoding.EncodeToString(secret)
for name, output := range map[string]string{
"history record": string(recordJSON),
"observer": strings.Join(observed, "\n"),
"transcript": strings.Join(transcript.lines, "\n"),
} {
if strings.Contains(output, encodedSecret) || strings.Contains(output, string(secret)) {
t.Fatalf("%s leaked image payload: %s", name, output)
}
if !strings.Contains(output, "sha256=") || !strings.Contains(output, "bytes=") {
t.Fatalf("%s lost redaction evidence: %s", name, output)
}
}
}
14 changes: 11 additions & 3 deletions internal/worker/codex_host_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,6 @@ func TestCodexAppServerControlsRemainExplicit(t *testing.T) {
for _, mutate := range []func(*NativeControls){
func(v *NativeControls) { v.CallerContext = false },
func(v *NativeControls) { v.PermissionMode = "default" },
func(v *NativeControls) {
v.Images = []NativeImage{{Name: "x", MediaType: "image/png", Data: []byte("x")}}
},
func(v *NativeControls) { v.ForkFromSessionID = "fork" },
func(v *NativeControls) { v.AllowedTools = []string{"Read"} },
} {
Expand All @@ -69,6 +66,17 @@ func TestCodexAppServerControlsRemainExplicit(t *testing.T) {
t.Fatal("unsupported app-server control accepted")
}
}
withImage := *n
withImage.Images = []NativeImage{{Name: "x", MediaType: "image/png", Data: []byte("x")}}
if err := withImage.Validate("codex", "", false); err != nil {
t.Fatalf("app-server image rejected: %v", err)
}
legacy := withImage
legacy.CodexAppServer = false
legacy.SkillRoots, legacy.JSONSchema = nil, ""
if err := legacy.Validate("codex", "", false); err == nil || !strings.Contains(err.Error(), "app-server") {
t.Fatalf("legacy Codex image accepted: %v", err)
}
}

func TestCodexAppServerLaunchDisablesAmbientSkillSources(t *testing.T) {
Expand Down
Loading
Loading