diff --git a/ai_prompt.go b/ai_prompt.go index b9d6205..1101eaf 100644 --- a/ai_prompt.go +++ b/ai_prompt.go @@ -158,11 +158,24 @@ func aiCatalogPromptSection(catalog []aiCatalogEntry) string { return b.String() } -// aiVolatileSystem is the post-breakpoint tail: everything here may change -// between requests without touching the cached prefix. +// aiVolatileSystem is the post-breakpoint tail of the system prompt. The +// session renders it ONCE, at the start of the conversation, and resends it +// byte-identical on every request: models with preserved thinking (Opus 5.5, +// Fable 5.x) sign each thinking block against the top-level system prompt, so +// editing it mid-conversation invalidates every earlier thinking block and +// the next request fails with HTTP 400. Later changes to these facts (a +// customer switch, a re-login) reach the model as appended messages instead โ€” +// see localAISession.composeUserMessageLocked. func aiVolatileSystem(configDir string, now time.Time, customerOverride string) string { + return fmt.Sprintf("Today's date: %s.\n", now.Format("2006-01-02")) + aiSessionContextLines(configDir, customerOverride) +} + +// aiSessionContextLines is the part of the volatile tail that can change +// during a session: the active customer context and the signed-in identity. +// The session compares it before each question to detect a change it must +// announce in the conversation. +func aiSessionContextLines(configDir string, customerOverride string) string { var b strings.Builder - fmt.Fprintf(&b, "Today's date: %s.\n", now.Format("2006-01-02")) switch context := readCustomerContext(configDir); { case customerOverride != "": // The agent's own session-scoped switch (set_customer_context) wins diff --git a/ai_session.go b/ai_session.go index c6ac84d..386a94e 100644 --- a/ai_session.go +++ b/ai_session.go @@ -29,7 +29,7 @@ import ( const ( aiSettingsFileName = "ai_settings.json" - aiDefaultModel = "claude-opus-5" + aiDefaultModel = "claude-opus-5-5" aiMaxToolRounds = 16 // aiMaxOutputTokens bounds one API turn. Adaptive thinking counts against // max_tokens: analytical questions (aggregating a 200-row result) have @@ -46,10 +46,10 @@ const ( // aiKnownModels is the selectable set shown by /model. Other claude-* ids are // accepted with a warning โ€” the API is the final validator. var aiKnownModels = []string{ - "claude-opus-5", - "claude-sonnet-5", - "claude-opus-4-8", - "claude-haiku-4-5", + "claude-opus-5-5", + "claude-fable-5-2", + "claude-sonnet-5-5", + "claude-haiku-5-5", } type aiSettings struct { @@ -242,13 +242,19 @@ type localAISession struct { approvals chan aiUserInput done chan struct{} // closed by Close; emit drains against it - mu sync.Mutex - history []anthropic.MessageParam - pending []string // injected slash results, consumed by the next question - running bool - cancel context.CancelFunc - turnSeq int - closed bool + mu sync.Mutex + // systemTail is the volatile system block, frozen at the conversation's + // first request (see aiVolatileSystem for why it must never change), and + // announcedContext is the context the model was last told about โ€” in + // systemTail, a set_customer_context result, or an appended update. + systemTail string + announcedContext string + history []anthropic.MessageParam + pending []string // injected slash results, consumed by the next question + running bool + cancel context.CancelFunc + turnSeq int + closed bool } // errAITurnRunning is returned by Send(chat) while a turn is in flight. @@ -407,8 +413,31 @@ func aiCommandResultContext(input aiUserInput) string { return b.String() } +// freezeSystemTailLocked renders the volatile system block on first use and +// keeps it for the rest of the conversation. +func (s *localAISession) freezeSystemTailLocked() { + if s.systemTail != "" { + return + } + override := s.executor.CustomerOverride() + s.systemTail = aiVolatileSystem(s.configDir, time.Now(), override) + s.announcedContext = aiSessionContextLines(s.configDir, override) +} + func (s *localAISession) composeUserMessageLocked(question string) anthropic.MessageParam { - blocks := make([]anthropic.ContentBlockParamUnion, 0, len(s.pending)+1) + blocks := make([]anthropic.ContentBlockParamUnion, 0, len(s.pending)+2) + if s.systemTail == "" { + s.freezeSystemTailLocked() + } else if current := aiSessionContextLines(s.configDir, s.executor.CustomerOverride()); current != s.announcedContext { + // The context changed outside the agent's own tool call (/customer, + // a re-login): the frozen system prompt is now stale, so the update + // rides in the conversation, appended where it became true. + if current == "" { + current = "No customer context is active.\n" + } + blocks = append(blocks, anthropic.NewTextBlock("Session context update (supersedes the context in the system prompt):\n"+current)) + s.announcedContext = aiSessionContextLines(s.configDir, s.executor.CustomerOverride()) + } for _, injected := range s.pending { blocks = append(blocks, anthropic.NewTextBlock(injected)) } @@ -459,11 +488,13 @@ func (s *localAISession) tools() []anthropic.ToolUnionParam { func (s *localAISession) params() anthropic.MessageNewParams { s.mu.Lock() + s.freezeSystemTailLocked() history := append([]anthropic.MessageParam{}, s.history...) model := s.model + tail := s.systemTail s.mu.Unlock() stable := anthropic.TextBlockParam{Text: s.stablePrompt, CacheControl: anthropic.NewCacheControlEphemeralParam()} - volatile := anthropic.TextBlockParam{Text: aiVolatileSystem(s.configDir, time.Now(), s.executor.CustomerOverride())} + volatile := anthropic.TextBlockParam{Text: tail} params := anthropic.MessageNewParams{ Model: anthropic.Model(model), MaxTokens: aiMaxOutputTokens, @@ -760,6 +791,11 @@ func (s *localAISession) executeSerialToolCall(turnID string, toolUse anthropic. started := time.Now() from, to, outcome := s.executor.SetCustomer(input) if !outcome.IsError { + // The tool result below is how the model learns the new tenant + // (the system prompt stays frozen), so record it as announced. + s.mu.Lock() + s.announcedContext = aiSessionContextLines(s.configDir, s.executor.CustomerOverride()) + s.mu.Unlock() s.emit(aiEvent{ContextSwitched: &aiContextSwitched{From: from, To: to, By: "agent"}}) } s.emit(aiEvent{ToolResult: &aiToolResult{ diff --git a/ai_session_test.go b/ai_session_test.go index a27d066..fb785e1 100644 --- a/ai_session_test.go +++ b/ai_session_test.go @@ -3,6 +3,7 @@ package main import ( "context" "encoding/json" + "os" "strings" "sync/atomic" "testing" @@ -606,11 +607,11 @@ func TestAISessionParamsLayout(t *testing.T) { func TestAISettingsRoundTripAndResolution(t *testing.T) { dir := t.TempDir() - if err := saveAISettings(dir, aiSettings{APIKey: "sk-test", Model: "claude-sonnet-5"}); err != nil { + if err := saveAISettings(dir, aiSettings{APIKey: "sk-test", Model: "claude-sonnet-5-5"}); err != nil { t.Fatal(err) } loaded := loadAISettings(dir) - if loaded.APIKey != "sk-test" || loaded.Model != "claude-sonnet-5" { + if loaded.APIKey != "sk-test" || loaded.Model != "claude-sonnet-5-5" { t.Fatalf("loaded = %+v", loaded) } t.Setenv("ANTHROPIC_API_KEY", "sk-env") @@ -627,7 +628,7 @@ func TestAISettingsRoundTripAndResolution(t *testing.T) { if err := aiValidateModel("gpt-4"); err == nil { t.Fatal("non-claude model accepted") } - if err := aiValidateModel("claude-opus-5"); err != nil { + if err := aiValidateModel("claude-opus-5-5"); err != nil { t.Fatal(err) } } @@ -659,8 +660,75 @@ func TestResolveAIEffortAndModelOverrides(t *testing.T) { t.Fatalf("env default must win over settings, got %q", got) } t.Setenv("DCI_AI_EFFORT", "") - t.Setenv("DCI_AI_MODEL", "claude-sonnet-5") - if got := resolveAIModel(aiSettings{Model: "claude-opus-5"}); got != "claude-sonnet-5" { + t.Setenv("DCI_AI_MODEL", "claude-sonnet-5-5") + if got := resolveAIModel(aiSettings{Model: "claude-opus-5-5"}); got != "claude-sonnet-5-5" { t.Fatalf("model env must win, got %q", got) } } + +// TestAISessionSystemPromptStableAcrossCustomerSwitch is the regression for +// preserved thinking's prefix check: Opus 5.5 / Fable 5.x sign each thinking +// block against the top-level system prompt, so a system prompt that changes +// after set_customer_context (or /customer) makes the next request a 400. The +// system blocks must stay byte-identical for the whole conversation; the new +// tenant reaches the model through the tool result or an appended message. +func TestAISessionSystemPromptStableAcrossCustomerSwitch(t *testing.T) { + var captured []anthropic.MessageNewParams + turns := []string{ + aiTestToolUseTurn(aiTestSwitchBlock("call-1", "acme.com")), + aiTestTextTurn, + aiTestTextTurn, + } + session := newTestSession(t, turns, &scriptedRunner{}) + session.tenantAware = true + scripted := session.streamer + session.streamer = func(ctx context.Context, params anthropic.MessageNewParams, onDelta, onThinking func(string)) (anthropic.Message, error) { + captured = append(captured, params) + return scripted(ctx, params, onDelta, onThinking) + } + + if err := session.Send(aiUserInput{Kind: aiInputChat, Text: "switch to acme"}); err != nil { + t.Fatal(err) + } + collectTurnEvents(t, session) + // The user then persists a different context with /customer. + if err := os.WriteFile(customerContextPath(session.configDir), []byte("globex.com\n"), 0o600); err != nil { + t.Fatal(err) + } + session.ClearCustomerOverride() + if err := session.Send(aiUserInput{Kind: aiInputChat, Text: "and now?"}); err != nil { + t.Fatal(err) + } + collectTurnEvents(t, session) + + if len(captured) != 3 { + t.Fatalf("captured %d requests, want 3", len(captured)) + } + first, _ := json.Marshal(captured[0].System) + for i, params := range captured[1:] { + if got, _ := json.Marshal(params.System); string(got) != string(first) { + t.Fatalf("request %d changed the system prompt:\nfirst: %s\nlater: %s", i+2, first, got) + } + } + if strings.Contains(string(first), "acme.com") || strings.Contains(string(first), "globex.com") { + t.Fatalf("frozen system prompt names a later context: %s", first) + } + + // The agent's switch is reported in its tool result. + toolResult, _ := json.Marshal(captured[1].Messages[2]) + if !strings.Contains(string(toolResult), "acme.com") { + t.Fatalf("tool result does not name the new customer: %s", toolResult) + } + // The /customer change is appended to the next user message. + last := captured[2].Messages[len(captured[2].Messages)-1] + encoded, _ := json.Marshal(last) + if !strings.Contains(string(encoded), "Session context update") || !strings.Contains(string(encoded), "globex.com") { + t.Fatalf("next user message does not announce the /customer change: %s", encoded) + } + // Earlier history is untouched (append-only). + before, _ := json.Marshal(captured[1].Messages) + after, _ := json.Marshal(captured[2].Messages[:len(captured[1].Messages)]) + if string(before) != string(after) { + t.Fatal("history before the new question was rewritten") + } +} diff --git a/ai_tools.go b/ai_tools.go index eb44caf..fc6b703 100644 --- a/ai_tools.go +++ b/ai_tools.go @@ -380,7 +380,10 @@ func (e *aiToolExecutor) SetCustomer(input aiSetCustomerInput) (from, to string, e.mu.Lock() e.customerOverride = token e.mu.Unlock() - return from, token, aiToolOutcome{Data: fmt.Sprintf("customer context switched from %q to %q for this session (the saved context is unchanged)", from, token)} + // The result is the model's only notice of the switch: the system prompt + // is frozen for the conversation (aiVolatileSystem), so say that the new + // tenant supersedes the one it names. + return from, token, aiToolOutcome{Data: fmt.Sprintf("customer context switched from %q to %q for this session (the saved context is unchanged). Active customer context is now %s; this supersedes the context in the system prompt.", from, token, token)} } // aiCapToolResult bounds one tool result entering model context (ยง7.6), diff --git a/ai_tui_test.go b/ai_tui_test.go index b8ae85b..68016dd 100644 --- a/ai_tui_test.go +++ b/ai_tui_test.go @@ -570,22 +570,22 @@ func TestAIContextSwitchEventRefreshesIdentity(t *testing.T) { func TestAIModelVerb(t *testing.T) { m := aiTestModel(t) - m = aiType(m, "/model claude-sonnet-5") + m = aiType(m, "/model claude-sonnet-5-5") updated, _ := aiPress(m, tea.KeyEnter) m = updated - if !strings.Contains(aiTranscriptText(m), "Model set to claude-sonnet-5") { + if !strings.Contains(aiTranscriptText(m), "Model set to claude-sonnet-5-5") { t.Fatal("/model confirmation missing from the transcript") } - if m.modelName != "claude-sonnet-5" { + if m.modelName != "claude-sonnet-5-5" { t.Fatalf("modelName = %q", m.modelName) } - if got := loadAISettings(m.configDir).Model; got != "claude-sonnet-5" { + if got := loadAISettings(m.configDir).Model; got != "claude-sonnet-5-5" { t.Fatalf("persisted model = %q", got) } m = aiType(m, "/model gpt-4") updated, _ = aiPress(m, tea.KeyEnter) m = updated - if m.modelName != "claude-sonnet-5" { + if m.modelName != "claude-sonnet-5-5" { t.Fatalf("invalid model applied: %q", m.modelName) } }