gateway: a masked request tells the model its placeholders are used as written (treeMan)
treeMan on Discord: with masking on, weaker models refuse to search
with a {{NAME_xxxxxxxx}} placeholder, ask to verify it, or rewrite it as
"an example name", which breaks long tasks. A request in which masking
swapped a value (maskHits.n > 0) now carries one short note, on each try:
Values written like {{NAME_ab12cd34}} are placeholders for real values.
Use them exactly as written, in replies and in tool calls alike: they
are filled in with the real values before anything runs. Don't ask to
verify them, and don't replace them with examples.
It names neither magpie nor a vendor or client (TestPlaceholderNoteIsNeutral
fails on magpie, Codex, Claude, a vendor's name, "provider", "gateway"...).
Its example uses a '1', outside the placeholder alphabet, so it is never
taken for a real placeholder or restored.
Where: where placeholders first appear, so it is new text the first time
and the same text on every later turn (the cached prefix holds). In the
instructions when they or the tools hold one (Anthropic system's last
block, Chat's first system/developer message, Gemini systemInstruction's
parts); otherwise on the earliest message that holds one, as a block or
part after its content (a string content becomes [text, note] blocks on
Anthropic, a paragraph on Chat), and on Responses as a developer message
after that item and the tool outputs following it. Responses
`instructions` (Codex's base_instructions) is never touched. A note
appended after text starts with a blank line, so a translator that joins
blocks (Anthropic to Chat) keeps it apart from the user's words.
Not added:
- a Claude subscription: the bridge puts the caller's instructions into
the run's first message, which Anthropic classifies; text added there is
risk for no gain;
- a ChatGPT/Codex sign-in (Account.Agent codex); Codex's own turns on
codexUpstreamOn don't pass this loop either;
- a Responses turn with previous_response_id: the note would pile up in
the stored conversation.
count_tokens counts without it.
A first version put the note in the system prompt. The full suite showed
TestMaskedConversationKeepsItsCachedPrefix red (a secret first found in a
tool output changed the system at turn 1 and rewrote the cache), hence
the first-appearance placement.
Run (mote, through mote-run):
- go test ./internal/gateway ./internal/redact -run
'TestPlaceholderNote|TestMaskedRequestTold|TestMaskedConversation|
TestUnredacted|TestRedacted|TestMask|TestMiddlewareThroughGateway': ok.
- Full suite at 46bdbad8f (-timeout 45m, log kept whole): red in
internal/gateway TestMiddlewareThroughGateway (mine: its fake echoes the
last message, which now holds the note; the fake strips it now), and
five tests red alone on origin/main cc81ad4ea too, filed as #4362
(TestAntigravityTurnsCodexsGPT5ThreadAwayOnce, TestAntigravityTurnedAway*,
TestCodexSpentGrokFailingIsTold); internal/gui TestMainWindowCorners
(#3949). Every other package ok.
- At 79c6a487c (this change on cc81ad4ea): go test -timeout 45m
./internal/gateway ./internal/redact ./internal/masking/...: redact and
masking ok; gateway red only in the five #4362 tests.
- go vet ./internal/gateway ./internal/redact on macOS, CGO_ENABLED=0
GOOS=windows go vet ./... on mote, go vet of both in WSL (Linux): ok.
(CGO_ENABLED=0 GOOS=linux go vet ./... stops in wails' menu_linux.go on
main too, so Linux was vetted natively.)
Broken by hand:
- note always in Anthropic's system (`if true ||`):
TestMaskedConversationKeepsItsCachedPrefix, TestPlaceholderNotePlaces,
TestMaskedRequestTold and the TestUnredacted* echo tests red.
- wiring off in serve: TestMaskedRequestTold red.
- the claude/previous_response_id skips removed:
TestPlaceholderNoteNotOnClientPaths red.
Not tried: no real vendor or weak model was run with the note, so whether
it stops the refusals treeMan saw is not measured; no real Claude
subscription or Codex sign-in request (both skipped by design).
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -2804,6 +2804,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
}
|
||||
// a middleware's onProvider changes what this provider is sent
|
||||
attemptBody = triedOn(r.Context(), c.p, c.model, attemptBody)
|
||||
// a value masking swapped for a placeholder: the model is told to
|
||||
// use it as written (treeMan on Discord). A conversation's values
|
||||
// are masked again on every turn, so once one is, every later
|
||||
// turn is told the same, and its cached prefix holds
|
||||
if maskedHits.n > 0 && notesPlaceholders(c.p, from, attemptBody) {
|
||||
attemptBody = withPlaceholderNote(from, attemptBody)
|
||||
}
|
||||
if hint := s.antigravityForeseen(c.p, from, attemptBody); !last && hint != "" {
|
||||
// Antigravity would only turn it away, as it did lately, and
|
||||
// someone after it may answer: it isn't asked, and nothing is
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
@@ -39,6 +40,9 @@ func TestMiddlewareThroughGateway(t *testing.T) {
|
||||
}
|
||||
json.Unmarshal(got, &sent)
|
||||
last, _ := json.Marshal(sent.Messages[len(sent.Messages)-1].Content)
|
||||
// the note on the masked message is the gateway's, not the agent's
|
||||
note, _ := json.Marshal(noteBlock)
|
||||
last = bytes.Replace(last, bytes.Trim(note, `"`), nil, 1)
|
||||
io.WriteString(w, sse(chunk("hello "), chunk(string(last)), `data: {"id":"c1","model":"m1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2}}`, "data: [DONE]"))
|
||||
}))
|
||||
defer up.Close()
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/redact"
|
||||
)
|
||||
|
||||
// placeholderNote tells a model that the placeholders masking put in a
|
||||
// request stand for real values that are put back before anything runs,
|
||||
// so it uses them as written: a less able model refused to search with
|
||||
// one, asked to verify it, or wrote it as "an example name" (treeMan on
|
||||
// Discord). It goes to the vendor, so it names neither magpie nor any
|
||||
// vendor or client (LESSONS: text magpie adds to a prompt), and it is the
|
||||
// same on every turn, so a cached prefix stays cached. Its example isn't
|
||||
// a placeholder masking writes (a 1 isn't in its alphabet), so it is
|
||||
// never taken for one or put back.
|
||||
const placeholderNote = "Values written like {{NAME_ab12cd34}} are placeholders for real values. " +
|
||||
"Use them exactly as written, in replies and in tool calls alike: they are filled in with the real values before anything runs. " +
|
||||
"Don't ask to verify them, and don't replace them with examples."
|
||||
|
||||
// noteBlock is placeholderNote as a block or part after the text it
|
||||
// follows: a translator that joins a message's blocks into one string
|
||||
// (Anthropic or Gemini to Chat) keeps it a paragraph of its own.
|
||||
const noteBlock = "\n\n" + placeholderNote
|
||||
|
||||
// notesPlaceholders says whether a request masked with a value swapped
|
||||
// for a placeholder is told so (placeholderNote) on its way to p. Not on
|
||||
// two paths, where the request is to look as its own client sent it:
|
||||
// - a Claude subscription, run through the Claude Code binary, which
|
||||
// puts the caller's instructions in the run's first message, the
|
||||
// content Anthropic classifies (claude-subscription-bridge.md);
|
||||
// - Codex's ChatGPT sign-in, whose instructions are Codex's own
|
||||
// base_instructions and are never changed.
|
||||
//
|
||||
// Nor a Responses turn that goes on from a stored response: its input is
|
||||
// only the new items, and the note, said each turn, would pile up in the
|
||||
// stored conversation.
|
||||
func notesPlaceholders(p provider.Provider, from provider.Protocol, body []byte) bool {
|
||||
if p.Account != nil && (p.Account.Agent == "claude" || p.Account.Agent == "codex") {
|
||||
return false
|
||||
}
|
||||
if from == provider.Responses && gjson.GetBytes(body, "previous_response_id").String() != "" {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// withPlaceholderNote is body with placeholderNote said where its
|
||||
// placeholders first appear, so the conversation before that point goes
|
||||
// as it went and its cached prefix holds (TestMaskedConversationKeeps-
|
||||
// ItsCachedPrefix): a value is masked first in new text, a tool's output
|
||||
// halfway through a task, and the text sent before it is sent again as
|
||||
// it went. A system prompt or tools with one has it from the first turn,
|
||||
// and is told in the instructions: the last block of Anthropic's system,
|
||||
// the end of Chat's first system (or developer) message, a part after
|
||||
// Gemini's systemInstruction's. Otherwise the earliest message with one
|
||||
// says it, after what it has: a text block or part of its own, or a line
|
||||
// at the end of a message that is one string. Responses' instructions are
|
||||
// never changed (Codex's base_instructions): a developer message of its
|
||||
// own goes first in its input, or after the earliest item with one and
|
||||
// the tool outputs beside it. On a later turn the same message is the
|
||||
// earliest, told the same, so the note never moves. A body it can't read,
|
||||
// or with no placeholder or no place for it, is returned as it is; the
|
||||
// edit is made in place in the bytes, the rest as the client wrote it.
|
||||
func withPlaceholderNote(from provider.Protocol, body []byte) []byte {
|
||||
if !gjson.ValidBytes(body) || !gjson.ParseBytes(body).IsObject() || !redact.HasPlaceholder(string(body)) {
|
||||
return body
|
||||
}
|
||||
switch from {
|
||||
case provider.Anthropic:
|
||||
return withNoteAnthropic(body)
|
||||
case provider.Chat:
|
||||
return withNoteChat(body)
|
||||
case provider.Responses:
|
||||
return withNoteResponses(body)
|
||||
case provider.Gemini:
|
||||
return withNoteGemini(body)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// holds says whether r's text has a placeholder.
|
||||
func holdsPlaceholder(r gjson.Result) bool { return r.Exists() && redact.HasPlaceholder(r.Raw) }
|
||||
|
||||
// earliest is the index of the first element of the array r with a
|
||||
// placeholder, -1 for none.
|
||||
func earliest(r gjson.Result) int {
|
||||
for i, e := range r.Array() {
|
||||
if holdsPlaceholder(e) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func withNoteAnthropic(body []byte) []byte {
|
||||
s := gjson.GetBytes(body, "system")
|
||||
if holdsPlaceholder(s) || holdsPlaceholder(gjson.GetBytes(body, "tools")) {
|
||||
switch {
|
||||
case !s.Exists():
|
||||
return withTopField(body, "system", noteQuoted(placeholderNote))
|
||||
case s.Type == gjson.Null:
|
||||
return spliced(body, s, noteQuoted(placeholderNote))
|
||||
case s.Type == gjson.String:
|
||||
return spliced(body, s, noteQuoted(withLine(s.String(), placeholderNote)))
|
||||
case s.IsArray():
|
||||
return appended(body, s, textPart("text"))
|
||||
}
|
||||
return body
|
||||
}
|
||||
i := earliest(gjson.GetBytes(body, "messages"))
|
||||
if i < 0 {
|
||||
return body
|
||||
}
|
||||
c := gjson.GetBytes(body, "messages."+strconv.Itoa(i)+".content")
|
||||
switch {
|
||||
case c.Type == gjson.String:
|
||||
blocks := noteJSON([]any{map[string]any{"type": "text", "text": c.String()}, map[string]any{"type": "text", "text": noteBlock}})
|
||||
return spliced(body, c, blocks)
|
||||
case c.IsArray():
|
||||
return appended(body, c, textPart("text"))
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func withNoteChat(body []byte) []byte {
|
||||
msgs := gjson.GetBytes(body, "messages")
|
||||
if !msgs.IsArray() {
|
||||
return body
|
||||
}
|
||||
i := earliest(msgs)
|
||||
if holdsPlaceholder(gjson.GetBytes(body, "tools")) || i >= 0 && isSystemRole(msgs.Array()[i]) {
|
||||
// the instructions: the first system message, or one of their own
|
||||
i = -1
|
||||
for j, m := range msgs.Array() {
|
||||
if isSystemRole(m) {
|
||||
i = j
|
||||
break
|
||||
}
|
||||
}
|
||||
if i < 0 {
|
||||
return prepended(body, msgs, noteJSON(map[string]any{"role": "system", "content": placeholderNote}))
|
||||
}
|
||||
}
|
||||
if i < 0 {
|
||||
return body
|
||||
}
|
||||
c := gjson.GetBytes(body, "messages."+strconv.Itoa(i)+".content")
|
||||
switch {
|
||||
case c.Type == gjson.String:
|
||||
return spliced(body, c, noteQuoted(withLine(c.String(), placeholderNote)))
|
||||
case c.IsArray():
|
||||
return appended(body, c, textPart("text"))
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func isSystemRole(m gjson.Result) bool {
|
||||
role := m.Get("role").String()
|
||||
return role == "system" || role == "developer"
|
||||
}
|
||||
|
||||
func withNoteResponses(body []byte) []byte {
|
||||
in := gjson.GetBytes(body, "input")
|
||||
dev := noteJSON(map[string]any{"type": "message", "role": "developer", "content": []any{map[string]any{"type": "input_text", "text": placeholderNote}}})
|
||||
if in.Type == gjson.String {
|
||||
user := noteJSON(map[string]any{"role": "user", "content": in.String()})
|
||||
return spliced(body, in, []byte("["+string(dev)+","+string(user)+"]"))
|
||||
}
|
||||
if !in.IsArray() {
|
||||
return body
|
||||
}
|
||||
if holdsPlaceholder(gjson.GetBytes(body, "instructions")) || holdsPlaceholder(gjson.GetBytes(body, "tools")) {
|
||||
return prepended(body, in, dev)
|
||||
}
|
||||
items := in.Array()
|
||||
i := earliest(in)
|
||||
if i < 0 {
|
||||
return body
|
||||
}
|
||||
// after the outputs beside it: a call's run of outputs stays whole
|
||||
for i+1 < len(items) && strings.HasSuffix(items[i+1].Get("type").String(), "_call_output") {
|
||||
i++
|
||||
}
|
||||
last := gjson.GetBytes(body, "input."+strconv.Itoa(i))
|
||||
if !at(body, last) {
|
||||
return body
|
||||
}
|
||||
return insertAt(body, last.Index+len(last.Raw), ","+string(dev))
|
||||
}
|
||||
|
||||
func withNoteGemini(body []byte) []byte {
|
||||
for _, key := range []string{"systemInstruction", "system_instruction"} {
|
||||
si := gjson.GetBytes(body, key)
|
||||
if !si.Exists() || si.Type == gjson.Null {
|
||||
continue
|
||||
}
|
||||
if !holdsPlaceholder(si) && !holdsPlaceholder(gjson.GetBytes(body, "tools")) {
|
||||
break
|
||||
}
|
||||
if parts := gjson.GetBytes(body, key+".parts"); parts.IsArray() {
|
||||
return appended(body, parts, noteJSON(map[string]any{"text": noteBlock}))
|
||||
}
|
||||
return body
|
||||
}
|
||||
text := noteJSON(map[string]any{"text": noteBlock})
|
||||
if holdsPlaceholder(gjson.GetBytes(body, "tools")) {
|
||||
return withTopField(body, "systemInstruction", noteJSON(map[string]any{"parts": []any{map[string]any{"text": placeholderNote}}}))
|
||||
}
|
||||
i := earliest(gjson.GetBytes(body, "contents"))
|
||||
if i < 0 {
|
||||
return body
|
||||
}
|
||||
if parts := gjson.GetBytes(body, "contents."+strconv.Itoa(i)+".parts"); parts.IsArray() {
|
||||
return appended(body, parts, text)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// textPart is placeholderNote as a content part of the given type.
|
||||
func textPart(typ string) []byte {
|
||||
return noteJSON(map[string]any{"type": typ, "text": noteBlock})
|
||||
}
|
||||
|
||||
// quoted is s as a JSON string, <, > and & as written.
|
||||
func noteQuoted(s string) []byte { return noteJSON(s) }
|
||||
|
||||
func noteJSON(v any) []byte {
|
||||
var b bytes.Buffer
|
||||
enc := json.NewEncoder(&b)
|
||||
enc.SetEscapeHTML(false)
|
||||
_ = enc.Encode(v)
|
||||
return bytes.TrimSuffix(b.Bytes(), []byte("\n"))
|
||||
}
|
||||
|
||||
// at says whether r's raw text is where its Index says in body: gjson
|
||||
// sets no Index for a value it can't place.
|
||||
func at(body []byte, r gjson.Result) bool {
|
||||
return r.Index > 0 && r.Index+len(r.Raw) <= len(body) && string(body[r.Index:r.Index+len(r.Raw)]) == r.Raw
|
||||
}
|
||||
|
||||
// spliced is body with r's value replaced by v.
|
||||
func spliced(body []byte, r gjson.Result, v []byte) []byte {
|
||||
if !at(body, r) {
|
||||
return body
|
||||
}
|
||||
out := make([]byte, 0, len(body)+len(v))
|
||||
out = append(out, body[:r.Index]...)
|
||||
out = append(out, v...)
|
||||
return append(out, body[r.Index+len(r.Raw):]...)
|
||||
}
|
||||
|
||||
// appended is body with item added at the end of the array r.
|
||||
func appended(body []byte, r gjson.Result, item []byte) []byte {
|
||||
if !at(body, r) {
|
||||
return body
|
||||
}
|
||||
end := r.Index + len(r.Raw) - 1 // its ]
|
||||
sep := ","
|
||||
if len(r.Array()) == 0 {
|
||||
sep = ""
|
||||
}
|
||||
return insertAt(body, end, sep+string(item))
|
||||
}
|
||||
|
||||
// prepended is body with item put first in the array r.
|
||||
func prepended(body []byte, r gjson.Result, item []byte) []byte {
|
||||
if !at(body, r) {
|
||||
return body
|
||||
}
|
||||
sep := ","
|
||||
if len(r.Array()) == 0 {
|
||||
sep = ""
|
||||
}
|
||||
return insertAt(body, r.Index+1, string(item)+sep)
|
||||
}
|
||||
|
||||
// withTopField is the object body with a field it doesn't have added
|
||||
// first.
|
||||
func withTopField(body []byte, key string, v []byte) []byte {
|
||||
i := bytes.IndexByte(body, '{')
|
||||
if i < 0 {
|
||||
return body
|
||||
}
|
||||
sep := ","
|
||||
if len(gjson.ParseBytes(body).Map()) == 0 {
|
||||
sep = ""
|
||||
}
|
||||
return insertAt(body, i+1, string(noteQuoted(key))+":"+string(v)+sep)
|
||||
}
|
||||
|
||||
func insertAt(body []byte, i int, s string) []byte {
|
||||
out := make([]byte, 0, len(body)+len(s))
|
||||
out = append(out, body[:i]...)
|
||||
out = append(out, s...)
|
||||
return append(out, body[i:]...)
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/redact"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// The note goes to the vendor: it names neither magpie, nor a vendor, nor
|
||||
// a client (LESSONS: text magpie adds to a prompt), and its example is no
|
||||
// placeholder masking writes, so it is never put back as one.
|
||||
func TestPlaceholderNoteIsNeutral(t *testing.T) {
|
||||
low := strings.ToLower(placeholderNote)
|
||||
for _, w := range []string{"magpie", "codex", "claude", "anthropic", "openai", "chatgpt", "gpt", "gemini", "google", "deepseek", "kimi", "qwen", "grok", "vendor", "provider", "gateway", "redact", "privacy", "proxy"} {
|
||||
if strings.Contains(low, w) {
|
||||
t.Errorf("the note names %q: %s", w, placeholderNote)
|
||||
}
|
||||
}
|
||||
ex := regexp.MustCompile(`\{\{[^}]*\}\}`).FindString(placeholderNote)
|
||||
if ex == "" {
|
||||
t.Fatal("the note shows no placeholder's form")
|
||||
}
|
||||
if regexp.MustCompile(`\{\{[A-Z][A-Z0-9_]*_[a-z2-7]{8}\}\}`).MatchString(ex) {
|
||||
t.Errorf("the note's example %s is a placeholder masking could write", ex)
|
||||
}
|
||||
if got := redact.Restore(placeholderNote, false); got != placeholderNote {
|
||||
t.Errorf("the note is changed when values are put back: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Each API's body is told where its placeholders first appear: in the
|
||||
// instructions when they or the tools hold one, else on the earliest
|
||||
// message that does, after what it has, the bytes before it kept as the
|
||||
// client wrote them; Responses' instructions are never touched.
|
||||
func TestPlaceholderNotePlaces(t *testing.T) {
|
||||
const ph = "{{EMAIL_abcdefgh}}"
|
||||
cases := []struct {
|
||||
name string
|
||||
from provider.Protocol
|
||||
body string
|
||||
where string // gjson path of the note's text
|
||||
keep string // gjson path whose raw stays as it was
|
||||
}{
|
||||
{"anthropic system string", provider.Anthropic, `{"model":"m","system":"Mail ` + ph + `.","messages":[{"role":"user","content":"hi"}]}`, "system", "messages"},
|
||||
{"anthropic system blocks", provider.Anthropic, `{"model":"m","system":[{"type":"text","text":"a"},{"type":"text","text":"b ` + ph + `","cache_control":{"type":"ephemeral"}}],"messages":[]}`, "system.2.text", "system.1"},
|
||||
{"anthropic tools", provider.Anthropic, `{"model":"m","tools":[{"name":"t","description":"` + ph + `"}],"messages":[{"role":"user","content":"x"}]}`, "system", "messages"},
|
||||
{"anthropic message", provider.Anthropic, `{"model":"m","system":"S","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"ok"},{"role":"user","content":"mail ` + ph + `"}]}`, "messages.2.content.1.text", "messages.1"},
|
||||
{"anthropic tool result", provider.Anthropic, `{"model":"m","system":"S","messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"` + ph + `"}]}]}`, "messages.0.content.1.text", "system"},
|
||||
{"chat system", provider.Chat, `{"model":"m","messages":[{"role":"user","content":"u"},{"role":"system","content":"S ` + ph + `"}]}`, "messages.1.content", "messages.0"},
|
||||
{"chat developer parts", provider.Chat, `{"model":"m","messages":[{"role":"developer","content":[{"type":"text","text":"S ` + ph + `"}]},{"role":"user","content":"u"}]}`, "messages.0.content.1.text", "messages.1"},
|
||||
{"chat tools no system", provider.Chat, `{"model":"m","tools":[{"type":"function","function":{"name":"f","description":"` + ph + `"}}],"messages":[{"role":"user","content":"u"}]}`, "messages.0.content", "tools"},
|
||||
{"chat tool output", provider.Chat, `{"model":"m","messages":[{"role":"system","content":"S"},{"role":"user","content":"u"},{"role":"tool","tool_call_id":"c","content":"` + ph + `"}]}`, "messages.2.content", "messages.0"},
|
||||
{"responses instructions", provider.Responses, `{"model":"m","instructions":"You are a coding agent. ` + ph + `","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"u"}]}]}`, "input.0.content.0.text", "input.1"},
|
||||
{"responses item", provider.Responses, `{"model":"m","instructions":"I","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"u"}]},{"type":"function_call","call_id":"a","name":"f","arguments":"{}"},{"type":"function_call","call_id":"b","name":"f","arguments":"{}"},{"type":"function_call_output","call_id":"a","output":"` + ph + `"},{"type":"function_call_output","call_id":"b","output":"x"},{"type":"message","role":"user","content":[{"type":"input_text","text":"next"}]}]}`, "input.5.content.0.text", "input.4"},
|
||||
{"responses text", provider.Responses, `{"model":"m","instructions":"I","input":"hello ` + ph + `"}`, "input.0.content.0.text", "instructions"},
|
||||
{"gemini system", provider.Gemini, `{"systemInstruction":{"parts":[{"text":"S ` + ph + `"}]},"contents":[{"role":"user","parts":[{"text":"u"}]}]}`, "systemInstruction.parts.1.text", "contents"},
|
||||
{"gemini snake", provider.Gemini, `{"system_instruction":{"parts":[{"text":"S ` + ph + `"}]},"contents":[]}`, "system_instruction.parts.1.text", "contents"},
|
||||
{"gemini content", provider.Gemini, `{"systemInstruction":{"parts":[{"text":"S"}]},"contents":[{"role":"user","parts":[{"text":"u"}]},{"role":"model","parts":[{"text":"ok"}]},{"role":"user","parts":[{"text":"` + ph + `"}]}]}`, "contents.2.parts.1.text", "systemInstruction"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
out := withPlaceholderNote(c.from, []byte(c.body))
|
||||
if !json.Valid(out) {
|
||||
t.Fatalf("not JSON: %s", out)
|
||||
}
|
||||
if got := gjson.GetBytes(out, c.where).String(); !strings.HasSuffix(got, placeholderNote) {
|
||||
t.Fatalf("%s = %q in %s", c.where, got, out)
|
||||
}
|
||||
if strings.Count(string(out), placeholderNote) != 1 {
|
||||
t.Fatalf("said more than once: %s", out)
|
||||
}
|
||||
if before := gjson.Get(c.body, c.keep).Raw; before != "" && gjson.GetBytes(out, c.keep).Raw != before {
|
||||
t.Fatalf("%s changed: %s", c.keep, out)
|
||||
}
|
||||
if c.from == provider.Responses && gjson.GetBytes(out, "instructions").String() != gjson.Get(c.body, "instructions").String() {
|
||||
t.Fatalf("instructions changed: %s", out)
|
||||
}
|
||||
// the same body is told the same way every time
|
||||
if again := withPlaceholderNote(c.from, []byte(c.body)); !bytes.Equal(again, out) {
|
||||
t.Fatalf("not stable:\n%s\n%s", out, again)
|
||||
}
|
||||
})
|
||||
}
|
||||
// a string input stays the user's message, after the note
|
||||
out := withPlaceholderNote(provider.Responses, []byte(`{"model":"m","instructions":"I","input":"hello `+ph+`"}`))
|
||||
if gjson.GetBytes(out, "input.1.role").String() != "user" || gjson.GetBytes(out, "input.1.content").String() != "hello "+ph {
|
||||
t.Fatalf("input text lost: %s", out)
|
||||
}
|
||||
// with no placeholder, or none it can place, it is left as it was
|
||||
for _, b := range []string{`not json`, `[1]`, `{"model":"m","input":[{"type":"message","role":"user","content":"hi"}]}`, `{"model":"m"}`} {
|
||||
if out := withPlaceholderNote(provider.Responses, []byte(b)); string(out) != b {
|
||||
t.Errorf("%s became %s", b, out)
|
||||
}
|
||||
}
|
||||
plain := `{"model":"m","system":"S","messages":[{"role":"user","content":"Values like {{NAME_ab12cd34}}"}]}`
|
||||
if out := withPlaceholderNote(provider.Anthropic, []byte(plain)); string(out) != plain {
|
||||
t.Errorf("told with no placeholder masking writes: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// A Claude subscription (run through the Claude Code binary) and Codex's
|
||||
// ChatGPT sign-in are never told; nor a Responses turn on a stored one.
|
||||
func TestPlaceholderNoteNotOnClientPaths(t *testing.T) {
|
||||
plain := []byte(`{"input":[]}`)
|
||||
for _, agent := range []string{"claude", "codex"} {
|
||||
p := provider.Provider{ID: agent, Account: &provider.Account{Agent: agent}}
|
||||
for _, from := range []provider.Protocol{provider.Anthropic, provider.Chat, provider.Responses, provider.Gemini} {
|
||||
if notesPlaceholders(p, from, plain) {
|
||||
t.Errorf("%s on %s is told", agent, from)
|
||||
}
|
||||
}
|
||||
}
|
||||
key := provider.Provider{ID: "k", Key: "k"}
|
||||
if !notesPlaceholders(key, provider.Responses, plain) || !notesPlaceholders(key, provider.Anthropic, plain) {
|
||||
t.Error("a key's provider isn't told")
|
||||
}
|
||||
if notesPlaceholders(key, provider.Responses, []byte(`{"previous_response_id":"resp_1","input":[]}`)) {
|
||||
t.Error("a turn on a stored response is told")
|
||||
}
|
||||
if !notesPlaceholders(provider.Provider{ID: "c", Account: &provider.Account{Agent: "copilot"}}, provider.Chat, plain) {
|
||||
t.Error("another sign-in isn't told")
|
||||
}
|
||||
}
|
||||
|
||||
// Through the gateway: a request masking changed is told, on every later
|
||||
// turn the same way; one it didn't change isn't.
|
||||
func TestMaskedRequestTold(t *testing.T) {
|
||||
const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"
|
||||
var mu sync.Mutex
|
||||
var got []byte
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
got = b
|
||||
mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":1}}`)
|
||||
}))
|
||||
defer up.Close()
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Anthropic: up.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := settings.Save(settings.Settings{Redact: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sent := func(req string) []byte {
|
||||
t.Helper()
|
||||
if code, body := post(t, "/v1/messages", req); code != 200 {
|
||||
t.Fatalf("%d %s", code, body)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return got
|
||||
}
|
||||
turn1 := `{"model":"fake/m1","max_tokens":10,"system":[{"type":"text","text":"Be brief."}],"messages":[{"role":"user","content":"my key is ` + key + `"}]}`
|
||||
b1 := sent(turn1)
|
||||
if strings.Contains(string(b1), key) || !strings.Contains(string(b1), "{{API_KEY_") {
|
||||
t.Fatalf("not masked: %s", b1)
|
||||
}
|
||||
if gjson.GetBytes(b1, "messages.0.content.1.text").String() != noteBlock || gjson.GetBytes(b1, "system").Raw != `[{"type":"text","text":"Be brief."}]` {
|
||||
t.Fatalf("not told on the message that holds it: %s", b1)
|
||||
}
|
||||
// the next turn carries the value again, as the agent had it back
|
||||
turn2 := `{"model":"fake/m1","max_tokens":10,"system":[{"type":"text","text":"Be brief."}],"messages":[{"role":"user","content":"my key is ` + key + `"},{"role":"assistant","content":"ok"},{"role":"user","content":"go on"}]}`
|
||||
b2 := sent(turn2)
|
||||
if gjson.GetBytes(b2, "system").Raw != gjson.GetBytes(b1, "system").Raw || gjson.GetBytes(b2, "messages.0").Raw != gjson.GetBytes(b1, "messages.0").Raw {
|
||||
t.Fatalf("the prefix changed between turns:\n%s\n%s", b1, b2)
|
||||
}
|
||||
// nothing masked, nothing said
|
||||
b3 := sent(`{"model":"fake/m1","max_tokens":10,"system":"Be brief.","messages":[{"role":"user","content":"hello"}]}`)
|
||||
if strings.Contains(string(b3), placeholderNote) || gjson.GetBytes(b3, "system").String() != "Be brief." {
|
||||
t.Fatalf("told with nothing masked: %s", b3)
|
||||
}
|
||||
}
|
||||
@@ -281,6 +281,12 @@ const (
|
||||
// placeholderRe is a placeholder as Mask writes it.
|
||||
var placeholderRe = regexp.MustCompile(`\{\{[A-Z][A-Z0-9_]*_[a-z2-7]{8}\}\}`)
|
||||
|
||||
// HasPlaceholder says whether s holds text written as Mask writes a
|
||||
// placeholder, in JSON or not.
|
||||
func HasPlaceholder(s string) bool {
|
||||
return strings.Contains(s, "{{") && placeholderRe.MatchString(s)
|
||||
}
|
||||
|
||||
// notAVariable turns away what stands in for a value: ${PASS}, <password>, ****.
|
||||
func notAVariable(v string) bool {
|
||||
if strings.ContainsAny(v[:1], "$%{<[*") {
|
||||
|
||||
Reference in New Issue
Block a user