diff --git a/CHANGELOG.md b/CHANGELOG.md index d21e99130..b8d26df70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/agent/bedrock_gateway.go b/agent/bedrock_gateway.go index 5b4ad6fb5..7164d648c 100644 --- a/agent/bedrock_gateway.go +++ b/agent/bedrock_gateway.go @@ -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 { @@ -294,6 +303,102 @@ func (t *bedrockGatewayTransport) RoundTrip(req *http.Request) (*http.Response, return ©, 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)) diff --git a/agent/bedrock_gateway_test.go b/agent/bedrock_gateway_test.go index 3e1fdad31..51cd855b3 100644 --- a/agent/bedrock_gateway_test.go +++ b/agent/bedrock_gateway_test.go @@ -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}}`)) @@ -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) { diff --git a/agent/deferred.go b/agent/deferred.go index d846b6e22..fa4d909b2 100644 --- a/agent/deferred.go +++ b/agent/deferred.go @@ -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 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 diff --git a/agent/deferred_test.go b/agent/deferred_test.go index e2a9b2edf..d92581490 100644 --- a/agent/deferred_test.go +++ b/agent/deferred_test.go @@ -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) } } diff --git a/agent/goals.go b/agent/goals.go index 004f6ac81..01bcb11e4 100644 --- a/agent/goals.go +++ b/agent/goals.go @@ -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, diff --git a/agent/goals_contract_test.go b/agent/goals_contract_test.go index cc26b30ce..e45808ba4 100644 --- a/agent/goals_contract_test.go +++ b/agent/goals_contract_test.go @@ -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) { diff --git a/agent/skill_index_test.go b/agent/skill_index_test.go index f6b6bf2c8..e77db6e8e 100644 --- a/agent/skill_index_test.go +++ b/agent/skill_index_test.go @@ -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) } } diff --git a/docs/context-telemetry.md b/docs/context-telemetry.md index 86974e58d..15cece26e 100644 --- a/docs/context-telemetry.md +++ b/docs/context-telemetry.md @@ -32,7 +32,7 @@ Every enabled `Stream` and `Complete` call measures the assembled `llm.Completio - `norma`'s `CompletionRequest.System` is a slice of segments that `llm.joinSystem` trims (`strings.TrimSpace`), drops when empty, and joins with blank lines (`"\n\n"`). `MeasureContext` applies the exact same trim, drop-empty, and `"\n\n"` join rules per slice. - When `DynamicBoundary > 0`, `System` is split at `b = min(DynamicBoundary, len(System))`: `System[:b]` is measured into `system_static_bytes` and `System[b:]` into `system_dynamic_bytes`. - When `DynamicBoundary <= 0`, there is no provider-visible cache split, so the entire `System` slice is measured as one block in `system_static_bytes` and `system_dynamic_bytes` is `0`. - - **Why this choice**: `agent/deferred.go` returns `boundary = 0` when no global deferred-MCP block exists and `boundary = len(system)` when one does. Placing the single unsplit block in `system_static_bytes` ensures `system_static_bytes + system_dynamic_bytes` always equals total system bytes and `system_dynamic_bytes > 0` strictly signals a dynamic suffix placed after a cache breakpoint. + - **Why this choice**: placing the single unsplit block in `system_static_bytes` ensures `system_static_bytes + system_dynamic_bytes` always equals total system bytes, and `system_dynamic_bytes` measures only what sits after a cache breakpoint. The boundary covers all of the agent's segments (`agent/deferred.go` sets `len(system)`; the goal decomposer sets 1 for its single segment). The planner, worker, chat and main agent turn on the untrusted-output boundary (on by default), so their one segment after it is the constant note `norma` appends (about 270 bytes); the goal decomposer does not, so its `system_dynamic_bytes` is 0. The opt-in `ARTEX_CACHE_PREFIX` worker split also moves the per-intent tail after the boundary. - **`tool_count` & `tools_bytes`**: `len(req.Tools)` and `len(json.Marshal(req.Tools))` (`0` when no tools). Go's `encoding/json` sorts map keys deterministically. - **`message_count`, `messages_user_bytes`, `messages_assistant_bytes`, `messages_other_bytes`, `last_message_bytes`**: each `llm.Message` is measured by `len(json.Marshal(msg))` and accumulated by role (`user`, `assistant`, or other); `last_message_bytes` is the serialized byte size of the final message. - **`tool_result_bytes`**: serialized byte length of `tool_result` content blocks inside messages. Reported as an **informational subset** of `messages_user_bytes` (not added to the partition denominator, avoiding double counting). @@ -122,7 +122,7 @@ ORDER BY input_tokens DESC; - **Recommendation: Proceed with a surgical `worker` prefix split (`ARTEX_CACHE_PREFIX`); verify `planner` cross-round cache behavior and `ARTEX_COMPACTION_MEMO` with live `ARTEX_CONTEXT_TELEMETRY=1` data before changing them.** - **Actual system-prompt volatility by lane (built-in prompts)**: - `system_dynamic` is **0.0%** across all lanes today because `agent/deferred.go` sets `DynamicBoundary = 0` (no global deferred MCP) or `len(system)` (everything before the boundary). Auditing the built-in templates and assembly in `agent/worker.go` and `agent/planner.go` shows what actually varies: + In production `system_dynamic` holds only the constant untrusted-output note (about 270 bytes, on the lanes that turn that boundary on), because `agent/deferred.go` always sets `DynamicBoundary = len(system)`; the opt-in `ARTEX_CACHE_PREFIX` worker split sets it to 1 and moves the per-intent tail after it. The 0.0% in the table comes from the representative fixture (`TestLLMContextRepresentativeFixtureReport`), which does not model `system_dynamic`. Auditing the built-in templates and assembly in `agent/worker.go` and `agent/planner.go` shows what actually varies: | Lane | Stable per task | Volatile per intent / round | |---|---|---|