Skip to content
Open
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ All notable changes to this project are documented in this file. The format is b

### Fixed

- **The system prompt is cached for every agent**: `deferredSystem` set the cache boundary only when the agent had globally available MCP tools, and returned 0 otherwise. A boundary of 0 sends no cache breakpoint at all, so for an agent without such tools (the common case) the planner, workers, chat and main agent sent their tools and system prompt uncached on every turn, and `cache_read_input_tokens` stayed at 0 on Anthropic profiles; the goal decomposer never set a boundary at all. The whole system prompt now always gets a breakpoint.
- **The Bedrock gateway turns automatic caching into an explicit breakpoint**: the legacy InvokeModel integration rejects the top-level `cache_control` field, which newer Norma versions send on Anthropic requests by default, and accepts explicit breakpoints on every version. The gateway removes the field and puts the breakpoint on the last cacheable block of the last message, where automatic caching would place it, so the conversation history is cached on Bedrock too. It removes the field but leaves the messages unchanged when that block already has a breakpoint or the request has no breakpoint slot left. The breakpoint on the system prompt is kept.
- **An `exact_ip` task allow rule grants sandbox egress**: the egress allowlist read task allow rules of kind `ip`, which the rule tables never store, so an `exact_ip` allow rule granted nothing. A task scoped to one private address (`10.0.0.5`) could not reach it from the sandbox, directly or through a name resolving only to it. `exact_ip` allow rules now join the allowed CIDRs as a host prefix, like `cidr` allow rules.
- **`GET /api/tasks/{id}/scope` reports scope approval**: the query behind it did not select `approved_by_operator` or `expanded`, so every row came back with `approved_by_operator: false` and `expanded: false`, including operator-approved rows that grant sandbox egress. The rows now carry both columns as stored, for the task's own scope and for its source tasks' scope.
- **The OpenAI Responses format no longer defaults to `gpt-5`**: OpenAI shuts `gpt-5` down on 2026-12-11 and lists `gpt-6.2-sol` as its replacement, so `ARTEX_LLM_PROVIDER=openai-responses` without `ARTEX_LLM_MODEL` (or a profile saved through the API without a model) would start failing then. The default is now `gpt-6.2-sol`; a model set in the profile or in `ARTEX_LLM_MODEL` is kept as is. A gateway set with `ARTEX_LLM_BASE_URL` that does not serve `gpt-6.2-sol` needs `ARTEX_LLM_MODEL` set explicitly.
Expand Down
105 changes: 105 additions & 0 deletions agent/bedrock_gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,15 @@ func (t *bedrockGatewayTransport) RoundTrip(req *http.Request) (*http.Response,
}
delete(body, "stream")
delete(body, "model")
// The legacy InvokeModel integration rejects automatic caching (top-level
// cache_control) and takes explicit breakpoints only, which every version
// accepts. Move the breakpoint to where automatic caching would put it.
if cc, ok := body["cache_control"]; ok {
delete(body, "cache_control")
if msgs, ok := markLastCacheableBlock(body, cc); ok {
body["messages"] = msgs
}
}
body["anthropic_version"] = json.RawMessage(`"bedrock-2023-05-31"`)
raw, err = json.Marshal(body)
if err != nil {
Expand Down Expand Up @@ -294,6 +303,102 @@ func (t *bedrockGatewayTransport) RoundTrip(req *http.Request) (*http.Response,
return &copy, nil
}

// cacheableBlockTypes are the content blocks that can carry a cache breakpoint;
// thinking blocks cannot.
var cacheableBlockTypes = map[string]bool{"text": true, "image": true, "document": true, "tool_use": true, "tool_result": true}

// maxCacheBreakpoints is the API's limit on cache_control markers per request.
const maxCacheBreakpoints = 4

// markLastCacheableBlock puts cc on the last cacheable block of the last
// message, the place automatic caching would pick, walking back past blocks
// that cannot carry it. A string content becomes one text block. It reports
// false, leaving the messages unchanged, when no block qualifies, when that
// block already has a breakpoint, or when body (without its top-level marker)
// already uses every breakpoint slot. Map round-trips sort keys, which leaves
// the rendered prompt and so the cached prefix unchanged.
func markLastCacheableBlock(body map[string]json.RawMessage, cc json.RawMessage) (json.RawMessage, bool) {
if countCacheBreakpoints(body) >= maxCacheBreakpoints {
return nil, false
}
var msgs []map[string]json.RawMessage
if json.Unmarshal(body["messages"], &msgs) != nil || len(msgs) == 0 {
return nil, false
}
last := msgs[len(msgs)-1]
var blocks []map[string]json.RawMessage
var text string
if json.Unmarshal(last["content"], &text) == nil {
quoted, _ := json.Marshal(text)
blocks = []map[string]json.RawMessage{{"type": json.RawMessage(`"text"`), "text": quoted}}
} else if json.Unmarshal(last["content"], &blocks) != nil {
return nil, false
}
for i := len(blocks) - 1; i >= 0; i-- {
var typ string
_ = json.Unmarshal(blocks[i]["type"], &typ)
if !cacheableBlockTypes[typ] {
continue
}
if _, marked := blocks[i]["cache_control"]; marked {
return nil, false
}
blocks[i]["cache_control"] = cc
content, err := json.Marshal(blocks)
if err != nil {
return nil, false
}
last["content"] = content
out, err := json.Marshal(msgs)
if err != nil {
return nil, false
}
return out, true
}
return nil, false
}

// countCacheBreakpoints counts the cache_control markers in the places the API
// reads them: tool definitions, system blocks, message content blocks and the
// blocks nested in a tool_result. A key of that name inside tool input or a
// schema is data, not a breakpoint, and is not counted.
func countCacheBreakpoints(body map[string]json.RawMessage) int {
n := 0
countBlocks := func(raw json.RawMessage) {
var blocks []map[string]json.RawMessage
if json.Unmarshal(raw, &blocks) != nil {
return // a string content or system has no blocks to mark
}
for _, b := range blocks {
if _, ok := b["cache_control"]; ok {
n++
}
var typ string
if json.Unmarshal(b["type"], &typ) == nil && typ == "tool_result" {
var inner []map[string]json.RawMessage
if json.Unmarshal(b["content"], &inner) == nil {
for _, ib := range inner {
if _, ok := ib["cache_control"]; ok {
n++
}
}
}
}
}
}
countBlocks(body["tools"])
countBlocks(body["system"])
var msgs []struct {
Content json.RawMessage `json:"content"`
}
if json.Unmarshal(body["messages"], &msgs) == nil {
for _, m := range msgs {
countBlocks(m.Content)
}
}
return n
}

func jsonResponse(resp *http.Response, body []byte) *http.Response {
copy := *resp
copy.Body = io.NopCloser(bytes.NewReader(body))
Expand Down
103 changes: 103 additions & 0 deletions agent/bedrock_gateway_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ func TestBedrockGatewayCompleteAndStream(t *testing.T) {
if string(body["anthropic_version"]) != `"bedrock-2023-05-31"` {
t.Errorf("version = %s", body["anthropic_version"])
}
if _, ok := body["cache_control"]; ok {
t.Error("top-level cache_control remained in body")
}
if !strings.Contains(r.URL.Path, "response-stream") {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"type":"message","content":[{"type":"text","text":"done"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`))
Expand Down Expand Up @@ -198,6 +201,106 @@ func TestBedrockGatewayDoesNotFollowRedirectWithToken(t *testing.T) {
}
}

// sendThroughGateway posts body through the gateway transport directly (so the
// test does not depend on what the Norma version in go.mod sends) and returns
// the body the InvokeModel endpoint received.
func sendThroughGateway(t *testing.T, body string) map[string]json.RawMessage {
t.Helper()
var got map[string]json.RawMessage
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
t.Error(err)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"type":"message","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn"}`))
}))
defer server.Close()
tr := &bedrockGatewayTransport{base: http.DefaultTransport, baseURL: server.URL, token: "synthetic-token", model: "test.model"}
req, err := http.NewRequest(http.MethodPost, server.URL+"/v1/messages", strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
resp, err := tr.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
return got
}

// The legacy InvokeModel integration rejects the top-level automatic-caching
// field but takes explicit breakpoints, so the gateway moves the breakpoint
// onto the last cacheable block of the last message and keeps the system one.
func TestBedrockGatewayMovesTopLevelCacheControl(t *testing.T) {
const sys = `"system":[{"type":"text","text":"SYS","cache_control":{"type":"ephemeral"}}]`
const mark = `"cache_control":{"type":"ephemeral"}`
cases := []struct {
name, messages string
wantLast string // substring the last message's content must contain; "" = unchanged
wantMarks int // 5-minute breakpoints in the forwarded messages
keep string // substring the forwarded messages must still contain
}{
{"text block", `[{"role":"user","content":[{"type":"text","text":"hi"}]}]`, `"text":"hi"`, 1, ""},
{"string content", `[{"role":"user","content":"hi"}]`, `"text":"hi"`, 1, ""},
{"tool result after earlier turns",
`[{"role":"user","content":"q"},{"role":"assistant","content":[{"type":"thinking","thinking":"","signature":"s"},{"type":"tool_use","id":"t1","name":"x","input":{}}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"r"}]}]`, `"type":"tool_result"`, 1, ""},
{"walks back past a thinking block",
`[{"role":"user","content":"q"},{"role":"assistant","content":[{"type":"text","text":"a"},{"type":"thinking","thinking":"","signature":"s"}]}]`, `"text":"a"`, 1, ""},
{"already marked keeps its own marker", `[{"role":"user","content":[{"type":"text","text":"hi","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]`, "", 0, `"ttl":"1h"`},
{"last free slot is used",
`[{"role":"user","content":[{"type":"text","text":"a",` + mark + `},{"type":"text","text":"b",` + mark + `},{"type":"text","text":"c"}]}]`, `"text":"c"`, 3, ""},
{"cache_control keys inside tool input are not breakpoints",
`[{"role":"user","content":"q"},{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"x","input":{"a":{"cache_control":1},"b":{"cache_control":2},"c":{"cache_control":3},"d":{"cache_control":4}}}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"r"}]}]`, `"type":"tool_result"`, 1, ""},
{"markers on tools and inside a tool_result count",
`[{"role":"user","content":"q"},{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"x","input":{}}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":[{"type":"text","text":"r1",` + mark + `},{"type":"text","text":"r2",` + mark + `}]}]}]`, "", 2, ""},
{"no slot left",
`[{"role":"user","content":[{"type":"text","text":"a",` + mark + `},{"type":"text","text":"b",` + mark + `},{"type":"text","text":"c",` + mark + `},{"type":"text","text":"d"}]}]`, "", 3, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
tools := ""
if strings.Contains(tc.messages, `"r1"`) {
tools = `"tools":[{"name":"x","input_schema":{"type":"object"},` + mark + `}],`
}
got := sendThroughGateway(t, `{"model":"m","stream":false,"max_tokens":16,"cache_control":{"type":"ephemeral"},`+tools+sys+`,"messages":`+tc.messages+`}`)
if _, ok := got["cache_control"]; ok {
t.Fatalf("top-level cache_control forwarded: %s", got["cache_control"])
}
if !bytes.Contains(got["system"], []byte(mark)) {
t.Fatalf("system breakpoint lost: %s", got["system"])
}
if n := bytes.Count(got["messages"], []byte(mark)); n != tc.wantMarks {
t.Fatalf("breakpoints in messages = %d, want %d: %s", n, tc.wantMarks, got["messages"])
}
if !bytes.Contains(got["messages"], []byte(tc.keep)) {
t.Fatalf("messages lost %s: %s", tc.keep, got["messages"])
}
if tc.wantLast == "" {
return
}
var msgs []map[string]json.RawMessage
var last []map[string]json.RawMessage
if json.Unmarshal(got["messages"], &msgs) != nil || json.Unmarshal(msgs[len(msgs)-1]["content"], &last) != nil {
t.Fatalf("last message content is not a block list: %s", got["messages"])
}
for i := len(last) - 1; i >= 0; i-- { // the gateway's marker is the last one
b := last[i]
enc, _ := json.Marshal(b)
if _, ok := b["cache_control"]; ok {
if !bytes.Contains(enc, []byte(tc.wantLast)) {
t.Fatalf("breakpoint on the wrong block: %s", enc)
}
return
}
}
t.Fatalf("no breakpoint on the last message: %s", got["messages"])
})
}
}

func TestBedrockGatewayEscapesModelARN(t *testing.T) {
const model = "arn:aws:bedrock:region:123456789012:foundation-model/test.model"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down
21 changes: 10 additions & 11 deletions agent/deferred.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,19 @@ import (
// deferredSystem builds an agent's system-prompt segments and cache boundary from
// its DeferredInfo. When globally-available MCP tools are present, their names + a
// "prefer core tools" instruction render into a <available-deferred-tools> block
// placed as the LAST system-prompt segment, with DynamicBoundary set so the whole
// (session-fixed) system prompt — including the block — is cached (design doc
// §2.1 / C1). Skill-gated MCP names are NOT in this block; they surface when their
// skill loads. Returns a single plain segment + boundary 0 when there is no global
// block to add.
// placed as the LAST system-prompt segment (design doc §2.1 / C1). Skill-gated MCP
// names are NOT in this block; they surface when their skill loads.
//
// The boundary is always len(system), so the whole (session-fixed) system prompt
// gets a cache breakpoint, with or without the block; a boundary of 0 would send
// it with none.
func deferredSystem(sysText string, def DeferredInfo) (system []string, boundary int) {
sysText += def.FindingGuidance + def.SkillIndex
block := actool.RenderDeferredToolsBlock(def.GlobalNames)
if block == "" {
return []string{sysText}, 0
system = []string{sysText}
if block := actool.RenderDeferredToolsBlock(def.GlobalNames); block != "" {
system = append(system, block)
}
system = []string{sysText, block}
boundary = len(system) // b >= len → whole system prompt cached (SDK guard)
return system, boundary
return system, len(system) // b >= len → whole system prompt cached (SDK guard)
}

// skillIndexMax bounds the names-only skill index. Skills are meant to be few and
Expand Down
7 changes: 4 additions & 3 deletions agent/deferred_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ import (
)

func TestDeferredSystem_NoGlobal(t *testing.T) {
// No global MCP names → plain single-segment system, no cache boundary.
// No global MCP names → plain single-segment system, still cached whole:
// boundary 0 would send it with no cache breakpoint.
sys, boundary := deferredSystem("SYS", DeferredInfo{})
if len(sys) != 1 || sys[0] != "SYS" || boundary != 0 {
t.Fatalf("expected [SYS],0 — got %v,%d", sys, boundary)
if len(sys) != 1 || sys[0] != "SYS" || boundary != 1 {
t.Fatalf("expected [SYS],1 — got %v,%d", sys, boundary)
}
}

Expand Down
1 change: 1 addition & 0 deletions agent/goals.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir,
session := agentcore.NewSession(agentcore.Options{
Provider: prov,
SystemPrompt: []string{sys},
DynamicBoundary: 1, // the whole static system prompt gets a cache breakpoint across the turns
Tools: tools,
PermissionMode: acperm.ModeBypass,
DisableBackgroundTasks: true,
Expand Down
7 changes: 7 additions & 0 deletions agent/goals_contract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,13 @@ func TestDecomposeGoalsValidStructuredToolCallAccepted(t *testing.T) {
if prov.calls() != 2 {
t.Fatalf("expected 2 turns with no retry, got %d", prov.calls())
}
// A multi-turn session: the static system prompt (with the tools before it)
// must carry a cache breakpoint, or every turn resends it uncached.
for i, req := range prov.reqs {
if req.DynamicBoundary < 1 {
t.Fatalf("request %d: DynamicBoundary=%d, want the system prompt cached", i, req.DynamicBoundary)
}
}
}

func TestDecomposeGoalsRejectsEmptyTaskGoalAndEmptyToolArgs(t *testing.T) {
Expand Down
4 changes: 2 additions & 2 deletions agent/skill_index_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ func TestSkillIndexBlock_Empty(t *testing.T) {
}
// An agent without skills keeps its previous prompt byte-for-byte.
sys, boundary := deferredSystem("SYS", DeferredInfo{})
if len(sys) != 1 || sys[0] != "SYS" || boundary != 0 {
t.Fatalf("expected [SYS],0 — got %v,%d", sys, boundary)
if len(sys) != 1 || sys[0] != "SYS" || boundary != 1 {
t.Fatalf("expected [SYS],1 — got %v,%d", sys, boundary)
}
}

Expand Down
Loading
Loading