gateway, redact: compile their 275 package-level regexps on first use, not at every start
magpie is one binary, so every package's init runs on every launch, including `magpie statusline`, which Claude Code runs on every message. internal/gateway and internal/redact compiled 275 patterns at init: 3.7 MB + 2.3 MB and ~38k allocations per launch, most of them for vendors and rules that launch never reaches. New internal/lazyre: RE holds the source and compiles it through a sync.Once on first use, with the *regexp.Regexp methods magpie calls delegating to it (Of wraps one already compiled, for the user's own privacy rules). A one-off Go AST rewrite turned every regexp.MustCompile in a package-level var (outside func literals) into lazyre.New; the struct fields, map and parameter that hold them took the new type. A bad pattern now panics on first use instead of at start, so TestAllCompile in gateway and redact compiles every registered one. Measured on mote (M5 Pro), sandbox HOME with a copy of real accounts, v0.1.3515 (273b9f5a9) vs this change: - GODEBUG=inittrace=1: all init 13.0 MB / 106k allocs -> 7.4 MB / 70k; gateway 3.68 MB -> 70 KB, redact 2.31 MB -> 261 KB. - `echo {} | magpie statusline`, /usr/bin/time -l, 3 runs each: instructions retired 260-265M -> 212-215M (-18%), peak footprint 22.1-22.3 MB -> 18.6-19.2 MB. Run: go vet ./... (mote); GOOS=linux and GOOS=windows go vet of gateway, redact, lazyre; go test -race ./internal/lazyre (incl. a bad-pattern test that MustAll panics); go test ./internal/redact (all); go test ./internal/gateway -run 'TestAllCompile|OtherOff|WorkDir| WorkPlace|RunNoise': ok. Broken by hand: TestBadPatternPanicsInMustAll registers `(` and fails if MustAll does not panic. Not run before the push: the whole internal/gateway package and the full suite (a full suite of273b9f5a9was running on mote).
This commit is contained in:
@@ -32,7 +32,6 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -40,6 +39,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
)
|
||||
@@ -1153,7 +1153,7 @@ func unanswered(key string, c candidate) {
|
||||
// blob", which names no item and says nothing of encrypted content,
|
||||
// where the #3392 shaping (xaiBody's) never runs because the relay's
|
||||
// host isn't api.x.ai.
|
||||
var foreignReasoning = regexp.MustCompile(`(?i)invalid_encrypted_content|invalid[ _]encrypted[ _](summary|content)|encrypted[ _]content.{0,80}could not be (verified|decrypted)|could not (decrypt|verify).{0,40}encrypted[ _]content|could not (decode|decrypt).{0,20}compaction[ _]blob`)
|
||||
var foreignReasoning = lazyre.New(`(?i)invalid_encrypted_content|invalid[ _]encrypted[ _](summary|content)|encrypted[ _]content.{0,80}could not be (verified|decrypted)|could not (decrypt|verify).{0,40}encrypted[ _]content|could not (decode|decrypt).{0,20}compaction[ _]blob`)
|
||||
|
||||
// refusedSeals remembers, per conversation and the key or account that
|
||||
// refused it, what another one sealed: its reasoning, and the sealed copy
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -16,6 +15,7 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -423,7 +423,7 @@ func withThinkingOnToolTurns(body []byte) []byte {
|
||||
|
||||
// anthropicModel is one of Anthropic's own models, which think only when asked,
|
||||
// so a request for one is left as the agent sent it.
|
||||
var anthropicModel = regexp.MustCompile(`(?i)(?:^|[/.:-])claude-`)
|
||||
var anthropicModel = lazyre.New(`(?i)(?:^|[/.:-])claude-`)
|
||||
|
||||
// alwaysThinks is a vendor refusing to turn a model's thinking off: Z.ai's
|
||||
// GLM-5.3 answers 1210, "…always engages in thinking…", or, in Chinese
|
||||
@@ -435,7 +435,7 @@ var anthropicModel = regexp.MustCompile(`(?i)(?:^|[/.:-])claude-`)
|
||||
// glm-5.3 "thinking.type `disabled` is not supported by this model"
|
||||
// (#1141). Kimi Code (China)'s K3.1 answers "…does not support disabled
|
||||
// thinking mode" (#3739).
|
||||
var alwaysThinks = regexp.MustCompile(`(?i)always engages in thinking|thinking (?:can ?not|can't) be (?:disabled|turned off)|enable_thinking[^"]{0,60}restricted to true|始终(?:支持|开启|启用)?思考|思考[^"]{0,20}(?:不可|无法|不能)关闭|requires adaptive thinking\W+thinking\.type\W+disabled\W+\(including reasoning\.effort=none\) is not allowed|thinking\.type \x60disabled\x60 is not supported by this model|does not support disabled thinking mode`)
|
||||
var alwaysThinks = lazyre.New(`(?i)always engages in thinking|thinking (?:can ?not|can't) be (?:disabled|turned off)|enable_thinking[^"]{0,60}restricted to true|始终(?:支持|开启|启用)?思考|思考[^"]{0,20}(?:不可|无法|不能)关闭|requires adaptive thinking\W+thinking\.type\W+disabled\W+\(including reasoning\.effort=none\) is not allowed|thinking\.type \x60disabled\x60 is not supported by this model|does not support disabled thinking mode`)
|
||||
|
||||
// refusesThinkingOff is an Anthropic endpoint turning away a request
|
||||
// with thinking turned off (thinking.type disabled): a model that always
|
||||
@@ -477,7 +477,7 @@ func withoutThinkingOff(body []byte) ([]byte, bool) {
|
||||
// claudeVersion finds the family's version in a Claude model id however a
|
||||
// relay spells it: claude-opus-4-6, claude-opus-5, anthropic.claude-sonnet-4.6-v1,
|
||||
// a relay's opus-5.5, claude-fable-5-1, or the old order, claude-3-7-sonnet.
|
||||
var claudeVersion = regexp.MustCompile(`(?:^|[^a-z0-9])(?:claude-)?(?:opus|sonnet|haiku|fable|mythos)-(\d{1,2})(?:[-.](\d{1,2}))?(?:[^0-9]|$)|claude-(\d+)(?:[-.](\d))?-(?:opus|sonnet|haiku)`)
|
||||
var claudeVersion = lazyre.New(`(?:^|[^a-z0-9])(?:claude-)?(?:opus|sonnet|haiku|fable|mythos)-(\d{1,2})(?:[-.](\d{1,2}))?(?:[^0-9]|$)|claude-(\d+)(?:[-.](\d))?-(?:opus|sonnet|haiku)`)
|
||||
|
||||
// adaptiveOnly is a Claude model from 4.6 on, which thinks adaptively:
|
||||
// claude-opus-5-5 refuses thinking.type=enabled with a budget ("requires
|
||||
@@ -556,7 +556,7 @@ func adaptiveThinking(body []byte) []byte {
|
||||
// spells it: claude-sonnet-5-5, claude-sonnet-5.5, a relay's sonnet-5.5,
|
||||
// Bedrock's anthropic.claude-sonnet-5-5-v1:0, Vertex's
|
||||
// claude-sonnet-5-5@20261001, claude-fable-5-1.
|
||||
var claudeLine = regexp.MustCompile(`(?:^|[^a-z0-9])(?:claude-)?(opus|sonnet|haiku|fable|mythos)-(\d{1,2})(?:[-.](\d{1,2}))?(?:[^0-9]|$)`)
|
||||
var claudeLine = lazyre.New(`(?:^|[^a-z0-9])(?:claude-)?(opus|sonnet|haiku|fable|mythos)-(\d{1,2})(?:[-.](\d{1,2}))?(?:[^0-9]|$)`)
|
||||
|
||||
// thinkingOff is how a Claude model takes thinking turned off.
|
||||
type thinkingOff int
|
||||
@@ -706,12 +706,12 @@ func thinkingOffAsTaken(body []byte, path string) []byte {
|
||||
// {"type": "between_tools"} instead of {"type": "disabled"}" as relays
|
||||
// pass it on (#1454), or the API's "Use "thinking.type.between_tools" for
|
||||
// the lowest thinking setting".
|
||||
var asksBetweenTools = regexp.MustCompile(`(?i)between_tools\W+instead of|use\W+thinking\.type\.between_tools`)
|
||||
var asksBetweenTools = lazyre.New(`(?i)between_tools\W+instead of|use\W+thinking\.type\.between_tools`)
|
||||
|
||||
// thinkingOffRefused is a Claude refusing thinking turned off at any
|
||||
// effort, as Opus 5.5 does: ""thinking.type.disabled" is not supported for
|
||||
// this model. Use "thinking.type.adaptive"…".
|
||||
var thinkingOffRefused = regexp.MustCompile(`(?i)thinking\.type\.disabled\W+is not supported`)
|
||||
var thinkingOffRefused = lazyre.New(`(?i)thinking\.type\.disabled\W+is not supported`)
|
||||
|
||||
// withBetweenTools is body with its thinking turned off as Sonnet 5.5
|
||||
// asks it, at effort high at most; false when body doesn't turn it off.
|
||||
@@ -784,7 +784,7 @@ func hasSampling(body []byte) bool {
|
||||
// samplingDeprecated is a Claude refusing a sampling parameter, as Haiku
|
||||
// 5.5 does: "`temperature` is deprecated for this model." (and `top_p`,
|
||||
// `top_k`).
|
||||
var samplingDeprecated = regexp.MustCompile("(?i)\\b(?:temperature|top_p|top_k)`?\\W+is (?:deprecated|not supported) for this model")
|
||||
var samplingDeprecated = lazyre.New("(?i)\\b(?:temperature|top_p|top_k)`?\\W+is (?:deprecated|not supported) for this model")
|
||||
|
||||
// withoutSampling is body without temperature, top_p and top_k; false
|
||||
// when it has none of them.
|
||||
@@ -812,7 +812,7 @@ func AdaptiveThinking(model string) bool { return adaptiveOnly(model) }
|
||||
// relay the user set up): a relay that maps Messages onto OpenAI reads the
|
||||
// level from output_config.effort, and a budget alone left every request at
|
||||
// its default, medium (zxz8009195489 on Discord, 2026-11-04).
|
||||
var effortInOutputConfig = regexp.MustCompile(`(?i)glm-5\.[23](?:$|[-.:/\[])|minimax-m3\.1-flash(?:$|[-.:/\[])|(?:^|[^a-z0-9])gpt-\d`)
|
||||
var effortInOutputConfig = lazyre.New(`(?i)glm-5\.[23](?:$|[-.:/\[])|minimax-m3\.1-flash(?:$|[-.:/\[])|(?:^|[^a-z0-9])gpt-\d`)
|
||||
|
||||
// deepseekHost is DeepSeek's own API, whose Anthropic endpoint
|
||||
// (api.deepseek.com/anthropic) takes the effort in output_config.
|
||||
@@ -855,7 +855,7 @@ func outputEffortAt(host, model string) bool {
|
||||
func AdaptiveWithEffort(model string) bool { return glmOutputEffort.MatchString(model) }
|
||||
|
||||
// glmOutputEffort is effortInOutputConfig's Z.ai half.
|
||||
var glmOutputEffort = regexp.MustCompile(`(?i)glm-5\.[23](?:$|[-.:/\[])`)
|
||||
var glmOutputEffort = lazyre.New(`(?i)glm-5\.[23](?:$|[-.:/\[])`)
|
||||
|
||||
// withOutputEffort is body asking, in output_config.effort, for the level
|
||||
// of levels nearest the reasoning it asks for; body when it asks for none.
|
||||
@@ -1574,7 +1574,7 @@ func rawCallID(mark, id string) string {
|
||||
return string(raw)
|
||||
}
|
||||
|
||||
var safeIDChars = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
|
||||
var safeIDChars = lazyre.New(`^[A-Za-z0-9_-]+$`)
|
||||
|
||||
func (e *anthropicEncoder) start(ev Event) {
|
||||
if e.started {
|
||||
|
||||
@@ -3,11 +3,11 @@ package gateway
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -86,13 +86,13 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
displayValueRefused = regexp.MustCompile(`thinking\.(?:adaptive|enabled)\.display:? Input should be`)
|
||||
displayRefused = regexp.MustCompile(`thinking\.(?:adaptive|enabled)\.display:? Extra inputs are not permitted`)
|
||||
turnEffortRefused = regexp.MustCompile(`messages\.\d+\.output_config:? Extra inputs are not permitted|Mid-conversation reasoning effort \(configuration_update\) is not supported`)
|
||||
turnRoleRefused = regexp.MustCompile(`messages\.(\d+)\.role\b`)
|
||||
safeguardsRefused = regexp.MustCompile(`\bsafeguards:? Extra inputs are not permitted`)
|
||||
deferredRefused = regexp.MustCompile("messages\\[\\d+\\]\\.content: unknown variant `(?:tool_addition|tool_removal|tool_definition|tool_reference)`")
|
||||
refsOnlyRefused = regexp.MustCompile("missing field `content`")
|
||||
displayValueRefused = lazyre.New(`thinking\.(?:adaptive|enabled)\.display:? Input should be`)
|
||||
displayRefused = lazyre.New(`thinking\.(?:adaptive|enabled)\.display:? Extra inputs are not permitted`)
|
||||
turnEffortRefused = lazyre.New(`messages\.\d+\.output_config:? Extra inputs are not permitted|Mid-conversation reasoning effort \(configuration_update\) is not supported`)
|
||||
turnRoleRefused = lazyre.New(`messages\.(\d+)\.role\b`)
|
||||
safeguardsRefused = lazyre.New(`\bsafeguards:? Extra inputs are not permitted`)
|
||||
deferredRefused = lazyre.New("messages\\[\\d+\\]\\.content: unknown variant `(?:tool_addition|tool_removal|tool_definition|tool_reference)`")
|
||||
refsOnlyRefused = lazyre.New("missing field `content`")
|
||||
)
|
||||
|
||||
// knownDisplay is a thinking.display every Anthropic endpoint has taken.
|
||||
|
||||
@@ -2,12 +2,12 @@ package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -187,7 +187,7 @@ var (
|
||||
// effortFieldUnknown is an upstream that doesn't know the effort's
|
||||
// field: OpenAI's "Unrecognized request argument supplied:
|
||||
// reasoning_effort", a validator's "Extra inputs are not permitted"
|
||||
effortFieldUnknown = regexp.MustCompile(`(?i)(?:unrecogni[sz]ed|unknown|unsupported|unexpected|extra)\s+(?:request\s+)?(?:argument|parameter|field|property|name|key)s?(?:\s+supplied)?\W{0,4}reasoning(?:[._]effort)?\b|\breasoning(?:[._]effort)?['"\x60]?\W{0,4}(?:extra inputs are not permitted|is not (?:supported|allowed|permitted)|unsupported)`)
|
||||
effortFieldUnknown = lazyre.New(`(?i)(?:unrecogni[sz]ed|unknown|unsupported|unexpected|extra)\s+(?:request\s+)?(?:argument|parameter|field|property|name|key)s?(?:\s+supplied)?\W{0,4}reasoning(?:[._]effort)?\b|\breasoning(?:[._]effort)?['"\x60]?\W{0,4}(?:extra inputs are not permitted|is not (?:supported|allowed|permitted)|unsupported)`)
|
||||
)
|
||||
|
||||
// ownEffortRefused reads a 400 to the effort magpie added (OwnEffort) as
|
||||
|
||||
@@ -5,12 +5,12 @@ import (
|
||||
"encoding/json"
|
||||
"maps"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -143,16 +143,16 @@ func (s *Server) bodyBetas(p provider.Provider, body []byte) []byte {
|
||||
// unexpectedBetas is the error of a provider that turns away betas it
|
||||
// doesn't know: Unexpected value(s) `a`, `b` for the `anthropic-beta`
|
||||
// header (Bedrock's), and its word for the body's anthropic_beta.
|
||||
var unexpectedBetas = regexp.MustCompile("(?i)unexpected values?(?:\\(s\\))?\\s+((?:`[^`]+`[,\\s]*(?:and\\s+)?)+)for the\\s+`anthropic[-_]beta`")
|
||||
var unexpectedBetas = lazyre.New("(?i)unexpected values?(?:\\(s\\))?\\s+((?:`[^`]+`[,\\s]*(?:and\\s+)?)+)for the\\s+`anthropic[-_]beta`")
|
||||
|
||||
var backquoted = regexp.MustCompile("`([^`]+)`")
|
||||
var backquoted = lazyre.New("`([^`]+)`")
|
||||
|
||||
// unsupportedBetas is Copilot's word for the same: 400 "unsupported beta
|
||||
// header(s): tool-search-tool-2025-10-19", the name Claude Code asks tool
|
||||
// search by in Claude Desktop's Code tab once its toolSearchEnabled policy
|
||||
// is on. Copilot answers the same request without it, defer_loading tools
|
||||
// and all (and with advanced-tool-use-2025-11-20).
|
||||
var unsupportedBetas = regexp.MustCompile(`(?i)unsupported beta headers?(?:\(s\))?:\s*([a-z0-9][a-z0-9._-]*(?:\s*,\s*[a-z0-9][a-z0-9._-]*)*)`)
|
||||
var unsupportedBetas = lazyre.New(`(?i)unsupported beta headers?(?:\(s\))?:\s*([a-z0-9][a-z0-9._-]*(?:\s*,\s*[a-z0-9][a-z0-9._-]*)*)`)
|
||||
|
||||
// refuseBetas reads the betas an error from p names as unknown, remembers
|
||||
// them so p isn't asked them again, and returns those it hadn't already.
|
||||
|
||||
@@ -3,9 +3,9 @@ package gateway
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
// and Code Assist is sent it as before (antigravityTurnsAway, #666).
|
||||
|
||||
// billingLine is a system block that is the billing line and nothing else.
|
||||
var billingLine = regexp.MustCompile(`^x-anthropic-billing-header:(\s*[A-Za-z_]+=[^;\s]*;)*\s*$`)
|
||||
var billingLine = lazyre.New(`^x-anthropic-billing-header:(\s*[A-Za-z_]+=[^;\s]*;)*\s*$`)
|
||||
|
||||
// keepsBillingLine says whether a request for model (wire, the vendor's name
|
||||
// for it) asked on to keeps Claude Code's billing line: a Claude model on
|
||||
|
||||
@@ -8,13 +8,13 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -50,7 +50,7 @@ import (
|
||||
|
||||
// bodyCapWords are a vendor's words for a request body over its byte
|
||||
// cap, not a conversation over the model's window (tooLong) nor a rate.
|
||||
var bodyCapWords = regexp.MustCompile(`(?i)request[ _](body|entity|payload)( size)?( is| was)? (too large|too big|over|larger than|exceeds?|exceeded)|request body is [\d.]+ ?[kmg]i?b|payload too large|entity too large|request_too_large|(body|request|payload) (size )?(exceeds?|exceeded|is over|is larger than) (the )?(max|limit|\d)|length limit exceeded|maximum allowed number of bytes|limit for one request|(max(imum)?|request) (request |body )*size (limit )?(exceeded|of)`)
|
||||
var bodyCapWords = lazyre.New(`(?i)request[ _](body|entity|payload)( size)?( is| was)? (too large|too big|over|larger than|exceeds?|exceeded)|request body is [\d.]+ ?[kmg]i?b|payload too large|entity too large|request_too_large|(body|request|payload) (size )?(exceeds?|exceeded|is over|is larger than) (the )?(max|limit|\d)|length limit exceeded|maximum allowed number of bytes|limit for one request|(max(imum)?|request) (request |body )*size (limit )?(exceeded|of)`)
|
||||
|
||||
// byteCapRefusal is a provider's refusal of a request for its bytes: a
|
||||
// 413 that doesn't say the model's window is full, or any other refusal
|
||||
@@ -98,7 +98,7 @@ func pageOverSize(status int, errBody []byte, sent int) bool {
|
||||
|
||||
// capSizes are the sizes a refusal names: "33554432 bytes", "32 MB",
|
||||
// "32MiB", "40.1 MB".
|
||||
var capSizes = regexp.MustCompile(`(?i)(\d+(?:\.\d+)?)\s*(bytes|b|kb|kib|mb|mib|gb|gib)\b`)
|
||||
var capSizes = lazyre.New(`(?i)(\d+(?:\.\d+)?)\s*(bytes|b|kb|kib|mb|mib|gb|gib)\b`)
|
||||
|
||||
// statedCap is the cap a refusal names: the smallest size in its words
|
||||
// under what was sent (the body's own size is often named beside it). A
|
||||
|
||||
@@ -8,10 +8,11 @@ import (
|
||||
"image"
|
||||
"image/jpeg"
|
||||
_ "image/png"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/image/draw"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// The browser MCP server lists one tool, browser, whose action names what
|
||||
@@ -152,7 +153,7 @@ func browserUnfold(raw json.RawMessage) (tool string, args json.RawMessage, shot
|
||||
|
||||
// the extension's answers name its own tools; through browser they are
|
||||
// actions
|
||||
var browserNameRe = regexp.MustCompile(`browser_(tabs|navigate|snapshot|click|type|press|hover|select|scroll|drag|upload|wait|screenshot|evaluate|text|console|dialog)\b`)
|
||||
var browserNameRe = lazyre.New(`browser_(tabs|navigate|snapshot|click|type|press|hover|select|scroll|drag|upload|wait|screenshot|evaluate|text|console|dialog)\b`)
|
||||
|
||||
var browserNameSay = strings.NewReplacer(
|
||||
"browser_tabs with action new", "the tab_new action",
|
||||
|
||||
@@ -10,12 +10,12 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -989,7 +989,7 @@ var gemini3Levels = []string{"minimal", "low", "medium", "high"}
|
||||
// thinking_level minimal alike; and gemini-3.1-pro-preview's
|
||||
// "thinking_level MINIMAL is not supported by this model" at its
|
||||
// generateContent.
|
||||
var geminiLevelRefused = regexp.MustCompile(`(?i)thinking[ _]level\W+(?:(minimal|low|medium|high)\W+is not supported|is unsupported\W+thinking_level_(minimal|low|medium|high))`)
|
||||
var geminiLevelRefused = lazyre.New(`(?i)thinking[ _]level\W+(?:(minimal|low|medium|high)\W+is not supported|is unsupported\W+thinking_level_(minimal|low|medium|high))`)
|
||||
|
||||
// geminiRefusedLevel is the thinking level Gemini turned away in body
|
||||
// (geminiLevelRefused), or "".
|
||||
|
||||
@@ -19,13 +19,13 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
@@ -395,7 +395,7 @@ func writePrior(b *strings.Builder, prev before) {
|
||||
}
|
||||
}
|
||||
|
||||
var firstNumber = regexp.MustCompile(`\d+`)
|
||||
var firstNumber = lazyre.New(`\d+`)
|
||||
|
||||
// readIntent is the intent a classifier's answer names: its first number,
|
||||
// 0 for none. The number is given back as it was said (said), so the
|
||||
|
||||
@@ -5,8 +5,9 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// Claude Code signed in to claude.ai, its base URL magpie's and no key
|
||||
@@ -111,7 +112,7 @@ func (w *signInWriter) Write(b []byte) (int, error) {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
var xAPIKey = regexp.MustCompile(`(?i)x-api-key`)
|
||||
var xAPIKey = lazyre.New(`(?i)x-api-key`)
|
||||
|
||||
// refusedMessage is a provider's refusal of magpie's credential, as a
|
||||
// Claude Code signed in to claude.ai is told it: b is magpie's error,
|
||||
|
||||
@@ -50,7 +50,6 @@ import (
|
||||
"path"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strconv"
|
||||
@@ -65,6 +64,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/claudecode"
|
||||
"github.com/yetone/magpie/internal/claudetui"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
@@ -585,7 +585,7 @@ func clientNamedWorkDir(req *Request) string {
|
||||
// of its own; the move reaches the model in the conversation as the
|
||||
// caller said it.
|
||||
func clientNamedWorkPlace(req *Request) (dir string, inTurns bool) {
|
||||
look := func(t string, turn bool, re *regexp.Regexp) {
|
||||
look := func(t string, turn bool, re *lazyre.RE) {
|
||||
if dir != "" {
|
||||
return
|
||||
}
|
||||
@@ -634,7 +634,7 @@ func clientNamedWorkPlace(req *Request) (dir string, inTurns bool) {
|
||||
// working directory: /x", a moved folder as "Primary working directory: /y
|
||||
// (was /x)"), on a --bare run just "CWD: /x"; OpenCode's, in its <env>;
|
||||
// pi's ("Current working directory:"); Codex's and pi's <cwd>.
|
||||
var clientSaidWorkDir = regexp.MustCompile(`(?m)^\s*(?:-\s*)?(?:Primary working directory|Working directory|Current working directory|CWD): *([^\r\n]+)$|<cwd>([^<\r\n]+)</cwd>`)
|
||||
var clientSaidWorkDir = lazyre.New(`(?m)^\s*(?:-\s*)?(?:Primary working directory|Working directory|Current working directory|CWD): *([^\r\n]+)$|<cwd>([^<\r\n]+)</cwd>`)
|
||||
|
||||
// clientTurnWorkDir is where a caller says its working directory is in a
|
||||
// turn of the conversation, on a line of its own: Codex's
|
||||
@@ -643,7 +643,7 @@ var clientSaidWorkDir = regexp.MustCompile(`(?m)^\s*(?:-\s*)?(?:Primary working
|
||||
// message of its own, and --bare's "CWD:" is its whole system prompt, so
|
||||
// their forms are not read in a turn: a line a user message quotes —
|
||||
// Claude Code's or anyone's — is no caller's word.
|
||||
var clientTurnWorkDir = regexp.MustCompile(`(?m)^\s*(?:-\s*)?(?:Working directory|Current working directory): *([^\r\n]+)$|<cwd>([^<\r\n]+)</cwd>`)
|
||||
var clientTurnWorkDir = lazyre.New(`(?m)^\s*(?:-\s*)?(?:Working directory|Current working directory): *([^\r\n]+)$|<cwd>([^<\r\n]+)</cwd>`)
|
||||
|
||||
func evalSymlinks(path string) string {
|
||||
if p, err := filepath.EvalSymlinks(path); err == nil {
|
||||
@@ -5062,9 +5062,9 @@ func bridgeToolName(name string) string {
|
||||
}
|
||||
|
||||
var (
|
||||
bridgeToolNameOK = regexp.MustCompile(`^[A-Za-z0-9_-]{1,51}$`)
|
||||
bridgeToolNameBad = regexp.MustCompile(`[^A-Za-z0-9_-]`)
|
||||
bridgeToolNameHashed = regexp.MustCompile(`_[0-9a-f]{12}$`)
|
||||
bridgeToolNameOK = lazyre.New(`^[A-Za-z0-9_-]{1,51}$`)
|
||||
bridgeToolNameBad = lazyre.New(`[^A-Za-z0-9_-]`)
|
||||
bridgeToolNameHashed = lazyre.New(`_[0-9a-f]{12}$`)
|
||||
)
|
||||
|
||||
// bridgeNames is the caller's name of each of tools by the name the MCP
|
||||
@@ -5123,7 +5123,7 @@ func withoutBillingHeader(system string) string {
|
||||
|
||||
// billingHeader is the line with its fields (cc_version=…; cc_entrypoint=…;
|
||||
// cch=…;), which the block after follows with no newline between.
|
||||
var billingHeader = regexp.MustCompile(`^x-anthropic-billing-header:(\s*[A-Za-z_]+=[^;\s]*;)*\s*`)
|
||||
var billingHeader = lazyre.New(`^x-anthropic-billing-header:(\s*[A-Za-z_]+=[^;\s]*;)*\s*`)
|
||||
|
||||
// renderClaudeTurn is the messages since a reply in a conversation Claude
|
||||
// Code already has, as it would be told them itself. The user's alone go
|
||||
@@ -5555,7 +5555,7 @@ func saidWithResults(msgs []Message) string {
|
||||
// sub-agent, a background command) ended, with the header it puts before
|
||||
// it: "[SYSTEM NOTIFICATION - NOT USER INPUT]" … <task-notification>…
|
||||
// </task-notification>.
|
||||
var taskNotice = regexp.MustCompile(`(?s)(?:\[SYSTEM NOTIFICATION - NOT USER INPUT\][^<]*)?<task-notification>.*?</task-notification>`)
|
||||
var taskNotice = lazyre.New(`(?s)(?:\[SYSTEM NOTIFICATION - NOT USER INPUT\][^<]*)?<task-notification>.*?</task-notification>`)
|
||||
|
||||
// withTaskNotices hands the run the notifications of background tasks
|
||||
// that came after the results (taskNotice), in a reminder at the end of the
|
||||
@@ -5603,7 +5603,7 @@ func withTaskNotices(results []Part, msgs []Message) []Part {
|
||||
|
||||
// skillBody is the text Claude Code sends after a Skill call's result:
|
||||
// the skill's SKILL.md, headed with where its files are.
|
||||
var skillBody = regexp.MustCompile(`^Base directory for this skill: `)
|
||||
var skillBody = lazyre.New(`^Base directory for this skill: `)
|
||||
|
||||
// withSkillBodies hands the run each skill's body that came after the
|
||||
// results, at the end of its Skill call's result. Claude Code answers a
|
||||
@@ -5677,21 +5677,21 @@ var (
|
||||
// Claude Code tells its model one: "The user sent a new message while
|
||||
// you were working:" (2.1.296), "The user sent the following message:"
|
||||
// (older).
|
||||
midTurnHead = regexp.MustCompile(`The user sent (?:a new message while you were working|the following message):[ \t]*\n`)
|
||||
midTurnHead = lazyre.New(`The user sent (?:a new message while you were working|the following message):[ \t]*\n`)
|
||||
// midTurnEnd is where the user's words after midTurnHead end: Claude
|
||||
// Code's ask to address them, the reminder's end, or a notice of its
|
||||
// own after them.
|
||||
midTurnEnd = regexp.MustCompile(`\n\n(?:This is how Claude Code surfaces messages the user sends mid-turn|IMPORTANT: After completing your current task, you MUST address the user's message above|Please address this message and continue with your tasks)|</system-reminder>|\n\n<total_tokens>|\n\n` + hookNoticeLead)
|
||||
midTurnEnd = lazyre.New(`\n\n(?:This is how Claude Code surfaces messages the user sends mid-turn|IMPORTANT: After completing your current task, you MUST address the user's message above|Please address this message and continue with your tasks)|</system-reminder>|\n\n<total_tokens>|\n\n` + hookNoticeLead)
|
||||
// hookNotice is a Claude Code hook's output told to the model:
|
||||
// "PreToolUse:Read hook additional context: …", "SessionStart hook
|
||||
// success: …", "Stop hook blocking error from command: …". Only
|
||||
// these kinds: "Stop hook is broken: …" may be the user's.
|
||||
hookNoticeLead = `[A-Z][A-Za-z]+(?::\S+)? hook (?:additional context|success|blocking error(?: from command)?|stopped continuation|feedback):`
|
||||
hookNotice = regexp.MustCompile(`^` + hookNoticeLead)
|
||||
hookNotice = lazyre.New(`^` + hookNoticeLead)
|
||||
// tokenCount is Claude Code's count of the tokens left, or used.
|
||||
tokenCount = regexp.MustCompile(`^(?:<total_tokens>[^<]*</total_tokens>|Token usage: \S+; \S+ remaining)$`)
|
||||
tokenCount = lazyre.New(`^(?:<total_tokens>[^<]*</total_tokens>|Token usage: \S+; \S+ remaining)$`)
|
||||
// reminderTag is a <system-reminder> tag, open or close.
|
||||
reminderTag = regexp.MustCompile(`</?system-reminder(?:\s[^>]*)?>`)
|
||||
reminderTag = lazyre.New(`</?system-reminder(?:\s[^>]*)?>`)
|
||||
// desktopNote is an annotation Claude Desktop (its Claude Code) puts
|
||||
// beside what the run reads, telling it about the picture it scaled
|
||||
// down, where a skill's files live, or that a tool of ToolSearch's
|
||||
@@ -5699,7 +5699,7 @@ var (
|
||||
// the user's — the picture itself rides in the tool result. Wide
|
||||
// images read in parallel bring one note each, which may come as one
|
||||
// text joined by blank lines: every note in it is the agent's.
|
||||
desktopNote = regexp.MustCompile(`(?s)^(?:(?:\[Image: original \d+x\d+, displayed at \d+x\d+\. Multiply coordinates by [\d.]+ to map to original image\.\]|Tool loaded\.)\s*)+$|^Base directory for this skill: `)
|
||||
desktopNote = lazyre.New(`(?s)^(?:(?:\[Image: original \d+x\d+, displayed at \d+x\d+\. Multiply coordinates by [\d.]+ to map to original image\.\]|Tool loaded\.)\s*)+$|^Base directory for this skill: `)
|
||||
)
|
||||
|
||||
// midTurnSaid is the user's words in each message they sent mid-turn
|
||||
@@ -6237,7 +6237,7 @@ func cliSchema(raw json.RawMessage) json.RawMessage {
|
||||
// given, before it reads its input: not JSON, not an object, or a schema
|
||||
// its Ajv won't compile ("strict mode: unknown keyword" for one only a
|
||||
// later draft has).
|
||||
var cliSchemaWords = regexp.MustCompile(`--json-schema (is not a valid JSON Schema|is not valid JSON|must be a JSON object)`)
|
||||
var cliSchemaWords = lazyre.New(`--json-schema (is not a valid JSON Schema|is not valid JSON|must be a JSON object)`)
|
||||
|
||||
// cliSchemaRefused is a run's Claude Code ending over the request's schema:
|
||||
// it ends the same for the same schema on every account and every try,
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strconv"
|
||||
@@ -19,6 +18,7 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/claudetui"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
@@ -385,7 +385,7 @@ func logOneOff(what, configDir, stderr string, err error) {
|
||||
|
||||
// homePath is a user's home folder in a path, on Windows, a Mac or
|
||||
// Linux, with either slash: what follows it is kept, the user's name not.
|
||||
var homePath = regexp.MustCompile(`(?i)(?:\b[a-z]:)?[\\/]+(?:users|home)[\\/]+[^\\/\s"'│:]+`)
|
||||
var homePath = lazyre.New(`(?i)(?:\b[a-z]:)?[\\/]+(?:users|home)[\\/]+[^\\/\s"'│:]+`)
|
||||
|
||||
// logSafe is s for app.log: secrets out (redact.Scrub), this user's home
|
||||
// folder and any other home folder in it written ~, its spaces
|
||||
|
||||
@@ -8,13 +8,13 @@ import (
|
||||
"maps"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -31,7 +31,7 @@ import (
|
||||
// this one tells it not to.
|
||||
const skipSignature = "skip_thought_signature_validator"
|
||||
|
||||
var unsafeToolID = regexp.MustCompile(`[^a-zA-Z0-9_-]`)
|
||||
var unsafeToolID = lazyre.New(`[^a-zA-Z0-9_-]`)
|
||||
|
||||
// antigravityBaseOf is the model an id of Antigravity's own is one level
|
||||
// of; a var so tests can stand in for it.
|
||||
@@ -796,7 +796,7 @@ func thinkingConfig(r *Request, model string, claude bool, at string) map[string
|
||||
|
||||
// geminiVersion is the major version in a Gemini model's id, as the id
|
||||
// names it: gemini-4-argon, models/gemini-3.8-flash, gemini-2.5-pro.
|
||||
var geminiVersion = regexp.MustCompile(`(?:^|/)gemini-(\d+)`)
|
||||
var geminiVersion = lazyre.New(`(?:^|/)gemini-(\d+)`)
|
||||
|
||||
// geminiGeneration is the generation of Gemini model names, 0 for an id
|
||||
// that names none (a non-Gemini model, or an alias such as
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptrace"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -28,6 +27,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/claudeseal"
|
||||
"github.com/yetone/magpie/internal/codexcat"
|
||||
"github.com/yetone/magpie/internal/codexsummary"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
@@ -50,7 +50,7 @@ var codexAPIBase = "https://api.openai.com/v1"
|
||||
// only magpie reads back (codexsummary).
|
||||
const magpieCompaction = codexsummary.Mark
|
||||
|
||||
var nativeSealedAgentPayload = regexp.MustCompile(`^gAAAAA[A-Za-z0-9_-]+={0,2}$`)
|
||||
var nativeSealedAgentPayload = lazyre.New(`^gAAAAA[A-Za-z0-9_-]+={0,2}$`)
|
||||
|
||||
// codexCompactPrompt and codexSummaryPrefix are Codex's own (Apache-2.0,
|
||||
// openai/codex, prompts/templates/compact).
|
||||
@@ -1794,7 +1794,7 @@ func codexRelayedAccount(base string, h http.Header, on *provider.Provider) (pro
|
||||
// found"), which a relay in front of one answers in words of its own
|
||||
// ("Referenced reasoning item 'rs_…' was not found or has expired",
|
||||
// #3062).
|
||||
var unreadableItem = regexp.MustCompile(`(?i)(?:encrypted content for item|item with id|referenced reasoning item) '?([A-Za-z]+_[A-Za-z0-9_-]+)'?`)
|
||||
var unreadableItem = lazyre.New(`(?i)(?:encrypted content for item|item with id|referenced reasoning item) '?([A-Za-z]+_[A-Za-z0-9_-]+)'?`)
|
||||
|
||||
// withoutUnreadable is body without what OpenAI's refusal msg says it
|
||||
// can't read: the item it names, what another account sealed
|
||||
@@ -2865,7 +2865,7 @@ func reasoningTextRefused(model string) string { return "reasoning text\x00" + m
|
||||
// long. Expected an array with maximum length 0, but got an array with
|
||||
// length 1 instead." (the ChatGPT backend's; a relay's may word the rest
|
||||
// otherwise, #1411)
|
||||
var reasoningContentRefusal = regexp.MustCompile(`input\[(\d+)\]\.content'?:? array too long`)
|
||||
var reasoningContentRefusal = lazyre.New(`input\[(\d+)\]\.content'?:? array too long`)
|
||||
|
||||
// refusesReasoningText is a 400 refusing the reasoning text in a Responses
|
||||
// request: the item the refusal names is reasoning with text in it.
|
||||
@@ -2936,7 +2936,7 @@ func citationOffsetRefused(model string) string { return "citation offsets\x00"
|
||||
// it passes it on: "Invalid response.create payload: Missing required
|
||||
// parameter: 'input[221].content[0].annotations[0].start_index'."
|
||||
// (#4921)
|
||||
var citationOffsetRefusal = regexp.MustCompile(`input\[\d+\]\.content\[\d+\]\.annotations\[\d+\]\.(?:start|end)_index`)
|
||||
var citationOffsetRefusal = lazyre.New(`input\[\d+\]\.content\[\d+\]\.annotations\[\d+\]\.(?:start|end)_index`)
|
||||
|
||||
// refusesCitationOffsets is a 400 refusing a Responses request over a
|
||||
// citation that lacks the offsets OpenAI's schema wants.
|
||||
@@ -3130,7 +3130,7 @@ func itemIDRefusal(b []byte) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
var itemIDRefusalHead = regexp.MustCompile(`Invalid 'input\[\d+\]\.id'`)
|
||||
var itemIDRefusalHead = lazyre.New(`Invalid 'input\[\d+\]\.id'`)
|
||||
|
||||
// itemIDsRefused is how unfit remembers a provider turning away, for
|
||||
// model, an input item id with another character in it (plainItemIDs).
|
||||
@@ -3297,7 +3297,7 @@ func plainItemIDs(body []byte) []byte {
|
||||
}
|
||||
|
||||
// longCallID finds a call_id longer than the ChatGPT backend takes.
|
||||
var longCallID = regexp.MustCompile(`"call_id"\s*:\s*"[^"]{65,}"`)
|
||||
var longCallID = lazyre.New(`"call_id"\s*:\s*"[^"]{65,}"`)
|
||||
|
||||
// boundCallIDs is a Responses request with every call_id longer than 64
|
||||
// characters as provider.BoundCallID has it, the rest of the request byte
|
||||
@@ -3895,7 +3895,7 @@ func upstreamFailed(rec *recorder) bool {
|
||||
upstreamFailedWords.Match(rec.body.Bytes())
|
||||
}
|
||||
|
||||
var upstreamFailedWords = regexp.MustCompile(`(?i)upstream request failed`)
|
||||
var upstreamFailedWords = lazyre.New(`(?i)upstream request failed`)
|
||||
|
||||
// summaryTooLarge is a summary request refused for its size: past the
|
||||
// vendor's byte cap (413; DeepSeek's "Failed to buffer the request body:
|
||||
@@ -3941,7 +3941,7 @@ func inputKindRefused(rec *recorder, err error) bool {
|
||||
return inputKindWords.Match(rec.body.Bytes())
|
||||
}
|
||||
|
||||
var inputKindWords = regexp.MustCompile(`(?i)unsupported_input_item|unknown item type`)
|
||||
var inputKindWords = lazyre.New(`(?i)unsupported_input_item|unknown item type`)
|
||||
|
||||
// compactFailure names who answered a summary request with a failure — the
|
||||
// provider, the model and the provider's base URL — and what it said.
|
||||
|
||||
@@ -6,13 +6,14 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// edgeReset is the 503 ChatGPT's front (Cloudflare, then Envoy) answers,
|
||||
// as text, when the backend behind it closed the connection before any
|
||||
// reply.
|
||||
var edgeReset = regexp.MustCompile(`(?i)upstream connect error or disconnect/reset before headers`)
|
||||
var edgeReset = lazyre.New(`(?i)upstream connect error or disconnect/reset before headers`)
|
||||
|
||||
// edgeUnbuffered is the 507 the same Envoy answers when its first try at
|
||||
// the backend failed and the request is more than it buffers to try again
|
||||
@@ -22,7 +23,7 @@ var edgeReset = regexp.MustCompile(`(?i)upstream connect error or disconnect/res
|
||||
// reset, at any size, since the 507 itself says the body was large.
|
||||
// sparrowu93 (#2034, pi) was told the 507 as it came, which pi doesn't
|
||||
// ask again for.
|
||||
var edgeUnbuffered = regexp.MustCompile(`(?i)exceeded request buffer limit while retrying upstream`)
|
||||
var edgeUnbuffered = lazyre.New(`(?i)exceeded request buffer limit while retrying upstream`)
|
||||
|
||||
// codexDropBody is the request size from which that 503 may be about the
|
||||
// request. ylorn (Discord, v0.1.1179) got it for every Codex turn a PNG
|
||||
|
||||
@@ -3,9 +3,10 @@ package gateway
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// Codex offers custom tools on Responses (exec in code mode, apply_patch):
|
||||
@@ -23,7 +24,7 @@ import (
|
||||
// "Unsupported custom tool: 'exec'", or the type named unsupported — as
|
||||
// xAI names it, Rust's own wording, "unknown variant `custom`" (#3392). A
|
||||
// refusal of anything else about a tool doesn't match.
|
||||
var customToolRefusal = regexp.MustCompile(`(?i)unsupported custom tool|custom tools? (?:is |are )?not (?:supported|allowed)|(?:unsupported|unknown|invalid) tool type[^\n{}]{0,20}?['"\x60]custom['"\x60]|tool type ['"\x60]custom['"\x60] (?:is )?(?:not supported|unsupported)|unknown variant[^\n{}]{0,20}?['"\x60]custom['"\x60]`)
|
||||
var customToolRefusal = lazyre.New(`(?i)unsupported custom tool|custom tools? (?:is |are )?not (?:supported|allowed)|(?:unsupported|unknown|invalid) tool type[^\n{}]{0,20}?['"\x60]custom['"\x60]|tool type ['"\x60]custom['"\x60] (?:is )?(?:not supported|unsupported)|unknown variant[^\n{}]{0,20}?['"\x60]custom['"\x60]`)
|
||||
|
||||
// customToolRefused is how unfit remembers model turning custom tools
|
||||
// away.
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -18,6 +17,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/desktopdir"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
@@ -34,8 +34,8 @@ import (
|
||||
// Anthropic model") and on the model a session is started with, so
|
||||
// anthropic/deepseek/deepseek-flash is turned away for its "deepseek".
|
||||
var (
|
||||
desktopDenied = regexp.MustCompile(`ark-code|astron|command-r|deepseek|doubao|gemini|gemma|glm|gpt|grok|hermes|hy3|kimi|lfm|\bling\b|llama|longcat|mimo|minimax|mistral|mixtral|moonshot|nemotron|openai|phi-|qianfan|qwen|tc-code|\bunic\b|yi-|stepfun|step-3|seed-|bytedance|hunyuan|granite|amazon\.nova|nova-|devstral|ministral|ernie|codex|arcee|trinity|abab|phi\d|\bk2\.|\bm2\.|jamba|arctic|solar|mercury|zamba|kat-coder|\bds-|dpsk`)
|
||||
desktopTier = regexp.MustCompile(`^(sonnet|opus|haiku|fable|mythos)(-[\d.]+)?$`)
|
||||
desktopDenied = lazyre.New(`ark-code|astron|command-r|deepseek|doubao|gemini|gemma|glm|gpt|grok|hermes|hy3|kimi|lfm|\bling\b|llama|longcat|mimo|minimax|mistral|mixtral|moonshot|nemotron|openai|phi-|qianfan|qwen|tc-code|\bunic\b|yi-|stepfun|step-3|seed-|bytedance|hunyuan|granite|amazon\.nova|nova-|devstral|ministral|ernie|codex|arcee|trinity|abab|phi\d|\bk2\.|\bm2\.|jamba|arctic|solar|mercury|zamba|kat-coder|\bds-|dpsk`)
|
||||
desktopTier = lazyre.New(`^(sonnet|opus|haiku|fable|mythos)(-[\d.]+)?$`)
|
||||
desktopWords = []string{"claude", "sonnet", "opus", "haiku", "fable", "mythos", "anthropic"}
|
||||
)
|
||||
|
||||
@@ -70,7 +70,7 @@ func desktopAccepts(id string) bool {
|
||||
// request that names no build at all, as the Code tab's Claude Code
|
||||
// ("claude-cli/… (external, claude-desktop)", known by its key) whose
|
||||
// ids are mythos-magpie-<n> already.
|
||||
var desktopUAVersion = regexp.MustCompile(` Claude/(\d+)`)
|
||||
var desktopUAVersion = lazyre.New(` Claude/(\d+)`)
|
||||
|
||||
func desktopKnowsMythos(ua string) bool {
|
||||
m := desktopUAVersion.FindStringSubmatch(ua)
|
||||
@@ -123,8 +123,8 @@ const (
|
||||
// desktopClaude is a model id that is Anthropic's own Claude model, as tIt
|
||||
// knows it: claude-<tier>-<version>, a date taken off.
|
||||
var (
|
||||
desktopClaude = regexp.MustCompile(`^claude-(?:opus|sonnet|haiku|fable|mythos)-\d+(?:-\d+)?$`)
|
||||
desktopDated = regexp.MustCompile(`-\d{8}$`)
|
||||
desktopClaude = lazyre.New(`^claude-(?:opus|sonnet|haiku|fable|mythos)-\d+(?:-\d+)?$`)
|
||||
desktopDated = lazyre.New(`-\d{8}$`)
|
||||
)
|
||||
|
||||
func aliasNumber(id string) string {
|
||||
|
||||
@@ -12,11 +12,12 @@ package gateway
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// effortRemember is how long an account's refusal of a level is kept: a
|
||||
@@ -94,12 +95,12 @@ func effortMate(left []candidate, c candidate, e string) int {
|
||||
var (
|
||||
// unsupportedEffort is OpenAI's "Unsupported value: 'high' is not
|
||||
// supported with the 'gpt-6-luna' model. Supported values are: …"
|
||||
unsupportedEffort = regexp.MustCompile(`(?i)unsupported value:?\s*['"\x60]?([a-z]+)['"\x60]?\s+is not supported`)
|
||||
unsupportedEffort = lazyre.New(`(?i)unsupported value:?\s*['"\x60]?([a-z]+)['"\x60]?\s+is not supported`)
|
||||
// effortNamed is a refusal naming the reasoning effort itself
|
||||
effortNamed = regexp.MustCompile(`(?i)reasoning[._ ]?effort`)
|
||||
effortDenied = regexp.MustCompile(`(?i)not supported|unsupported|not available|isn'?t available|not allowed|invalid value|upgrade|your plan`)
|
||||
supportedAre = regexp.MustCompile(`(?i)supported values are:?\s*([^.]*)`)
|
||||
quotedLevel = regexp.MustCompile(`['"\x60]([a-z]+)['"\x60]`)
|
||||
effortNamed = lazyre.New(`(?i)reasoning[._ ]?effort`)
|
||||
effortDenied = lazyre.New(`(?i)not supported|unsupported|not available|isn'?t available|not allowed|invalid value|upgrade|your plan`)
|
||||
supportedAre = lazyre.New(`(?i)supported values are:?\s*([^.]*)`)
|
||||
quotedLevel = lazyre.New(`['"\x60]([a-z]+)['"\x60]`)
|
||||
)
|
||||
|
||||
// effortRefused reads a vendor's 400 as the reasoning level sent turned
|
||||
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
@@ -34,6 +33,7 @@ import (
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
@@ -1565,7 +1565,7 @@ func restOf(id string) (Rest, bool) {
|
||||
|
||||
// quotaWords are how vendors say "out of quota" or "slow down" when their
|
||||
// status code doesn't: some answer 400 or 403 with it.
|
||||
var quotaWords = regexp.MustCompile(`(?i)quota|insufficient|balance|credit|billing|out of budget|budget (exceeded|exhausted)|exceeded|rate.?limit|usage.?limit|limit.?reached|hit your .*limit|limit.{0,24}resets|too many requests|overloaded|余额|额度|欠费|限流|频率|频繁|速率|套餐|用量|上限`)
|
||||
var quotaWords = lazyre.New(`(?i)quota|insufficient|balance|credit|billing|out of budget|budget (exceeded|exhausted)|exceeded|rate.?limit|usage.?limit|limit.?reached|hit your .*limit|limit.{0,24}resets|too many requests|overloaded|余额|额度|欠费|限流|频率|频繁|速率|套餐|用量|上限`)
|
||||
|
||||
// quotaSaid is whether an error's words, with no status to go by, say
|
||||
// out of quota or slow down: quotaWords, unless they say the conversation
|
||||
@@ -1624,7 +1624,7 @@ func codeAssistModelMissing(p provider.Provider, status int, body []byte) bool {
|
||||
// {"type":"ModelDeprecated","message":"Model exo-free has been
|
||||
// deprecated."}} (MOMO on Discord), OpenAI's "The model … has been
|
||||
// deprecated".
|
||||
var retiredWords = regexp.MustCompile(`(?i)"ModelDeprecated"|model_deprecated|model.{0,80}(has been|was|is now|is) (deprecated|retired|discontinued|decommissioned|sunset)`)
|
||||
var retiredWords = lazyre.New(`(?i)"ModelDeprecated"|model_deprecated|model.{0,80}(has been|was|is now|is) (deprecated|retired|discontinued|decommissioned|sunset)`)
|
||||
|
||||
// modelRetired says the vendor turned the request away because the model
|
||||
// is retired there: it leaves that provider's place in the lists
|
||||
@@ -1658,13 +1658,13 @@ func modelRetired(status int, body []byte) bool {
|
||||
// glm-5-free is not supported"). Not its "is not supported for format
|
||||
// anthropic", a model served on another API (wrongEndpoint), and not its
|
||||
// AuthError "Invalid API key." for a key it doesn't take.
|
||||
var zenModelGone = regexp.MustCompile(`(^|[\s:"])Model [^"\s]+ is not supported("|\s*$)`)
|
||||
var zenModelGone = lazyre.New(`(^|[\s:"])Model [^"\s]+ is not supported("|\s*$)`)
|
||||
|
||||
// refusedWords are how a vendor says it won't take requests from this
|
||||
// client at all — WorkBuddy's "Illegal API invocation from an unapproved
|
||||
// channel" to a chat opening with another agent's own system prompt — a
|
||||
// refusal of the provider, not of the request, another member may serve.
|
||||
var refusedWords = regexp.MustCompile(`(?i)unapproved channel|illegal api invocation`)
|
||||
var refusedWords = lazyre.New(`(?i)unapproved channel|illegal api invocation`)
|
||||
|
||||
// promptRefused says a vendor answered with that refusal: the agent's
|
||||
// prompt, not the account, is at fault.
|
||||
@@ -1694,7 +1694,7 @@ func promptRefused(status int, body []byte) bool {
|
||||
// the only field set." (#5374, worksyang) — a description beside an
|
||||
// anyOf, which Google's Schema takes alone, the reporter's same tools
|
||||
// another member took.
|
||||
var shapeWords = regexp.MustCompile(`(?i)failed to deserialize|unknown (item |content |input )?(type|variant|field|parameter)|unknown_parameter|unrecognized (request argument|field|parameter)|extra (inputs|fields) are not permitted|additional properties are not allowed|schema exceeds the maximum (nesting )?depth|schema[^"]{0,60}\bnesting depth\b|function_declarations\[\d+\]\.parameters\b|schema specified other fields alongside any_?of`)
|
||||
var shapeWords = lazyre.New(`(?i)failed to deserialize|unknown (item |content |input )?(type|variant|field|parameter)|unknown_parameter|unrecognized (request argument|field|parameter)|extra (inputs|fields) are not permitted|additional properties are not allowed|schema exceeds the maximum (nesting )?depth|schema[^"]{0,60}\bnesting depth\b|function_declarations\[\d+\]\.parameters\b|schema specified other fields alongside any_?of`)
|
||||
|
||||
// unsaidWords are Command Code's Provider API turning a request away with
|
||||
// nothing but a trace id: {"message":"invalid request error trace_id:
|
||||
@@ -1711,7 +1711,7 @@ var shapeWords = regexp.MustCompile(`(?i)failed to deserialize|unknown (item |co
|
||||
// that says so names the model's context length before the trace id, and
|
||||
// isn't one. The message may come after a provider's name ("Command Code:
|
||||
// "), as magpie tells it on.
|
||||
var unsaidWords = regexp.MustCompile(`(?i)(^|"|\\"|: )invalid request error trace_id: [0-9a-f]{16,}(\\?"|\s*$)`)
|
||||
var unsaidWords = lazyre.New(`(?i)(^|"|\\"|: )invalid request error trace_id: [0-9a-f]{16,}(\\?"|\s*$)`)
|
||||
|
||||
// shapeRefused says a request failed over its shape alone: the next
|
||||
// member is asked, and this one doesn't rest, as nothing is wrong with it.
|
||||
@@ -1756,7 +1756,7 @@ func shapeRefused(status int, body []byte) bool {
|
||||
// again (regionFresh).
|
||||
// A request's own field named location ("location field is not
|
||||
// supported") isn't one.
|
||||
var regionWords = regexp.MustCompile(`(?i)\buser location is not supported for the api use\b|unsupported_country_region_territory|country, region,? or territory not supported`)
|
||||
var regionWords = lazyre.New(`(?i)\buser location is not supported for the api use\b|unsupported_country_region_territory|country, region,? or territory not supported`)
|
||||
|
||||
// regionRefused says the vendor refused the request for where it came
|
||||
// from, with regionWords.
|
||||
@@ -1766,7 +1766,7 @@ func regionRefused(status int, body []byte) bool {
|
||||
|
||||
// googleRegionWords is Google's wording of the refusal (Gemini, Code
|
||||
// Assist, Antigravity), which names the vendor in regionNote.
|
||||
var googleRegionWords = regexp.MustCompile(`(?i)\buser location is not supported for the api use\b`)
|
||||
var googleRegionWords = lazyre.New(`(?i)\buser location is not supported for the api use\b`)
|
||||
|
||||
// regionNote is what the agent is told beside a refusal of where the
|
||||
// request came from (regionRefused), or "" for any other reply: the
|
||||
@@ -1802,7 +1802,7 @@ func explained(p provider.Provider, model string, res *http.Response, b []byte)
|
||||
// same history on every account and model the backend serves, and the
|
||||
// history as plain text is answered, so it is about the request, not the
|
||||
// account: asked again there, it only drains the accounts' allowances.
|
||||
var protectionWords = regexp.MustCompile(`(?i)response protection is unavailable`)
|
||||
var protectionWords = lazyre.New(`(?i)response protection is unavailable`)
|
||||
|
||||
// protectionRefused says the vendor turned the request's content away
|
||||
// with protectionWords: the account is not at fault, and none of its
|
||||
@@ -1822,7 +1822,7 @@ func protectionRefused(status int, body []byte) bool {
|
||||
// where the error names its code, not in its words: "…a different
|
||||
// model.","type":"invalid_request_error" reads as a model unserved
|
||||
// (unservedWords) otherwise.
|
||||
var zdrCoded = regexp.MustCompile(`\\?"(type|code)\\?"\s*:\s*\\?"cmd_zdr_no_providers\\?"`)
|
||||
var zdrCoded = lazyre.New(`\\?"(type|code)\\?"\s*:\s*\\?"cmd_zdr_no_providers\\?"`)
|
||||
|
||||
// zdrRefused says Command Code turned the request away for its Zero Data
|
||||
// Retention setting: a choice the user made for every request to the
|
||||
@@ -1977,11 +1977,11 @@ const lengthMargin = 0.5
|
||||
|
||||
// lengthWords say the request is too long, or to make it shorter or start
|
||||
// over, without naming what overflowed.
|
||||
var lengthWords = regexp.MustCompile(`(?i)太长|过长|超长|精简|缩短|删减|(开启|新建|开始|重新开启)(一个)?新的?(对话|会话|聊天)|too (long|large|big)|shorten|reduce (the )?(length|size)|start a new (conversation|chat|session)`)
|
||||
var lengthWords = lazyre.New(`(?i)太长|过长|超长|精简|缩短|删减|(开启|新建|开始|重新开启)(一个)?新的?(对话|会话|聊天)|too (long|large|big)|shorten|reduce (the )?(length|size)|start a new (conversation|chat|session)`)
|
||||
|
||||
// partWords name a part of the request whose length isn't the
|
||||
// conversation's: a picture, a file, the reply, a field, a name.
|
||||
var partWords = regexp.MustCompile(`(?i)图片|图像|文件|附件|输出|回复|名称|字段|参数|标题|image|picture|file|attachment|output|max_tokens|max_completion|completion|title|description`)
|
||||
var partWords = lazyre.New(`(?i)图片|图像|文件|附件|输出|回复|名称|字段|参数|标题|image|picture|file|attachment|output|max_tokens|max_completion|completion|title|description`)
|
||||
|
||||
// saysLength says a request error's message speaks of the request's length
|
||||
// and of nothing else: not a pace, a quota, a part of the request.
|
||||
@@ -2095,7 +2095,7 @@ func unsaidOverflows(p provider.Provider, status int) bool {
|
||||
// transportWords are a failure that never reached a vendor's answer, as Go,
|
||||
// Bun or Windows say it, or magpie's own words for a reply that broke off:
|
||||
// a request that met one may well fit, and is asked again.
|
||||
var transportWords = regexp.MustCompile(`(?i)dial (tcp|udp)|connectex|wsarecv|wsasend|i/o timeout|TLS handshake timeout|context deadline exceeded|Client\.Timeout|timeout awaiting response headers|connection (was )?(reset|refused|aborted|closed)|forcibly closed|broken pipe|unexpected EOF|no such host|network is unreachable|no route to host|server closed idle connection|Unable to connect|ConnectionRefused|ConnectionClosed|FailedToOpenSocket|ETIMEDOUT|ECONNRESET|ECONNREFUSED|ECONNABORTED|ENOTFOUND|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH|EPIPE`)
|
||||
var transportWords = lazyre.New(`(?i)dial (tcp|udp)|connectex|wsarecv|wsasend|i/o timeout|TLS handshake timeout|context deadline exceeded|Client\.Timeout|timeout awaiting response headers|connection (was )?(reset|refused|aborted|closed)|forcibly closed|broken pipe|unexpected EOF|no such host|network is unreachable|no route to host|server closed idle connection|Unable to connect|ConnectionRefused|ConnectionClosed|FailedToOpenSocket|ETIMEDOUT|ECONNRESET|ECONNREFUSED|ECONNABORTED|ENOTFOUND|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH|EPIPE`)
|
||||
|
||||
// transportFailed says an error body is a transport failure rather than a
|
||||
// vendor's answer (transportWords), or one magpie made of a reply that
|
||||
@@ -2255,7 +2255,7 @@ var wallCodes = map[string]bool{"user_model_rate_limited": true}
|
||||
// with no label), which a moment does clear, and a GLM key asked again
|
||||
// in place stays so. The words and the id together are the label's own,
|
||||
// not words anywhere in the body a prompt may quote.
|
||||
var zcodeRateWall = regexp.MustCompile(`\[1302\]\[您的账户已达到速率限制[^\]]*\]\[[0-9a-fA-F]{16,}\]`)
|
||||
var zcodeRateWall = lazyre.New(`\[1302\]\[您的账户已达到速率限制[^\]]*\]\[[0-9a-fA-F]{16,}\]`)
|
||||
|
||||
// walled says whether body is a refusal whose error.code is one of
|
||||
// wallCodes: the code where the vendor puts it, not the words anywhere in
|
||||
@@ -4264,17 +4264,17 @@ func errorCode(raw json.RawMessage) string {
|
||||
// policyCode is an error code that names the vendor's usage policy:
|
||||
// OpenAI's bio_policy ("This content was flagged for possible biological
|
||||
// risk"), cyber_policy and the like (#248).
|
||||
var policyCode = regexp.MustCompile(`^[a-z]+_policy$`)
|
||||
var policyCode = lazyre.New(`^[a-z]+_policy$`)
|
||||
|
||||
// sensitiveCode is how Volcengine Ark's errors say its filter refused the
|
||||
// input or the reply: InputTextSensitiveContentDetected,
|
||||
// OutputTextSensitiveContentDetected, SensitiveContentDetected and the
|
||||
// image and video kinds of them.
|
||||
var sensitiveCode = regexp.MustCompile(`SensitiveContentDetected$`)
|
||||
var sensitiveCode = lazyre.New(`SensitiveContentDetected$`)
|
||||
|
||||
// flaggedWords are how OpenAI's invalid_prompt says the prompt was held to
|
||||
// its usage policy, rather than malformed.
|
||||
var flaggedWords = regexp.MustCompile(`(?i)flagged|usage polic`)
|
||||
var flaggedWords = lazyre.New(`(?i)flagged|usage polic`)
|
||||
|
||||
// policyRefusal tells whether an error — an error object, a body holding
|
||||
// one, or a stream's error event — is the vendor's safety filter refusing
|
||||
@@ -4573,7 +4573,7 @@ func namedStatusOf(errRaw []byte) int {
|
||||
// "(HTTP 503)": a plugin that can't fail its 200 any more puts its
|
||||
// upstream's status in its message (mycf_711's wps-lingxi rows,
|
||||
// "灵犀上游返回 AIError:AI服务异常(上游暂时不可用,可重试)(HTTP 503)").
|
||||
var httpSaid = regexp.MustCompile(`[((]\s*HTTP\s*(429|5\d\d)\s*[))]`)
|
||||
var httpSaid = lazyre.New(`[((]\s*HTTP\s*(429|5\d\d)\s*[))]`)
|
||||
|
||||
// textStatus is the status an error's words name (httpSaid), 0 when they
|
||||
// name none, or say the request is too long, or are magpie's own. Only a
|
||||
|
||||
@@ -3,10 +3,10 @@ package gateway
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -148,7 +148,7 @@ func formatRefused(model string) string { return "response_format:" + model }
|
||||
|
||||
// formatRefusal is an upstream's 400 naming the field structured output is
|
||||
// asked for in, in any API's words.
|
||||
var formatRefusal = regexp.MustCompile(`(?i)response_format|json_schema|json_object|output_config\.format|text\.format|structured.output|response_?mime_?type|response_?json_?schema|response_?schema`)
|
||||
var formatRefusal = lazyre.New(`(?i)response_format|json_schema|json_object|output_config\.format|text\.format|structured.output|response_?mime_?type|response_?json_?schema|response_?schema`)
|
||||
|
||||
// refusesFormat is whether an upstream's answer turned the request away
|
||||
// over its format.
|
||||
|
||||
+22
-22
@@ -18,7 +18,6 @@ import (
|
||||
"net/http/httptrace"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
@@ -37,6 +36,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/gwbudget"
|
||||
"github.com/yetone/magpie/internal/gwmw"
|
||||
"github.com/yetone/magpie/internal/gwtool"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/pluginrt"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
@@ -217,7 +217,7 @@ func standIn(agent, asked string) string {
|
||||
// claude-fable-5-1, claude-haiku-4-5-20251001, claude-3-5-sonnet-20241022,
|
||||
// whatever the version, matched by family so a release magpie has never
|
||||
// heard of is one too. A provider's "a/claude-…" is not one.
|
||||
var claudeFamily = regexp.MustCompile(`^claude-(?:[0-9][0-9.-]*-)?(?:opus|sonnet|haiku|fable)(?:[-.@:]|$)`)
|
||||
var claudeFamily = lazyre.New(`^claude-(?:[0-9][0-9.-]*-)?(?:opus|sonnet|haiku|fable)(?:[-.@:]|$)`)
|
||||
|
||||
// claudeTierStandIn is the model Claude Code is set to use for the tier of
|
||||
// a full Claude id it names (StandIn), even one magpie serves: Claude Code
|
||||
@@ -2045,7 +2045,7 @@ func (s *Server) countOn(w http.ResponseWriter, r *http.Request, p provider.Prov
|
||||
|
||||
// Match the counting operation or the endpoint itself, not an unsupported
|
||||
// image, model, API key or tool parameter mentioned in the same error.
|
||||
var unsupportedCountWords = regexp.MustCompile(`(?i)` +
|
||||
var unsupportedCountWords = lazyre.New(`(?i)` +
|
||||
`^(unsupported|unimplemented|not (supported|implemented))$|` +
|
||||
`\b(count_tokens|counttokens|token counting|counting tokens) ((is )?not (supported|implemented)|is (unsupported|unimplemented))\b|` +
|
||||
`\b(unsupported|unimplemented|does not support|doesn't support) (count_tokens|counttokens|token counting|counting tokens)\b|` +
|
||||
@@ -8291,7 +8291,7 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
|
||||
// reasoning_effort are not supported for global.openai.gpt-6-luna in
|
||||
// /v1/chat/completions. To use function tools, use /v1/responses or set
|
||||
// reasoning_effort to 'none'.").
|
||||
var toolsWithoutEffort = regexp.MustCompile(`(?is)tools with reasoning_effort are not supported.*reasoning_effort to .?none`)
|
||||
var toolsWithoutEffort = lazyre.New(`(?is)tools with reasoning_effort are not supported.*reasoning_effort to .?none`)
|
||||
|
||||
// effortRequired is an upstream turning a request away for asking no
|
||||
// reasoning effort, or none, from a model that needs one: "reasoning
|
||||
@@ -8299,7 +8299,7 @@ var toolsWithoutEffort = regexp.MustCompile(`(?is)tools with reasoning_effort ar
|
||||
// "this model requires a reasoning effort", "reasoning cannot be
|
||||
// disabled". A refusal of a level the model hasn't, or of the field
|
||||
// itself, is not one.
|
||||
var effortRequired = regexp.MustCompile(`(?i)reasoning[ _.]?effort\W+(?:is\s+)?(?:required|mandatory|missing)\b|(?:missing|requires?|needs?)\s+(?:a\s+|the\s+)?(?:required\s+)?(?:parameter\W+)?reasoning(?:[ _.]?effort)?\b|reasoning\s+is\s+(?:required|mandatory)\b|reasoning\W+(?:cannot|can't|can not)\s+be\s+(?:disabled|turned off)`)
|
||||
var effortRequired = lazyre.New(`(?i)reasoning[ _.]?effort\W+(?:is\s+)?(?:required|mandatory|missing)\b|(?:missing|requires?|needs?)\s+(?:a\s+|the\s+)?(?:required\s+)?(?:parameter\W+)?reasoning(?:[ _.]?effort)?\b|reasoning\s+is\s+(?:required|mandatory)\b|reasoning\W+(?:cannot|can't|can not)\s+be\s+(?:disabled|turned off)`)
|
||||
|
||||
// needsReasoning is b turning effort away as effortRequired does, or,
|
||||
// for reasoning asked off (none, minimal), in the words of a model that
|
||||
@@ -8311,7 +8311,7 @@ func needsReasoning(effort string, b []byte) bool {
|
||||
}
|
||||
|
||||
// OpenRouter rejects an explicit reasoning-off request for some endpoints.
|
||||
var mandatoryReasoning = regexp.MustCompile(`(?i)reasoning is mandatory for this endpoint and cannot be disabled`)
|
||||
var mandatoryReasoning = lazyre.New(`(?i)reasoning is mandatory for this endpoint and cannot be disabled`)
|
||||
|
||||
// servesElsewhere reports whether p serves model on an API besides proto
|
||||
// that hasn't turned it away.
|
||||
@@ -8464,22 +8464,22 @@ func refusedOptional(status int, msg, body []byte) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
var unknownOptionalField = regexp.MustCompile("(?i)\\b(?:unknown (?:name|field|parameter)|unsupported (?:parameter|field|property|argument)|unrecognized (?:request )?(?:argument|parameter)(?: supplied)?):?\\s*['\"\\x60]([a-z_]+)['\"\\x60]")
|
||||
var unquotedUnsupportedOptionalField = regexp.MustCompile("(?i)\\bunsupported (?:parameter|field|property|argument):\\s*([a-z_]+)\\b")
|
||||
var rejectedOptionalField = regexp.MustCompile("(?i)(?:^|\\b(?:parameter|field|property|argument)\\s+)['\"\\x60]([a-z_]+)['\"\\x60]\\s+(?:is\\s+)?(?:unsupported|not supported)\\b")
|
||||
var unknownOptionalField = lazyre.New("(?i)\\b(?:unknown (?:name|field|parameter)|unsupported (?:parameter|field|property|argument)|unrecognized (?:request )?(?:argument|parameter)(?: supplied)?):?\\s*['\"\\x60]([a-z_]+)['\"\\x60]")
|
||||
var unquotedUnsupportedOptionalField = lazyre.New("(?i)\\bunsupported (?:parameter|field|property|argument):\\s*([a-z_]+)\\b")
|
||||
var rejectedOptionalField = lazyre.New("(?i)(?:^|\\b(?:parameter|field|property|argument)\\s+)['\"\\x60]([a-z_]+)['\"\\x60]\\s+(?:is\\s+)?(?:unsupported|not supported)\\b")
|
||||
|
||||
// leadingRejectedOptionalField is a message that starts with the field's
|
||||
// bare name: OpenAI's "prompt_cache_options is not supported on this
|
||||
// model" (#2154). Only at the start, so a field named further on, in an
|
||||
// echo of the input, is not taken for it.
|
||||
var leadingRejectedOptionalField = regexp.MustCompile("(?i)^\\s*([a-z_]+)\\s+is\\s+(?:unsupported|not supported)\\b")
|
||||
var leadingRejectedOptionalField = lazyre.New("(?i)^\\s*([a-z_]+)\\s+is\\s+(?:unsupported|not supported)\\b")
|
||||
|
||||
// valueRejectedForField is a vendor naming the field after the value it
|
||||
// turned away: litellm's "'priority' is not supported for 'service_tier'
|
||||
// on this model" (#3978). The name after "for" is what separates this
|
||||
// from a value's refusal ("... is not supported with this model"),
|
||||
// which reaches the client as it came.
|
||||
var valueRejectedForField = regexp.MustCompile("(?i)['\"\\x60][^'\"\\x60]{0,64}['\"\\x60]\\s+is\\s+(?:unsupported|not supported)\\s+for\\s+['\"\\x60]([a-z_]+)['\"\\x60]")
|
||||
var valueRejectedForField = lazyre.New("(?i)['\"\\x60][^'\"\\x60]{0,64}['\"\\x60]\\s+is\\s+(?:unsupported|not supported)\\s+for\\s+['\"\\x60]([a-z_]+)['\"\\x60]")
|
||||
|
||||
func unsupportedOptionalField(fault any, field string) bool {
|
||||
switch v := fault.(type) {
|
||||
@@ -8664,7 +8664,7 @@ func refusedInMessages(status int, msg, body []byte) []string {
|
||||
}
|
||||
|
||||
// fieldAtPosition is Kimi's refusal of a thinking field in a message.
|
||||
var fieldAtPosition = regexp.MustCompile(`\bthe (reasoning_details|reasoning_content|reasoning) at position \d+\b`)
|
||||
var fieldAtPosition = lazyre.New(`\bthe (reasoning_details|reasoning_content|reasoning) at position \d+\b`)
|
||||
|
||||
// badRequest is a status an upstream refuses a request's contents with.
|
||||
func badRequest(status int) bool {
|
||||
@@ -10139,7 +10139,7 @@ func forcesTool(choice string) bool {
|
||||
// answers `tools.N.custom: For 'object' type, 'additionalProperties' must
|
||||
// be explicitly set to false` (#668), which Anthropic says only of a
|
||||
// strict tool, and magpie sends none.
|
||||
var toolChoiceRefused = regexp.MustCompile(`(?i)tool_choice\W+type\W+tool\W+and\W+any\W+are not supported|tools\.\d+\.custom\W+for\W+object\W+type\W+additionalProperties\W+must be explicitly set to false`)
|
||||
var toolChoiceRefused = lazyre.New(`(?i)tool_choice\W+type\W+tool\W+and\W+any\W+are not supported|tools\.\d+\.custom\W+for\W+object\W+type\W+additionalProperties\W+must be explicitly set to false`)
|
||||
|
||||
// unforced is req with its forced tool_choice left to the model: a named
|
||||
// tool is the only one offered, as the Claude subscription's bridge does,
|
||||
@@ -10156,7 +10156,7 @@ func unforced(req *Request) *Request {
|
||||
// effortLevelsNamed is an error that lists the reasoning levels a model
|
||||
// takes, as one refusing "none" does: Command Code's `expected one of
|
||||
// "low"|"medium"|"high"|"xhigh"|"max"`.
|
||||
var effortLevelsNamed = regexp.MustCompile(`(?i)\blow\b\W+(?:medium|high)\b`)
|
||||
var effortLevelsNamed = lazyre.New(`(?i)\blow\b\W+(?:medium|high)\b`)
|
||||
|
||||
// otherOffNamed is, for one level of reasoning off, the other named in an
|
||||
// error: one refusing that level and listing the other among those taken
|
||||
@@ -10164,14 +10164,14 @@ var effortLevelsNamed = regexp.MustCompile(`(?i)\blow\b\W+(?:medium|high)\b`)
|
||||
// Supported values are: 'none', 'low', 'medium', and 'high'."). The level is
|
||||
// matched quoted, as errors listing levels quote them (in JSON a double
|
||||
// quote comes escaped), so a "None" in a sentence isn't it.
|
||||
var otherOffNamed = map[string]*regexp.Regexp{
|
||||
"none": regexp.MustCompile(`(?i)['"]minimal\\?['"]`),
|
||||
var otherOffNamed = map[string]*lazyre.RE{
|
||||
"none": lazyre.New(`(?i)['"]minimal\\?['"]`),
|
||||
"minimal": noneQuoted,
|
||||
}
|
||||
|
||||
// noneQuoted is reasoning effort none named in an error, quoted, as
|
||||
// errors listing levels quote them (in JSON a double quote comes escaped).
|
||||
var noneQuoted = regexp.MustCompile(`(?i)['"]none\\?['"]`)
|
||||
var noneQuoted = lazyre.New(`(?i)['"]none\\?['"]`)
|
||||
|
||||
// bodyEffort is the reasoning effort a Chat or Responses request asks for,
|
||||
// or an Anthropic one in its output_config, or a Gemini one in its
|
||||
@@ -10492,7 +10492,7 @@ func saidOverloaded(status int, msg string) bool {
|
||||
// takes for a failure worth asking again (Pi's isRetryableError, #2372):
|
||||
// one of the usual statuses, a timeout, a rate limit, a busy or
|
||||
// unreachable server.
|
||||
var passingSaid = regexp.MustCompile(`(?i)\b(429|500|502|503|504)\b|timed? ?out|rate.?limit|too many requests|overloaded|service.?unavailable|server.?error|internal.?error|connection.?(error|refused|reset)|retry your request|try your request again`)
|
||||
var passingSaid = lazyre.New(`(?i)\b(429|500|502|503|504)\b|timed? ?out|rate.?limit|too many requests|overloaded|service.?unavailable|server.?error|internal.?error|connection.?(error|refused|reset)|retry your request|try your request again`)
|
||||
|
||||
// saysPassing is msg, an error sent in a stream whose status the agent
|
||||
// can no longer be told, with the status said in it when it is one a
|
||||
@@ -10513,12 +10513,12 @@ func saysPassing(status int, msg string) string {
|
||||
// retry later" and "Too many pending requests, please retry later" in a
|
||||
// 400, "The service is temporarily unavailable. Please retry later." with
|
||||
// no status at all (#2372, the texts zminds' Pi sessions recorded).
|
||||
var busyWords = regexp.MustCompile(`(?i)concurrency limit|too many (pending|concurrent|in-?flight) requests|temporarily unavailable|(please )?(retry|try again) later|并发|稍后(再)?重?试`)
|
||||
var busyWords = lazyre.New(`(?i)concurrency limit|too many (pending|concurrent|in-?flight) requests|temporarily unavailable|(please )?(retry|try again) later|并发|稍后(再)?重?试`)
|
||||
|
||||
// spentWords say an account is out of what it pays for, which no retry
|
||||
// clears: Pi's own deny-list keeps such a text from being asked again, and
|
||||
// magpie doesn't tell it otherwise.
|
||||
var spentWords = regexp.MustCompile(`(?i)quota|insufficient|balance|credit|billing|budget|usage.?limit|余额|额度|欠费|套餐|用量`)
|
||||
var spentWords = lazyre.New(`(?i)quota|insufficient|balance|credit|billing|budget|usage.?limit|余额|额度|欠费|套餐|用量`)
|
||||
|
||||
// saysBusy is msg, a request error's text (400, 409, 422), with "you can
|
||||
// retry your request" said in it when its words say only that the relay
|
||||
@@ -10662,7 +10662,7 @@ func writeErrorAs(w http.ResponseWriter, proto provider.Protocol, status int, ty
|
||||
// 提示词, prompt…) beside its length, so "名称超出最大长度" (a field) or
|
||||
// "输出过长" (the reply) isn't taken; bare "token数量超过上限" isn't either,
|
||||
// as a day's allowance is said so too.
|
||||
var tooLongRe = regexp.MustCompile(`(?i)context_length_exceeded|prompt is too long|input is too long|(exceeds?|exceeded|over|beyond)( the)?( model'?s?)?( maximum)? context|context (length|limit|window) (exceeded|is exceeded)|context (window )?(is )?full\b|maximum context length|too many (input |prompt )?tokens|上下文(长度)?(超|过长)|超(过|出)(了)?(模型)?(的)?(最大)?上下文` +
|
||||
var tooLongRe = lazyre.New(`(?i)context_length_exceeded|prompt is too long|input is too long|(exceeds?|exceeded|over|beyond)( the)?( model'?s?)?( maximum)? context|context (length|limit|window) (exceeded|is exceeded)|context (window )?(is )?full\b|maximum context length|too many (input |prompt )?tokens|上下文(长度)?(超|过长)|超(过|出)(了)?(模型)?(的)?(最大)?上下文` +
|
||||
`|input token count.*exceeds the maximum|maximum prompt length is \d|reduce the length of the messages|maximum allowed input length|longer than the model'?s? context length|available context size|greater than the context length|prompt token count of [\d,]+ exceeds the limit|context window exceeds limit|exceeded model token limit|configured context size|prompt too long|prompt exceeds max length|context_window_exceeded|exceeded (max |maximum )?context length|range of input length should be|token limit exceeded|input tokens? (count )?(exceeds?|exceeded) (the )?(max(imum)? )?limit` +
|
||||
`|(内容|输入|文本|提示词?|prompt|问题|对话|消息)(内容|文本)?(长度)?\s*(太长|过长|超长)|字数(太多|过多)` +
|
||||
`|(内容|输入|文本|提示词?|prompt|问题|对话|消息)[^,。,.;;!!]{0,12}超(过|出)[^,。,.;;!!]{0,12}(长度|token|令牌|字数)` +
|
||||
@@ -10697,7 +10697,7 @@ func tooLong(status int, msg string) bool {
|
||||
|
||||
// paceWords say a limit on how fast or how much, not on one prompt's size,
|
||||
// in Chinese too (#4420): "内容太长,已达到速率限制" is the momentary cap.
|
||||
var paceWords = regexp.MustCompile(`(?i)rate.?limit|per (minute|hour|day)|\bTP[MD]\b|please wait|try again later|throttl|速率|频繁|频率|限流|并发|每(秒|分钟|小时|天|日)|稍后(再试|重试)`)
|
||||
var paceWords = lazyre.New(`(?i)rate.?limit|per (minute|hour|day)|\bTP[MD]\b|please wait|try again later|throttl|速率|频繁|频率|限流|并发|每(秒|分钟|小时|天|日)|稍后(再试|重试)`)
|
||||
|
||||
// splitSent tells what of sent, the ms from the request (start) to its
|
||||
// answering try's body written, was magpie's own work, the tries that
|
||||
|
||||
@@ -4,12 +4,12 @@ import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -484,7 +484,7 @@ func dropSignatures(req *Request, drop func(sig string) bool) *Request {
|
||||
// "Corrupted thought signature.". It is about the request's history, not
|
||||
// the account: the request is asked again without signatures, and no
|
||||
// account rests for it.
|
||||
var signatureRefused = regexp.MustCompile(`(?i)\b(invalid|corrupted) thought signature`)
|
||||
var signatureRefused = lazyre.New(`(?i)\b(invalid|corrupted) thought signature`)
|
||||
|
||||
// signaturesReach says a request built for provider p on API to carries
|
||||
// Gemini's signatures there: Gemini's own API (Vertex AI, AI Studio, Code
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"runtime/pprof"
|
||||
"slices"
|
||||
@@ -14,6 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// A request magpie holds too long before routing it is stopped with a 504
|
||||
@@ -49,7 +49,7 @@ func heldWhere() string {
|
||||
|
||||
// heldName is a report's file name: held-<UTC time>-<nanoseconds>.txt, so
|
||||
// names sort in the order written.
|
||||
var heldName = regexp.MustCompile(`^held-\d{8}-\d{6}-\d{9}\.txt$`)
|
||||
var heldName = lazyre.New(`^held-\d{8}-\d{6}-\d{9}\.txt$`)
|
||||
|
||||
// heldMu keeps two reports' writes and prunes apart, and heldLast is
|
||||
// when the last was named.
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// TestAllCompile compiles every pattern this package compiles on first
|
||||
// use, so a bad one fails here and not on a user's request.
|
||||
func TestAllCompile(t *testing.T) {
|
||||
if n := lazyre.MustAll(); n == 0 {
|
||||
t.Fatal("no lazy patterns registered")
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,10 @@ package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// tooFewTokens reads a provider's floor on the reply's length from the 400
|
||||
@@ -13,7 +14,7 @@ import (
|
||||
// providers answer and some turn away. A > may come JSON-escaped, as
|
||||
// \u003e: the error is read from the body magpie re-encoded for the agent,
|
||||
// or a vendor encodes its own that way (#260: "Expected a value >= 16").
|
||||
var tooFewTokens = regexp.MustCompile(`(?i)max_(?:completion_|output_)?tokens.{0,60}?(greater than|more than|larger than|at least|(?:>|\\u003e)=?)\s*(\d+)`)
|
||||
var tooFewTokens = lazyre.New(`(?i)max_(?:completion_|output_)?tokens.{0,60}?(greater than|more than|larger than|at least|(?:>|\\u003e)=?)\s*(\d+)`)
|
||||
|
||||
// tokenFloor is the least a provider said it takes, or 0 when the error
|
||||
// isn't about that.
|
||||
|
||||
@@ -5,10 +5,10 @@ import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -33,7 +33,7 @@ func mantleRouteKey(model string) string { return "mantle-route:" + model }
|
||||
|
||||
// mantleWrongRoute is Mantle's refusal of a model asked at the prefix that
|
||||
// doesn't serve it.
|
||||
var mantleWrongRoute = regexp.MustCompile(`(?i)(?:isn't|is not|not) supported on this route`)
|
||||
var mantleWrongRoute = lazyre.New(`(?i)(?:isn't|is not|not) supported on this route`)
|
||||
|
||||
// mantleReroute asks a request Mantle refused for its route again at the
|
||||
// other prefix, once, and remembers that prefix for the model when it is
|
||||
|
||||
@@ -3,12 +3,12 @@ package gateway
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -150,12 +150,12 @@ func replyLeft(msg []byte) int {
|
||||
// that adds the reply's allowance to the prompt: "(N in the messages, M in
|
||||
// the completion)", or vLLM's newer "your prompt contains at least N input
|
||||
// tokens".
|
||||
var windowAndPrompt = regexp.MustCompile(`(?is)maximum context length is (\d+) tokens.{0,200}?(?:\((\d+) in the messages, \d+ in the completion\)|your prompt contains at least (\d+) input tokens)`)
|
||||
var windowAndPrompt = lazyre.New(`(?is)maximum context length is (\d+) tokens.{0,200}?(?:\((\d+) in the messages, \d+ in the completion\)|your prompt contains at least (\d+) input tokens)`)
|
||||
|
||||
// inputPlusReply is Anthropic's words for the same, which an endpoint
|
||||
// speaking its API may answer with: "input length and `max_tokens` exceed
|
||||
// context limit: 197202 + 21333 > 200000".
|
||||
var inputPlusReply = regexp.MustCompile(`(?i)input length and .{0,3}max_tokens.{0,3} exceed context limit:\s*(\d+)\s*\+\s*\d+\s*>\s*(\d+)`)
|
||||
var inputPlusReply = lazyre.New(`(?i)input length and .{0,3}max_tokens.{0,3} exceed context limit:\s*(\d+)\s*\+\s*\d+\s*>\s*(\d+)`)
|
||||
|
||||
// leastReplyLeft is the least room left for a reply that is worth asking
|
||||
// for: less, and the conversation needs compacting, which the refusal
|
||||
|
||||
@@ -46,12 +46,12 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
@@ -240,7 +240,7 @@ func nativeProto(p provider.Provider) provider.Protocol {
|
||||
|
||||
// schemeLike is a first segment that reads as a URL's scheme ("http:",
|
||||
// "javascript:x").
|
||||
var schemeLike = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.-]*:`)
|
||||
var schemeLike = lazyre.New(`^[A-Za-z][A-Za-z0-9+.-]*:`)
|
||||
|
||||
// nativeTarget is raw, the path after the provider as the caller escaped
|
||||
// it, at base's host: scheme and host from base, nothing of base's path.
|
||||
|
||||
@@ -6,9 +6,9 @@ import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -67,7 +67,7 @@ func eventsStart(head []byte) bool {
|
||||
}
|
||||
|
||||
// htmlStart is how a web page begins.
|
||||
var htmlStart = regexp.MustCompile(`(?i)^<(!doctype\s+html|html[\s>]|head[\s>]|body[\s>])`)
|
||||
var htmlStart = lazyre.New(`(?i)^<(!doctype\s+html|html[\s>]|head[\s>]|body[\s>])`)
|
||||
|
||||
// webPage says what a page served in place of a reply was, by its title,
|
||||
// and for a firewall's block page what to do about it.
|
||||
|
||||
@@ -3,8 +3,8 @@ package gateway
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -29,7 +29,7 @@ import (
|
||||
|
||||
// rootUnionRefusal is an upstream refusing a tool's parameters for a
|
||||
// union at their root.
|
||||
var rootUnionRefusal = regexp.MustCompile(`(?i)tool parameter root must be an object type|does not support oneOf, allOf, or anyOf at the top level|schema must have type .object. and not have .oneOf.|schema must be a JSON Schema of .type: \\?"object\\?".`)
|
||||
var rootUnionRefusal = lazyre.New(`(?i)tool parameter root must be an object type|does not support oneOf, allOf, or anyOf at the top level|schema must have type .object. and not have .oneOf.|schema must be a JSON Schema of .type: \\?"object\\?".`)
|
||||
|
||||
// rootUnionRefused is how unfit remembers model refusing one.
|
||||
func rootUnionRefused(model string) string { return "root union\x00" + model }
|
||||
|
||||
@@ -19,13 +19,13 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -33,7 +33,7 @@ import (
|
||||
// connection was made: a name that didn't resolve, no route, refused, a
|
||||
// dial or TLS handshake that timed out. A proxy that is down (proxyDown)
|
||||
// is told apart before it.
|
||||
var connFailed = regexp.MustCompile(`dial tcp |dial udp |lookup [^ ]+|TLS handshake timeout|network is unreachable|no route to host|Unable to connect|ConnectionRefused|FailedToOpenSocket|ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ENETUNREACH|EHOSTUNREACH`)
|
||||
var connFailed = lazyre.New(`dial tcp |dial udp |lookup [^ ]+|TLS handshake timeout|network is unreachable|no route to host|Unable to connect|ConnectionRefused|FailedToOpenSocket|ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ENETUNREACH|EHOSTUNREACH`)
|
||||
|
||||
// lastHeard is when any upstream last answered, as unix nanoseconds.
|
||||
var lastHeard atomic.Int64
|
||||
|
||||
@@ -3,10 +3,10 @@ package gateway
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -27,7 +27,7 @@ const passthroughKey = "internal_chat_message_metadata_passthrough"
|
||||
// passthroughRefusal is OpenAI's refusal of one member of the passthrough,
|
||||
// or of the passthrough itself, as its path in the request: the member's
|
||||
// name, empty for the whole passthrough.
|
||||
var passthroughRefusal = regexp.MustCompile(`input\[\d+\]\.` + passthroughKey + `(?:\.([A-Za-z0-9_]+))?\]?\s*\[unknown_parameter\]|(?i:unknown parameter):?\s*'input\[\d+\]\.` + passthroughKey + `(?:\.([A-Za-z0-9_]+))?'`)
|
||||
var passthroughRefusal = lazyre.New(`input\[\d+\]\.` + passthroughKey + `(?:\.([A-Za-z0-9_]+))?\]?\s*\[unknown_parameter\]|(?i:unknown parameter):?\s*'input\[\d+\]\.` + passthroughKey + `(?:\.([A-Za-z0-9_]+))?'`)
|
||||
|
||||
// refusedPassthrough is the member msg says the upstream doesn't know,
|
||||
// "" for the passthrough as a whole.
|
||||
|
||||
@@ -4,10 +4,10 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -93,7 +93,7 @@ func busy(status int, body []byte) bool {
|
||||
// queue status rather than sending the request again. Only the plugin's
|
||||
// own words are matched: a relay's 503 that names its own queue ("queue
|
||||
// full", 排队中) is a moment's overload, waited out as before.
|
||||
var queuedWords = regexp.MustCompile(`(?i)\bqueued the request\b|\bthis plan's queue:`)
|
||||
var queuedWords = lazyre.New(`(?i)\bqueued the request\b|\bthis plan's queue:`)
|
||||
|
||||
// queued says whether a failure's body is the Qoder plugin's queue answer.
|
||||
func queued(body []byte) bool {
|
||||
|
||||
@@ -2,7 +2,8 @@ package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// A model that won't go on from a conversation ending with the
|
||||
@@ -33,7 +34,7 @@ import (
|
||||
|
||||
// prefillRefusal is an upstream's refusal of a conversation ending with
|
||||
// the assistant's message.
|
||||
var prefillRefusal = regexp.MustCompile(`(?i)does not support (?:assistant message )?prefill|requests ending with a model turn are not supported`)
|
||||
var prefillRefusal = lazyre.New(`(?i)does not support (?:assistant message )?prefill|requests ending with a model turn are not supported`)
|
||||
|
||||
// prefillRefused is how unfit remembers a provider's model refusing a
|
||||
// conversation ending with the assistant's message.
|
||||
|
||||
@@ -18,12 +18,12 @@ package gateway
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -346,12 +346,12 @@ func (p *Prompt) calibrate(counted, window int) {
|
||||
|
||||
var (
|
||||
// Claude Code: "Contents of /path/CLAUDE.md (project instructions, …):"
|
||||
contentsOf = regexp.MustCompile(`(?m)^Contents of (\S.*?) \(([^()\n]*(?:\([^()\n]*\)[^()\n]*)*)\):[ \t]*$`)
|
||||
contentsOf = lazyre.New(`(?m)^Contents of (\S.*?) \(([^()\n]*(?:\([^()\n]*\)[^()\n]*)*)\):[ \t]*$`)
|
||||
// OpenCode: "Instructions from: /path/AGENTS.md"
|
||||
instructionsFrom = regexp.MustCompile(`(?m)^Instructions from: (\S.*?)[ \t]*$`)
|
||||
instructionsFrom = lazyre.New(`(?m)^Instructions from: (\S.*?)[ \t]*$`)
|
||||
// Codex: "# AGENTS.md instructions for /path"
|
||||
agentsFor = regexp.MustCompile(`^# (\S+\.md) instructions for (\S.*?)[ \t]*\n`)
|
||||
leadTag = regexp.MustCompile(`^\s*<([a-zA-Z_][\w -]{0,40})>`)
|
||||
agentsFor = lazyre.New(`^# (\S+\.md) instructions for (\S.*?)[ \t]*\n`)
|
||||
leadTag = lazyre.New(`^\s*<([a-zA-Z_][\w -]{0,40})>`)
|
||||
)
|
||||
|
||||
// memoryTag says whose an instruction file is from how the agent
|
||||
@@ -492,8 +492,8 @@ var (
|
||||
readTools = map[string]bool{"Read": true, "read": true, "read_file": true, "ReadFile": true, "view": true,
|
||||
"View": true, "NotebookRead": true, "readFile": true, "open_file": true, "cat": true}
|
||||
pathKeys = []string{"file_path", "path", "filePath", "target_file", "notebook_path", "file", "filename", "uri"}
|
||||
cmdOfExec = regexp.MustCompile(`\bcmd\s*:\s*"((?:[^"\\]|\\.)*)"`)
|
||||
toolOfJS = regexp.MustCompile(`\btools\.(\w+)\s*\(`)
|
||||
cmdOfExec = lazyre.New(`\bcmd\s*:\s*"((?:[^"\\]|\\.)*)"`)
|
||||
toolOfJS = lazyre.New(`\btools\.(\w+)\s*\(`)
|
||||
readCmds = map[string]bool{"cat": true, "head": true, "tail": true, "nl": true, "bat": true, "less": true, "more": true}
|
||||
)
|
||||
|
||||
@@ -714,10 +714,10 @@ func userSays(text string) bool { return userWords(text) != "" }
|
||||
var (
|
||||
// reminders are what agents add to a user's message for the model
|
||||
// alone: Claude Code's <system-reminder>, ZCode's with a source=.
|
||||
reminders = regexp.MustCompile(`(?s)<system-reminder(?:\s[^>]*)?>.*?</system-reminder>`)
|
||||
reminders = lazyre.New(`(?s)<system-reminder(?:\s[^>]*)?>.*?</system-reminder>`)
|
||||
// myRequest heads what the user typed in the Codex app, after the
|
||||
// context it puts first (# Context from my IDE setup:, <in-app-browser-context>…).
|
||||
myRequest = regexp.MustCompile(`(?m)^## My request(?: for Codex)?:[ \t]*\n?`)
|
||||
myRequest = lazyre.New(`(?m)^## My request(?: for Codex)?:[ \t]*\n?`)
|
||||
// injected are how a text the agent put in as the user begins, beside
|
||||
// agentsFor and the reminders: Codex's and the Codex app's context,
|
||||
// Reasonix's snapshot of the workspace, Claude Code's and ZCode's
|
||||
|
||||
+27
-27
@@ -19,7 +19,6 @@ import (
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
@@ -28,6 +27,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/routes"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
@@ -139,7 +139,7 @@ func plainUnavailable(c candidate, status int, body []byte) bool {
|
||||
|
||||
// idRun is a run in an error's words that differs from one try to the
|
||||
// next: a request or trace id, a timestamp.
|
||||
var idRun = regexp.MustCompile(`[0-9a-fA-F][0-9a-fA-F-]{11,}|\d{6,}`)
|
||||
var idRun = lazyre.New(`[0-9a-fA-F][0-9a-fA-F-]{11,}|\d{6,}`)
|
||||
|
||||
// refusalWords is a 5xx's status and the words it said, ids left out
|
||||
// (idRun), for two tries' to be compared; "" when it said nothing, as a
|
||||
@@ -302,7 +302,7 @@ var creditLadder = []time.Duration{creditRest, 2 * time.Hour, 8 * time.Hour, 24
|
||||
// max_tokens … can only afford N" (the request's size, not the balance
|
||||
// spent), and a vendor's "try again in 30 seconds" or "1 分钟后重试".
|
||||
// These rest creditRest, as before; they don't climb creditLadder.
|
||||
var creditSoon = regexp.MustCompile(`(?i)openrouter_in_flight_budget|can only afford|fewer max_tokens|(?:try again|retry)(?: after| in)?\s*\d|\d+\s*(?:秒|分钟|小时)[后後]`)
|
||||
var creditSoon = lazyre.New(`(?i)openrouter_in_flight_budget|can only afford|fewer max_tokens|(?:try again|retry)(?: after| in)?\s*\d|\d+\s*(?:秒|分钟|小时)[后後]`)
|
||||
|
||||
// creditBackoff is the rest of a key (c, no subscription account) out of
|
||||
// credit, rested by id: the vendor's own time when it names one (a
|
||||
@@ -336,7 +336,7 @@ func creditBackoff(id string, header http.Header, body []byte, now time.Time) (d
|
||||
|
||||
var (
|
||||
// creditWords: the account or key has no money left.
|
||||
creditWords = regexp.MustCompile(`(?i)insufficient.?(balance|credit|fund)|balance|credit|billing|payment|arrear|overdue|suspended|余额|欠费|充值|账户.*(不足|停)`)
|
||||
creditWords = lazyre.New(`(?i)insufficient.?(balance|credit|fund)|balance|credit|billing|payment|arrear|overdue|suspended|余额|欠费|充值|账户.*(不足|停)`)
|
||||
// brokeWords: a 429 that says the balance itself is spent, as Zhipu
|
||||
// answers a GLM Coding Plan's key at the pay-as-you-go endpoint (1113
|
||||
// "余额不足或无可用资源包,请充值") — out of credit, not a rate limit;
|
||||
@@ -346,26 +346,26 @@ var (
|
||||
// prepaid API credits are spent: its underscores kept "credits
|
||||
// exhausted" from matching, so it read as a rate limit and the same
|
||||
// key was asked again rather than the next account
|
||||
brokeWords = regexp.MustCompile(`(?i)insufficient.?(balance|credit|fund)|\bcredits? (are )?exhausted\b|credit.?balance.?exhausted|余额不足|欠费|请充值`)
|
||||
brokeWords = lazyre.New(`(?i)insufficient.?(balance|credit|fund)|\bcredits? (are )?exhausted\b|credit.?balance.?exhausted|余额不足|欠费|请充值`)
|
||||
// quotaWords: it has used up what its plan allows for now. The budget's
|
||||
// words needn't sit beside each other: LiteLLM's spent key answers 429
|
||||
// "Budget has been exceeded! Key=… (sk-…), Current cost: …, Max budget:
|
||||
// …" (#5111, wuxiaoqiang12) — its "has been" broke the pair, and read
|
||||
// as a plain rate limit the key was asked again every half an hour, the
|
||||
// user's quota-rest never read
|
||||
usedUpWords = regexp.MustCompile(`(?i)quota|usage.?limit|out of budget|budget.{0,32}(exceeded|exhausted)|limit.?reached|hit your .*limit|limit.{0,24}resets|exceeded.*(plan|limit)|额度|用量|套餐|上限`)
|
||||
usedUpWords = lazyre.New(`(?i)quota|usage.?limit|out of budget|budget.{0,32}(exceeded|exhausted)|limit.?reached|hit your .*limit|limit.{0,24}resets|exceeded.*(plan|limit)|额度|用量|套餐|上限`)
|
||||
// rateWords: a 429 that is a short rate limit — requests or tokens per
|
||||
// minute — which usedUpWords took for a used-up plan ("Rate limit
|
||||
// exceeded", "reached"): as magpie words an upstream error, with
|
||||
// "rate_limit_error" for its type, every such 429 was, and rested a
|
||||
// quarter of an hour rather than a minute (#153).
|
||||
// "Frequency limit" is the English of 频率 (zoecats on Discord).
|
||||
rateWords = regexp.MustCompile(`(?i)rate.?limit|frequency.?limit|too many requests|per.?(second|sec|minute|min)\b|\b[rt]pm\b|频率|太频繁|过于频繁|速率`)
|
||||
rateWords = lazyre.New(`(?i)rate.?limit|frequency.?limit|too many requests|per.?(second|sec|minute|min)\b|\b[rt]pm\b|频率|太频繁|过于频繁|速率`)
|
||||
// plannedWords: a 429 that says the plan's own allowance is used, rate
|
||||
// words or not — a day's free requests, say, or a sub2api key's own
|
||||
// 5-hour, day or 7-day limit ("api key 7天限额已用完", sent as
|
||||
// rate_limit_exceeded).
|
||||
plannedWords = regexp.MustCompile(`(?i)quota|usage.?limit|hit your .*limit|limit.{0,24}resets|per.?(day|week|month)|daily|weekly|monthly|额度|用量|套餐|限额已用完`)
|
||||
plannedWords = lazyre.New(`(?i)quota|usage.?limit|hit your .*limit|limit.{0,24}resets|per.?(day|week|month)|daily|weekly|monthly|额度|用量|套餐|限额已用完`)
|
||||
// minuteWords: a 429 that names a window of a minute or less, or the
|
||||
// rate itself — tokens or requests per minute, TPM, RPM — which some
|
||||
// vendors call a quota all the same: Gemini's "You exceeded your
|
||||
@@ -376,15 +376,15 @@ var (
|
||||
// of a quota that says nothing of when, with balance left
|
||||
// (monater.114514 on Discord). A longer window named beside it
|
||||
// (longWords) is still the plan's.
|
||||
minuteWords = regexp.MustCompile(`(?i)per.?(second|minute)|per.?(sec|min)\b|\b[rt]p[ms]\b|(token|call|request) rate limit|每分钟|每秒`)
|
||||
minuteWords = lazyre.New(`(?i)per.?(second|minute)|per.?(sec|min)\b|\b[rt]p[ms]\b|(token|call|request) rate limit|每分钟|每秒`)
|
||||
// longWords: a window longer than a minute, or a plan's own limit,
|
||||
// named in a 429 — what minuteWords' rate limit is not.
|
||||
longWords = regexp.MustCompile(`(?i)usage.?limit|hit your .*limit|limit.{0,24}resets|per.?(hour|day|week|month)|\bhours?\b|hourly|daily|weekly|monthly|\b[rt]p[dh]\b|额度已用|用量|套餐|限额已用完|小时|每天|每日|每周|每月`)
|
||||
longWords = lazyre.New(`(?i)usage.?limit|hit your .*limit|limit.{0,24}resets|per.?(hour|day|week|month)|\bhours?\b|hourly|daily|weekly|monthly|\b[rt]p[dh]\b|额度已用|用量|套餐|限额已用完|小时|每天|每日|每周|每月`)
|
||||
// urlWords: a link in an error, whose words are its path, not what the
|
||||
// vendor said: Azure's rate limit points to aka.ms/oai/quotaincrease
|
||||
urlWords = regexp.MustCompile(`https?://\S+`)
|
||||
urlWords = lazyre.New(`https?://\S+`)
|
||||
// resetsWords: Claude Code's "usage limit reached|<when it resets>".
|
||||
resetsWords = regexp.MustCompile(`(?i)limit reached\|(\d{10})\b`)
|
||||
resetsWords = lazyre.New(`(?i)limit reached\|(\d{10})\b`)
|
||||
// resetsWhen: a 429 that says in words when the account is back, as
|
||||
// WorkBuddy's do in both its builds (#1669): "将在 2026-10-11 20:16:02
|
||||
// UTC+8重置", "your usage will reset at 2026-10-11 12:37:53 UTC+8, ...".
|
||||
@@ -401,22 +401,22 @@ var (
|
||||
// build writes it since November (taoxiaoxin on Discord: "将在
|
||||
// 2026-11-06 17:13:04 (UTC+8) 重置"): unread, the refusal rested the
|
||||
// whole account a quarter of an hour as out of quota.
|
||||
resetsWhen = regexp.MustCompile(`(?i)(?:\bresets? at|将在|将于)\s*(\d{4})-(\d{1,2})-(\d{1,2})[ T](\d{1,2}):(\d{2}):(\d{2})\s*[((]?\s*(?:(?:UTC|GMT)([+-])(\d{1,2})(?::?(\d{2}))?|([+-])(\d{2})(\d{2}) (?-i:[A-Z]{2,5}))\s*[))]?(?:\s*(?:重置|[,.;,。;]))`)
|
||||
resetsWhen = lazyre.New(`(?i)(?:\bresets? at|将在|将于)\s*(\d{4})-(\d{1,2})-(\d{1,2})[ T](\d{1,2}):(\d{2}):(\d{2})\s*[((]?\s*(?:(?:UTC|GMT)([+-])(\d{1,2})(?::?(\d{2}))?|([+-])(\d{2})(\d{2}) (?-i:[A-Z]{2,5}))\s*[))]?(?:\s*(?:重置|[,.;,。;]))`)
|
||||
// monthlyWords: a refusal that says the allowance it used up is a
|
||||
// month's, as Ark's does ("You have exceeded the monthly usage quota")
|
||||
// and Zhipu's 1310 ("Weekly/Monthly Limit Exhausted"): the reset time
|
||||
// it writes can honestly be weeks off (longestSaid).
|
||||
monthlyWords = regexp.MustCompile(`(?i)\bmonthly\b|月度|每月|本月`)
|
||||
monthlyWords = lazyre.New(`(?i)\bmonthly\b|月度|每月|本月`)
|
||||
// otherModels: a refusal that says the account's other models still
|
||||
// answer ("切换其他模型", "switch to the other models"): its limit is
|
||||
// the model's, and the model alone rests
|
||||
otherModels = regexp.MustCompile(`(?i)switch(?:ing)? to (?:the )?other models?|切换(?:到)?其他模型`)
|
||||
otherModels = lazyre.New(`(?i)switch(?:ing)? to (?:the )?other models?|切换(?:到)?其他模型`)
|
||||
// modelCooling is a relay that pools credentials per model saying
|
||||
// those of the requested model cooled down: CLIProxyAPI's 429
|
||||
// model_cooldown, "All credentials for model model-a are cooling down
|
||||
// via provider upstream" (#3039, Welkon's relay), or OmniRoute's "All
|
||||
// credentials for the requested model are cooling down"
|
||||
modelCooling = regexp.MustCompile(`(?i)credentials for (?:the requested )?model .{0,200}?cooling down`)
|
||||
modelCooling = lazyre.New(`(?i)credentials for (?:the requested )?model .{0,200}?cooling down`)
|
||||
// clineFreeLimit: Cline's refusal of a free model whose day's allowance
|
||||
// is used up, 429 "Daily free limit reached on model deepseek/deepseek-
|
||||
// v4-flash. Try again in 23h 59m", as its own clients read it (cline/
|
||||
@@ -424,16 +424,16 @@ var (
|
||||
// isClineFreeModelLimitMessage, which tells the user to pick another
|
||||
// model): the limit is that model's, and the model alone rests
|
||||
// (#1398, wuasakura)
|
||||
clineFreeLimit = regexp.MustCompile(`(?i)free limit reached on model`)
|
||||
clineFreeLimit = lazyre.New(`(?i)free limit reached on model`)
|
||||
// tryAgainIn: how long Cline's free-model refusal says until it is
|
||||
// back ("Try again in 23h 59m"), in the units resetsInWords reads
|
||||
tryAgainIn = regexp.MustCompile(`(?i)\btry again in (?:(\d+)\s*d(?:ays?)?\b\s*)?(?:(\d+)\s*h(?:ours?|rs?)?\b\s*)?(?:(\d+)\s*m(?:in(?:utes?|s)?)?\b)?`)
|
||||
tryAgainIn = lazyre.New(`(?i)\btry again in (?:(\d+)\s*d(?:ays?)?\b\s*)?(?:(\d+)\s*h(?:ours?|rs?)?\b\s*)?(?:(\d+)\s*m(?:in(?:utes?|s)?)?\b)?`)
|
||||
// quotaCodes: a vendor's own code for a used-up allowance, which alone
|
||||
// makes a server error (5xx) one over the quota: Claude Code's resets
|
||||
// line, the ChatGPT backend's usage_limit_reached, Google's
|
||||
// RESOURCE_EXHAUSTED. A 5xx's words don't: a relay's 500 "当前模型 …
|
||||
// 负载已经达到上限,请稍后重试" is its load's limit, not the plan's (#1418).
|
||||
quotaCodes = regexp.MustCompile(`(?i)limit reached\|\d{10}\b|usage_limit_reached|RESOURCE_EXHAUSTED`)
|
||||
quotaCodes = lazyre.New(`(?i)limit reached\|\d{10}\b|usage_limit_reached|RESOURCE_EXHAUSTED`)
|
||||
// cutWords: a plugin's own error for the turn its upstream's stream
|
||||
// died mid-call: the model wrote its tool call as text, the text
|
||||
// stopped before the call was whole, and the plugin ends the turn as a
|
||||
@@ -444,7 +444,7 @@ var (
|
||||
// never named it, twice, before anything of the reply was given — the
|
||||
// model's glitch, not the account's, and asked again it mostly answers
|
||||
// (magpie-community/plugins#579)
|
||||
cutWords = regexp.MustCompile(`(?i)tool call, written as text, was cut short|native tool call has no name; it is not sent on as a tool`)
|
||||
cutWords = lazyre.New(`(?i)tool call, written as text, was cut short|native tool call has no name; it is not sent on as a tool`)
|
||||
)
|
||||
|
||||
// Why a candidate failed, as rest tells it.
|
||||
@@ -532,7 +532,7 @@ const reloopedError = "the model's reasoning was stuck in a loop before it said
|
||||
|
||||
// proxyDown is the error Go gives when the proxy itself can't be reached,
|
||||
// over HTTP (proxyconnect) or SOCKS (socks connect).
|
||||
var proxyDown = regexp.MustCompile(`proxyconnect |socks connect `)
|
||||
var proxyDown = lazyre.New(`proxyconnect |socks connect `)
|
||||
|
||||
// wordsOf is catalog.Words: an error body as its words are matched, with
|
||||
// the strings of a JSON body that escapes what isn't ASCII decoded (#1669).
|
||||
@@ -660,7 +660,7 @@ func minuteRate(body []byte) bool {
|
||||
// month ("hour allocated quota exceeded") and arrears (400 Arrearage) are
|
||||
// worded otherwise. OpenAI's own insufficient_quota is out of credit, so
|
||||
// this is DashScope's alone.
|
||||
var dashScopeTokenRate = regexp.MustCompile(`Allocated quota exceeded, please increase your quota limit|"(?:code|type)"\s*:\s*"insufficient_quota"`)
|
||||
var dashScopeTokenRate = lazyre.New(`Allocated quota exceeded, please increase your quota limit|"(?:code|type)"\s*:\s*"insufficient_quota"`)
|
||||
|
||||
// dashScopeRate says p is DashScope and its 429 is a rate per minute or
|
||||
// second (dashScopeTokenRate), not its free allowance or a plan's window.
|
||||
@@ -723,7 +723,7 @@ func restrictedRefused(p provider.Provider, status int, body []byte) bool {
|
||||
// suspended: "This service has been disabled in this account for violation
|
||||
// of Terms of Service. Please submit an appeal to continue using this
|
||||
// product." (bestony on Discord, an Antigravity account, 11-06).
|
||||
var googleToS = regexp.MustCompile(`(?i)disabled in this account for violation of Terms of Service`)
|
||||
var googleToS = lazyre.New(`(?i)disabled in this account for violation of Terms of Service`)
|
||||
|
||||
// googleSuspended says Google suspended p, an account signed in to
|
||||
// Antigravity or Gemini CLI, for its terms (googleToS): the account, not
|
||||
@@ -1128,7 +1128,7 @@ func resetsAt(body []byte, now time.Time) time.Duration {
|
||||
// time Z.ai named (Player on Discord: "reset at 2026-10-15 20:12", "not
|
||||
// asked again before 17:12"). Only these words, then a whole date and a
|
||||
// time to the minute at least, with no digit, colon or zone after it.
|
||||
var zhipuResets = regexp.MustCompile(`(?:\bYour limit will reset at|您的限额将在)\s*(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?(\s*\S{0,3})`)
|
||||
var zhipuResets = lazyre.New(`(?:\bYour limit will reset at|您的限额将在)\s*(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?(\s*\S{0,3})`)
|
||||
|
||||
// heldClock is when a key or model held out of its allowance is asked
|
||||
// again, as an error put in words says it. The agent reading it, or a
|
||||
@@ -1194,7 +1194,7 @@ func resetsZhipu(body []byte, now time.Time) time.Duration {
|
||||
// hours and minutes, as Factory's 402 does: "You've reached your weekly
|
||||
// standard usage limit (resets in 0h 19min)" (#1979). At least one of
|
||||
// them, each a number and its unit, and nothing else between.
|
||||
var resetsInWords = regexp.MustCompile(`(?i)\bresets? in (?:(\d+)\s*d(?:ays?)?\b\s*)?(?:(\d+)\s*h(?:ours?|rs?)?\b\s*)?(?:(\d+)\s*m(?:in(?:utes?|s)?)?\b)?`)
|
||||
var resetsInWords = lazyre.New(`(?i)\bresets? in (?:(\d+)\s*d(?:ays?)?\b\s*)?(?:(\d+)\s*h(?:ours?|rs?)?\b\s*)?(?:(\d+)\s*m(?:in(?:utes?|s)?)?\b)?`)
|
||||
|
||||
// quotaResetAfter: Antigravity's (Google Code Assist's) 429 for a model's
|
||||
// allowance used up, which writes how long until it is back as Go prints
|
||||
@@ -1203,7 +1203,7 @@ var resetsInWords = regexp.MustCompile(`(?i)\bresets? in (?:(\d+)\s*d(?:ays?)?\b
|
||||
// an hour of a quota that says nothing, and the account first in order
|
||||
// was asked again, and refused, every 15 minutes for the hours or days
|
||||
// its quota was out (Dani Ariyanto on Discord, 10-24).
|
||||
var quotaResetAfter = regexp.MustCompile(`(?i)\bquota will reset after ((?:\d+h)?(?:\d+m)?(?:\d+(?:\.\d+)?s)?)`)
|
||||
var quotaResetAfter = lazyre.New(`(?i)\bquota will reset after ((?:\d+h)?(?:\d+m)?(?:\d+(?:\.\d+)?s)?)`)
|
||||
|
||||
// resetsAfter is how long the refusal says until it is back
|
||||
// (resetsInWords, quotaResetAfter, soonWords), held to longestWritten. Zero when it
|
||||
@@ -1225,7 +1225,7 @@ func resetsAfter(body []byte) time.Duration {
|
||||
// long until it is back: "try again in 30 seconds", "retry after 20s",
|
||||
// "resets in 45 secs", "请 1 分钟后重试", "30秒后再试". The English minutes,
|
||||
// hours and days are resetsInWords' and tryAgainIn's.
|
||||
var soonWords = regexp.MustCompile(`(?i)\b(?:resets? (?:in|after)|try again in|retry (?:in|after))\s*(\d+(?:\.\d+)?)\s*(?:s|secs?|seconds?)\b|(\d+)\s*(秒|分钟)钟?\s*(?:之?后)`)
|
||||
var soonWords = lazyre.New(`(?i)\b(?:resets? (?:in|after)|try again in|retry (?:in|after))\s*(\d+(?:\.\d+)?)\s*(?:s|secs?|seconds?)\b|(\d+)\s*(秒|分钟)钟?\s*(?:之?后)`)
|
||||
|
||||
// soonest is the longest a refusal may say it is back in for a 429 to be
|
||||
// a rate limit waited out, not a plan used up: as long as a provider's
|
||||
|
||||
@@ -4,12 +4,12 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
@@ -56,7 +56,7 @@ func isClaudeScience(r *http.Request) bool {
|
||||
|
||||
// scienceSlug is a name Claude Science takes for an internal model's id
|
||||
// and leaves out of its picker (kor in its bundle).
|
||||
var scienceSlug = regexp.MustCompile(`^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$`)
|
||||
var scienceSlug = lazyre.New(`^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$`)
|
||||
|
||||
// scienceName is a model's name as Claude Science is shown it: a slug's
|
||||
// first letter in upper case, which its picker keeps.
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -20,6 +19,7 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/budget"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
@@ -876,7 +876,7 @@ func readYouSearch(b []byte) ([]foundPage, error) {
|
||||
return pages, nil
|
||||
}
|
||||
|
||||
var searchTags = regexp.MustCompile(`<[^>]*>`)
|
||||
var searchTags = lazyre.New(`<[^>]*>`)
|
||||
|
||||
// searchPlain is a search API's text without the tags it marks matches with
|
||||
// (Brave's <strong>), on one line.
|
||||
|
||||
@@ -3,8 +3,8 @@ package gateway
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -23,7 +23,7 @@ import (
|
||||
// not allowed, before or after it, or Pydantic's extra_forbidden located
|
||||
// there. An invalid value or a schema strict mode can't take is a
|
||||
// different fault and doesn't match.
|
||||
var toolStrictRefusal = regexp.MustCompile(`(?i)(?:unsupported|unknown|unrecognized|not (?:supported|allowed|permitted)|extra (?:fields?|inputs?|parameters?)|forbidden)[^\n{}]{0,120}?\btools(?:\[\d+\]|\.\d+)(?:\.[^\s.'"\x60]+)?\.strict\b|\btools(?:\[\d+\]|\.\d+)(?:\.[^\s.'"\x60]+)?\.strict\b['"\x60]?[^\n{}]{0,40}?(?:unsupported|unknown|unrecognized|not (?:supported|allowed|permitted)|extra_forbidden|forbidden)|"loc"\s*:\s*\[\s*(?:"body"\s*,\s*)?"tools"\s*,\s*\d+\s*,\s*(?:"function"\s*,\s*)?"strict"\s*\][^{}]*"type"\s*:\s*"extra_forbidden"|"type"\s*:\s*"extra_forbidden"[^{}]*"loc"\s*:\s*\[\s*(?:"body"\s*,\s*)?"tools"\s*,\s*\d+\s*,\s*(?:"function"\s*,\s*)?"strict"\s*\]`)
|
||||
var toolStrictRefusal = lazyre.New(`(?i)(?:unsupported|unknown|unrecognized|not (?:supported|allowed|permitted)|extra (?:fields?|inputs?|parameters?)|forbidden)[^\n{}]{0,120}?\btools(?:\[\d+\]|\.\d+)(?:\.[^\s.'"\x60]+)?\.strict\b|\btools(?:\[\d+\]|\.\d+)(?:\.[^\s.'"\x60]+)?\.strict\b['"\x60]?[^\n{}]{0,40}?(?:unsupported|unknown|unrecognized|not (?:supported|allowed|permitted)|extra_forbidden|forbidden)|"loc"\s*:\s*\[\s*(?:"body"\s*,\s*)?"tools"\s*,\s*\d+\s*,\s*(?:"function"\s*,\s*)?"strict"\s*\][^{}]*"type"\s*:\s*"extra_forbidden"|"type"\s*:\s*"extra_forbidden"[^{}]*"loc"\s*:\s*\[\s*(?:"body"\s*,\s*)?"tools"\s*,\s*\d+\s*,\s*(?:"function"\s*,\s*)?"strict"\s*\]`)
|
||||
|
||||
// toolStrictRefused is how unfit remembers a provider refusing it: the
|
||||
// provider's validator, not a model, turns it away.
|
||||
|
||||
@@ -4,10 +4,11 @@ import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"unicode"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// A model deep into a long conversation may write its tool calls into its
|
||||
@@ -114,14 +115,14 @@ var (
|
||||
// DeepSeek's DSML pipes, a namespace (minimax:), or nothing, the plain
|
||||
// invoke
|
||||
invokePre = `(?:[||][\s||]*DSML[\s||]*|[A-Za-z_][\w-]*:)?`
|
||||
dsmlInvoke = regexp.MustCompile(`<\s*` + invokePre + `invoke\s+name\s*=\s*"([^"]+)"\s*>`)
|
||||
dsmlParam = regexp.MustCompile(`(?s)<\s*` + invokePre + `parameter\s+name\s*=\s*"([^"]+)"((?:\s+\w+\s*=\s*"[^"]*")*)\s*>(.*?)<\s*/?\s*` + invokePre + `parameter\s*>`)
|
||||
dsmlClose = regexp.MustCompile(`<\s*/\s*` + invokePre + `invoke\s*>`)
|
||||
dsmlString = regexp.MustCompile(`string\s*=\s*"true"`)
|
||||
dsmlInvoke = lazyre.New(`<\s*` + invokePre + `invoke\s+name\s*=\s*"([^"]+)"\s*>`)
|
||||
dsmlParam = lazyre.New(`(?s)<\s*` + invokePre + `parameter\s+name\s*=\s*"([^"]+)"((?:\s+\w+\s*=\s*"[^"]*")*)\s*>(.*?)<\s*/?\s*` + invokePre + `parameter\s*>`)
|
||||
dsmlClose = lazyre.New(`<\s*/\s*` + invokePre + `invoke\s*>`)
|
||||
dsmlString = lazyre.New(`string\s*=\s*"true"`)
|
||||
// what is left of the tags once the calls are read out, and the
|
||||
// braces, quotes or > GLM leaves before a close (#1945); and the
|
||||
// plain invoke's, with its wrappers
|
||||
textCallJunk = regexp.MustCompile(dsmlTag + `[^<>]*>?|[}\]"'>]*\s*</tool_calls?>|<tool_calls?>|<\s*/?\s*(?:[A-Za-z_][\w-]*:)?(?:invoke|parameter|function_calls|tool_calls?)\b[^<>]*>`)
|
||||
textCallJunk = lazyre.New(dsmlTag + `[^<>]*>?|[}\]"'>]*\s*</tool_calls?>|<tool_calls?>|<\s*/?\s*(?:[A-Za-z_][\w-]*:)?(?:invoke|parameter|function_calls|tool_calls?)\b[^<>]*>`)
|
||||
)
|
||||
|
||||
// textCallNames are the tools a request offers, by name.
|
||||
@@ -533,8 +534,8 @@ func hermesCall(s string, names map[string]bool) (writtenCall, int, bool) {
|
||||
}
|
||||
|
||||
var (
|
||||
paramHead = regexp.MustCompile(`^\s*\{\s*"name"\s*:\s*"([^"]+)"\s*\}?\s*>?`)
|
||||
paramOpen = regexp.MustCompile(`^\s*<parameter(?:\s+name\s*=\s*"([^"]+)"|=([^\s>]+))\s*>`)
|
||||
paramHead = lazyre.New(`^\s*\{\s*"name"\s*:\s*"([^"]+)"\s*\}?\s*>?`)
|
||||
paramOpen = lazyre.New(`^\s*<parameter(?:\s+name\s*=\s*"([^"]+)"|=([^\s>]+))\s*>`)
|
||||
)
|
||||
|
||||
// paramCall reads a call DeepSeek wrote half as Hermes' block and half as
|
||||
@@ -597,8 +598,8 @@ func paramCall(s string, names map[string]bool) (writtenCall, int, bool) {
|
||||
}
|
||||
|
||||
var (
|
||||
glmPair = regexp.MustCompile(`(?s)^\s*<arg_key>(.*?)</arg_key>\s*<arg_value>(.*?)</arg_value>`)
|
||||
glmName = regexp.MustCompile(`^\s*([^\s<>{}"]+)\s*`)
|
||||
glmPair = lazyre.New(`(?s)^\s*<arg_key>(.*?)</arg_key>\s*<arg_value>(.*?)</arg_value>`)
|
||||
glmName = lazyre.New(`^\s*([^\s<>{}"]+)\s*`)
|
||||
)
|
||||
|
||||
// glmCall reads GLM's own call (#906, nullburn: GLM-5.3-Flash through
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
// an assistant turn of the tool loop being continued with no thinking is
|
||||
// refused, one with a space is taken, as are finished turns and plain
|
||||
// replies without.
|
||||
var thinkingBackRefusal = regexp.MustCompile("(?i)`?(?:content\\[\\]\\.thinking|reasoning_content)`? in the thinking mode must be passed back")
|
||||
var thinkingBackRefusal = lazyre.New("(?i)`?(?:content\\[\\]\\.thinking|reasoning_content)`? in the thinking mode must be passed back")
|
||||
|
||||
// reasoningBackWords are a model asking for an earlier assistant
|
||||
// message's reasoning in other words than thinkingBackRefusal's:
|
||||
@@ -26,7 +26,7 @@ var thinkingBackRefusal = regexp.MustCompile("(?i)`?(?:content\\[\\]\\.thinking|
|
||||
// has none (EDwinpzy on Discord, magpie 0.1.2717), and the like that name
|
||||
// reasoning_content as missing or required. A request missing what every
|
||||
// API requires ("Missing required parameter: 'messages'") isn't one.
|
||||
var reasoningBackWords = regexp.MustCompile(`(?i)\breasoning_content\b[^"]{0,40}\b(?:is (?:missing|required)|must be (?:passed|provided|included))|\b(?:missing|required)\b[^"]{0,80}\breasoning_content\b`)
|
||||
var reasoningBackWords = lazyre.New(`(?i)\breasoning_content\b[^"]{0,40}\b(?:is (?:missing|required)|must be (?:passed|provided|included))|\b(?:missing|required)\b[^"]{0,80}\breasoning_content\b`)
|
||||
|
||||
// reasoningBackRefused says a model turned the request away for an
|
||||
// earlier turn's reasoning it didn't have: a demand of that model's on the
|
||||
|
||||
@@ -5,12 +5,12 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -39,10 +39,10 @@ import (
|
||||
// boundRefusal is Claude's refusal of a thinking block it didn't sign for
|
||||
// this conversation or account: the signature's wording, the newer
|
||||
// binding's, and a redacted_thinking block's.
|
||||
var boundRefusal = regexp.MustCompile("(?i)invalid `?signature`? in `?thinking`? block|bound to a different conversation|not created in this conversation|invalid data in `?redacted_thinking`? block")
|
||||
var boundRefusal = lazyre.New("(?i)invalid `?signature`? in `?thinking`? block|bound to a different conversation|not created in this conversation|invalid data in `?redacted_thinking`? block")
|
||||
|
||||
// boundAt is where the refusal says the block is: messages.<m>.content.<b>.
|
||||
var boundAt = regexp.MustCompile(`messages\.(\d+)\.content\.(\d+)`)
|
||||
var boundAt = lazyre.New(`messages\.(\d+)\.content\.(\d+)`)
|
||||
|
||||
// thinkingRefusedMost bounds the signatures remembered; past it the
|
||||
// memory starts again, and a conversation still going is mended by one
|
||||
@@ -269,8 +269,8 @@ func withoutForeignThinking(p provider.Provider, body []byte) []byte {
|
||||
|
||||
// thinkingTyped is a body with a thinking block in it, for one that says
|
||||
// no signature at all.
|
||||
var thinkingTyped = regexp.MustCompile(`"type"\s*:\s*"thinking"`)
|
||||
var thinkingTyped = lazyre.New(`"type"\s*:\s*"thinking"`)
|
||||
|
||||
// deepseekSignature is the signature DeepSeek's Anthropic endpoint gives
|
||||
// its thinking: the reply's id, a UUID.
|
||||
var deepseekSignature = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
|
||||
var deepseekSignature = lazyre.New(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -15,7 +14,7 @@ import (
|
||||
// no thinking) with `thinking.type must be "enabled"` (cybercaius on
|
||||
// Discord, v0.1.1862, his own 天翼云 provider). Read off the reply, not
|
||||
// the provider: any upstream that says it is asked again thinking.
|
||||
var thinkingNeededRefusal = regexp.MustCompile(`(?i)thinking[._ ]type\W+(?:must|should|has to) be\W+enabled\b`)
|
||||
var thinkingNeededRefusal = lazyre.New(`(?i)thinking[._ ]type\W+(?:must|should|has to) be\W+enabled\b`)
|
||||
|
||||
// thinkingNeeded is how unfit remembers an upstream that takes model only
|
||||
// with thinking enabled (thinkingNeededRefusal).
|
||||
|
||||
@@ -6,12 +6,12 @@ import (
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
@@ -347,12 +347,12 @@ func resultSum(p Part) string {
|
||||
// id, and its shell's duration_seconds.
|
||||
var runNoise = []struct {
|
||||
mark string // in a result the expression may change
|
||||
re *regexp.Regexp
|
||||
re *lazyre.RE
|
||||
with string
|
||||
}{
|
||||
{"Wall time", regexp.MustCompile(`(?m)^(Wall time:? )[0-9.]+( seconds?)`), "${1}#${2}"},
|
||||
{"Chunk ID: ", regexp.MustCompile(`(?m)^(Chunk ID: )\S+`), "${1}#"},
|
||||
{`"duration_seconds"`, regexp.MustCompile(`("duration_seconds"\s*:\s*)[0-9.eE+-]+`), "${1}#"},
|
||||
{"Wall time", lazyre.New(`(?m)^(Wall time:? )[0-9.]+( seconds?)`), "${1}#${2}"},
|
||||
{"Chunk ID: ", lazyre.New(`(?m)^(Chunk ID: )\S+`), "${1}#"},
|
||||
{`"duration_seconds"`, lazyre.New(`("duration_seconds"\s*:\s*)[0-9.eE+-]+`), "${1}#"},
|
||||
}
|
||||
|
||||
func steadyResult(s string) string {
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -14,6 +13,7 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/gwtool"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
)
|
||||
|
||||
@@ -58,7 +58,7 @@ type mcpTool struct {
|
||||
name string // <plugin>_<tool>
|
||||
}
|
||||
|
||||
var unsafeToolChars = regexp.MustCompile(`[^A-Za-z0-9_-]+`)
|
||||
var unsafeToolChars = lazyre.New(`[^A-Za-z0-9_-]+`)
|
||||
|
||||
// toolPrefix is the plugin's part of its tools' names: its short name
|
||||
// (opencode-weather-tools → weather-tools), in the characters MCP clients
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"regexp"
|
||||
|
||||
"github.com/yetone/magpie/internal/capre"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -42,7 +43,7 @@ var anthropicToolName = capre.MustCompile(`^[a-zA-Z0-9_-]+$`, 128)
|
||||
// tools: Anthropic's "must define tools", Bedrock's "The toolConfig field
|
||||
// must be defined when using toolUse and toolResult content blocks", or
|
||||
// tools said required beside the calls.
|
||||
var toolsMissing = regexp.MustCompile("(?i)must define tools|toolconfig field must be defined|tools?\\W{1,4}(?:param(?:eter)?|field)?\\W{0,4}(?:is |are )?(?:required|must be (?:defined|provided|specified))[^\\n]{0,80}(?:tool_calls?|tool_use|tool_result|toolUse|toolResult|function_call)")
|
||||
var toolsMissing = lazyre.New("(?i)must define tools|toolconfig field must be defined|tools?\\W{1,4}(?:param(?:eter)?|field)?\\W{0,4}(?:is |are )?(?:required|must be (?:defined|provided|specified))[^\\n]{0,80}(?:tool_calls?|tool_use|tool_result|toolUse|toolResult|function_call)")
|
||||
|
||||
// toolNotDeclared is what follows or leads a tool's name in a refusal of
|
||||
// a call to it: not found, not defined, unknown.
|
||||
|
||||
@@ -16,13 +16,13 @@ import (
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
@@ -555,7 +555,7 @@ func ptrs(pics []picture) []*picture {
|
||||
|
||||
// decimalNumber is a number as JSON writes it, not as Go's ParseFloat also
|
||||
// takes it (hex, inf, nan, underscores).
|
||||
var decimalNumber = regexp.MustCompile(`^[0-9]+(\.[0-9]*)?([eE][+-]?[0-9]+)?$`)
|
||||
var decimalNumber = lazyre.New(`^[0-9]+(\.[0-9]*)?([eE][+-]?[0-9]+)?$`)
|
||||
|
||||
// parseSeconds is a duration in whole seconds, however it was written: 6,
|
||||
// "6", 6.0, 6e0. What the vendor's limit makes of a length it says itself.
|
||||
@@ -793,7 +793,7 @@ func signer(p provider.Provider) string {
|
||||
|
||||
// idPart is what a provider id or a vendor's request id is made of; an id
|
||||
// is put in a URL, so nothing that would change its path gets through.
|
||||
var idPart = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
|
||||
var idPart = lazyre.New(`^[A-Za-z0-9_-]+$`)
|
||||
|
||||
// parseVideoID is the provider, vendor id, start and signer of a video's id.
|
||||
func parseVideoID(id string) (providerID, vendorID string, started time.Time, by string, ok bool) {
|
||||
|
||||
@@ -8,12 +8,12 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -197,7 +197,7 @@ func minimaxRatio(f filming) string {
|
||||
|
||||
// minimaxCode is the code MiniMax put at the end of its message: "insufficient
|
||||
// balance (1008)" is 1008.
|
||||
var minimaxCode = regexp.MustCompile(`\((\d{3,5})\)\s*$`)
|
||||
var minimaxCode = lazyre.New(`\((\d{3,5})\)\s*$`)
|
||||
|
||||
// minimaxSaid is what MiniMax's answer b says went wrong, and its code: its
|
||||
// OpenAI-shaped error, or the base_resp its older APIs answer with.
|
||||
|
||||
@@ -10,13 +10,13 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -834,7 +834,7 @@ func smallModelWhere(p provider.Provider, kind string, keep func(catalog.Model)
|
||||
// endpoints found that support image input", vLLM's "is not a multimodal
|
||||
// model", and the plain "does not support image input" / "image input is
|
||||
// not supported" / "不支持图片" of the rest.
|
||||
var imageRefusedWords = regexp.MustCompile("(?i)unknown variant [`'\"\\\\]*(?:image_url|input_image|image)\\b|image_url is only supported by certain models|no endpoints found that support image|not a multi-?modal model|(?:does not|doesn't|do not|don't|cannot|can't|unable to) (?:support|accept|process|handle|take|read) (?:the )?(?:image|images|vision|multi-?modal)|\\b(?:image|images|vision|multi-?modal|image_url|input_image)(?: (?:input|inputs|content|parts?))? (?:is |are )?(?:not supported|unsupported|not enabled|not allowed)|不支持(?:图片|图像|多模态|视觉|识图)")
|
||||
var imageRefusedWords = lazyre.New("(?i)unknown variant [`'\"\\\\]*(?:image_url|input_image|image)\\b|image_url is only supported by certain models|no endpoints found that support image|not a multi-?modal model|(?:does not|doesn't|do not|don't|cannot|can't|unable to) (?:support|accept|process|handle|take|read) (?:the )?(?:image|images|vision|multi-?modal)|\\b(?:image|images|vision|multi-?modal|image_url|input_image)(?: (?:input|inputs|content|parts?))? (?:is |are )?(?:not supported|unsupported|not enabled|not allowed)|不支持(?:图片|图像|多模态|视觉|识图)")
|
||||
|
||||
// imageRefused says a failure was the model turning the request's image
|
||||
// away: what a describer fixes by describing it, not what another
|
||||
|
||||
@@ -4,9 +4,9 @@ import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"golang.org/x/image/webp"
|
||||
)
|
||||
@@ -32,7 +32,7 @@ const webpRefused = "image/webp"
|
||||
// took for a file and found none of its file fields in, and the pair of
|
||||
// codes in the double brackets it puts before them. Read of the words
|
||||
// wordsOf gives, as a relay may pass them on \u-escaped (#1669).
|
||||
var zhipuImageRefusal = regexp.MustCompile(`必须传入file_id、file_url、file_data至少之一|图片输入格式|\[(?:1210|1214)\]\[`)
|
||||
var zhipuImageRefusal = lazyre.New(`必须传入file_id、file_url、file_data至少之一|图片输入格式|\[(?:1210|1214)\]\[`)
|
||||
|
||||
// mayHoldWebP is whether the body may hold a webp: an image/webp type, or
|
||||
// the base64 of a RIFF file's head, wherever its base64 starts (a webp
|
||||
|
||||
@@ -29,29 +29,29 @@ import (
|
||||
"html"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
var (
|
||||
ccWorkDir = regexp.MustCompile(`(?m)^(?: - )?Primary working directory: (.+)$`)
|
||||
ccWorkDir = lazyre.New(`(?m)^(?: - )?Primary working directory: (.+)$`)
|
||||
// the folder a <cwd> holds: Codex's on its line, Pi's on its own
|
||||
cwdTag = regexp.MustCompile(`<cwd>\s*([^<\n]+?)\s*</cwd>`)
|
||||
envDir = regexp.MustCompile(`(?m)^\s*Working directory: (.+)$`)
|
||||
cwdTag = lazyre.New(`<cwd>\s*([^<\n]+?)\s*</cwd>`)
|
||||
envDir = lazyre.New(`(?m)^\s*Working directory: (.+)$`)
|
||||
// a --bare run's whole system prompt is "CWD: /x"
|
||||
bareCWD = regexp.MustCompile(`(?m)^\s*(?: - )?CWD: (.+)$`)
|
||||
bareCWD = lazyre.New(`(?m)^\s*(?: - )?CWD: (.+)$`)
|
||||
// pi 1.1 states its folder as a line, where its <cwd> wraps it
|
||||
piDir = regexp.MustCompile(`(?m)^\s*(?: - )?Current working directory: (.+)$`)
|
||||
wasDir = regexp.MustCompile(` \(was .*\)$`)
|
||||
piDir = lazyre.New(`(?m)^\s*(?: - )?Current working directory: (.+)$`)
|
||||
wasDir = lazyre.New(` \(was .*\)$`)
|
||||
)
|
||||
|
||||
// dirForm is one form a caller states its folder in. wrap, when set, is
|
||||
// the caller's own block the form is read inside: in a turn, a form is a
|
||||
// caller's word only inside the block it states it in (#4940).
|
||||
type dirForm struct {
|
||||
re *regexp.Regexp
|
||||
re *lazyre.RE
|
||||
wrap string
|
||||
was bool // a moved-folder line, its " (was …)" dropped
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@ package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -17,8 +17,8 @@ import (
|
||||
// unavailable" when its bucket is spent. The plugin's words, after any
|
||||
// "<provider>: " put in front of them.
|
||||
var (
|
||||
zcodeEndedWords = regexp.MustCompile(`(?:^|: )ZCode has no active limited quota for (\S+)$`)
|
||||
zcodeSpentWords = regexp.MustCompile(`(?:^|: )ZCode's limited quota for (\S+) is exhausted or temporarily unavailable$`)
|
||||
zcodeEndedWords = lazyre.New(`(?:^|: )ZCode has no active limited quota for (\S+)$`)
|
||||
zcodeSpentWords = lazyre.New(`(?:^|: )ZCode's limited quota for (\S+) is exhausted or temporarily unavailable$`)
|
||||
)
|
||||
|
||||
// zcodeTrialRefused says c, a ZCode plugin account asked for one of its
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// Package lazyre holds a regular expression that is compiled the first
|
||||
// time it is used, not when its package starts.
|
||||
//
|
||||
// magpie is one binary, so every package's init runs on every launch,
|
||||
// `magpie statusline` (run by Claude Code on each message) included.
|
||||
// Hundreds of package-level regexp.MustCompile calls cost several MB and
|
||||
// milliseconds there for patterns that launch never reaches. An RE has
|
||||
// the methods of *regexp.Regexp that magpie calls; Regexp returns the
|
||||
// compiled one. A bad pattern panics on first use, so TestAllCompile in
|
||||
// each converted package compiles every one before release.
|
||||
package lazyre
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// RE is a regexp compiled on first use. Safe for concurrent use.
|
||||
type RE struct {
|
||||
src string
|
||||
once sync.Once
|
||||
re *regexp.Regexp
|
||||
}
|
||||
|
||||
var (
|
||||
allMu sync.Mutex
|
||||
all []*RE
|
||||
)
|
||||
|
||||
// New returns an RE for src. It does not compile it.
|
||||
func New(src string) *RE {
|
||||
r := &RE{src: src}
|
||||
allMu.Lock()
|
||||
all = append(all, r)
|
||||
allMu.Unlock()
|
||||
return r
|
||||
}
|
||||
|
||||
// Of wraps an expression already compiled, for a field that holds both
|
||||
// kinds.
|
||||
func Of(re *regexp.Regexp) *RE {
|
||||
r := &RE{src: re.String(), re: re}
|
||||
r.once.Do(func() {})
|
||||
return r
|
||||
}
|
||||
|
||||
// MustAll compiles every RE made so far and returns how many there are,
|
||||
// so a test fails on a bad pattern.
|
||||
func MustAll() int {
|
||||
allMu.Lock()
|
||||
rs := append([]*RE(nil), all...)
|
||||
allMu.Unlock()
|
||||
for _, r := range rs {
|
||||
r.Regexp()
|
||||
}
|
||||
return len(rs)
|
||||
}
|
||||
|
||||
// Regexp returns the compiled expression, compiling it the first time.
|
||||
func (r *RE) Regexp() *regexp.Regexp {
|
||||
r.once.Do(func() { r.re = regexp.MustCompile(r.src) })
|
||||
return r.re
|
||||
}
|
||||
|
||||
func (r *RE) String() string { return r.src }
|
||||
func (r *RE) MatchString(s string) bool { return r.Regexp().MatchString(s) }
|
||||
func (r *RE) Match(b []byte) bool { return r.Regexp().Match(b) }
|
||||
func (r *RE) NumSubexp() int { return r.Regexp().NumSubexp() }
|
||||
func (r *RE) SubexpNames() []string { return r.Regexp().SubexpNames() }
|
||||
func (r *RE) SubexpIndex(name string) int { return r.Regexp().SubexpIndex(name) }
|
||||
func (r *RE) LiteralPrefix() (string, bool) { return r.Regexp().LiteralPrefix() }
|
||||
func (r *RE) Find(b []byte) []byte { return r.Regexp().Find(b) }
|
||||
func (r *RE) FindIndex(b []byte) []int { return r.Regexp().FindIndex(b) }
|
||||
func (r *RE) FindSubmatch(b []byte) [][]byte { return r.Regexp().FindSubmatch(b) }
|
||||
func (r *RE) FindSubmatchIndex(b []byte) []int { return r.Regexp().FindSubmatchIndex(b) }
|
||||
func (r *RE) FindString(s string) string { return r.Regexp().FindString(s) }
|
||||
func (r *RE) FindStringIndex(s string) []int { return r.Regexp().FindStringIndex(s) }
|
||||
func (r *RE) FindStringSubmatch(s string) []string {
|
||||
return r.Regexp().FindStringSubmatch(s)
|
||||
}
|
||||
func (r *RE) FindStringSubmatchIndex(s string) []int {
|
||||
return r.Regexp().FindStringSubmatchIndex(s)
|
||||
}
|
||||
func (r *RE) FindAll(b []byte, n int) [][]byte { return r.Regexp().FindAll(b, n) }
|
||||
func (r *RE) FindAllIndex(b []byte, n int) [][]int { return r.Regexp().FindAllIndex(b, n) }
|
||||
func (r *RE) FindAllSubmatch(b []byte, n int) [][][]byte {
|
||||
return r.Regexp().FindAllSubmatch(b, n)
|
||||
}
|
||||
func (r *RE) FindAllSubmatchIndex(b []byte, n int) [][]int {
|
||||
return r.Regexp().FindAllSubmatchIndex(b, n)
|
||||
}
|
||||
func (r *RE) FindAllString(s string, n int) []string { return r.Regexp().FindAllString(s, n) }
|
||||
func (r *RE) FindAllStringIndex(s string, n int) [][]int {
|
||||
return r.Regexp().FindAllStringIndex(s, n)
|
||||
}
|
||||
func (r *RE) FindAllStringSubmatch(s string, n int) [][]string {
|
||||
return r.Regexp().FindAllStringSubmatch(s, n)
|
||||
}
|
||||
func (r *RE) FindAllStringSubmatchIndex(s string, n int) [][]int {
|
||||
return r.Regexp().FindAllStringSubmatchIndex(s, n)
|
||||
}
|
||||
func (r *RE) ReplaceAll(src, repl []byte) []byte { return r.Regexp().ReplaceAll(src, repl) }
|
||||
func (r *RE) ReplaceAllLiteral(src, repl []byte) []byte {
|
||||
return r.Regexp().ReplaceAllLiteral(src, repl)
|
||||
}
|
||||
func (r *RE) ReplaceAllFunc(src []byte, f func([]byte) []byte) []byte {
|
||||
return r.Regexp().ReplaceAllFunc(src, f)
|
||||
}
|
||||
func (r *RE) ReplaceAllString(src, repl string) string {
|
||||
return r.Regexp().ReplaceAllString(src, repl)
|
||||
}
|
||||
func (r *RE) ReplaceAllLiteralString(src, repl string) string {
|
||||
return r.Regexp().ReplaceAllLiteralString(src, repl)
|
||||
}
|
||||
func (r *RE) ReplaceAllStringFunc(src string, f func(string) string) string {
|
||||
return r.Regexp().ReplaceAllStringFunc(src, f)
|
||||
}
|
||||
func (r *RE) Split(s string, n int) []string { return r.Regexp().Split(s, n) }
|
||||
func (r *RE) Expand(dst, template, src []byte, match []int) []byte {
|
||||
return r.Regexp().Expand(dst, template, src, match)
|
||||
}
|
||||
func (r *RE) ExpandString(dst []byte, template string, src string, match []int) []byte {
|
||||
return r.Regexp().ExpandString(dst, template, src, match)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package lazyre
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCompiledOnFirstUse(t *testing.T) {
|
||||
r := New(`a(b+)`)
|
||||
if r.re != nil {
|
||||
t.Fatal("compiled at New")
|
||||
}
|
||||
if got := r.FindStringSubmatch("xabbb"); len(got) != 2 || got[1] != "bbb" {
|
||||
t.Fatalf("FindStringSubmatch = %q", got)
|
||||
}
|
||||
if r.re == nil {
|
||||
t.Fatal("not compiled after use")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentFirstUse(t *testing.T) {
|
||||
r := New(`^[0-9]+$`)
|
||||
var wg sync.WaitGroup
|
||||
for range 16 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if !r.MatchString("123") {
|
||||
t.Error("no match")
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestBadPatternPanicsInMustAll(t *testing.T) {
|
||||
defer func() {
|
||||
allMu.Lock()
|
||||
all = all[:len(all)-1]
|
||||
allMu.Unlock()
|
||||
if recover() == nil {
|
||||
t.Fatal("MustAll did not panic on a bad pattern")
|
||||
}
|
||||
}()
|
||||
New(`(`)
|
||||
MustAll()
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// A masked word that is a date matches that calendar date however it is
|
||||
@@ -31,11 +33,11 @@ import (
|
||||
const dateSep = `(?:[ \t]*[-/.、/-][ \t]*|[ \t])`
|
||||
|
||||
var (
|
||||
dateYMD = regexp.MustCompile(`^(\d{4})` + dateSep + `(\d{1,2})` + dateSep + `(\d{1,2})\.?$`)
|
||||
dateCJK = regexp.MustCompile(`^(\d{4})[ \t]*[年년][ \t]*(\d{1,2})[ \t]*[月월][ \t]*(\d{1,2})[ \t]*[日号號일]?$`)
|
||||
dateDMY = regexp.MustCompile(`^(\d{1,2})` + dateSep + `(\d{1,2})` + dateSep + `(\d{4})$`)
|
||||
dateNameF = regexp.MustCompile(`^([A-Za-z]+)\.?[ \t]+(\d{1,2})(?:st|nd|rd|th)?,?[ \t]+(\d{4})$`)
|
||||
dateNameB = regexp.MustCompile(`^(\d{1,2})(?:st|nd|rd|th)?(?:[ \t]+|-)([A-Za-z]+)\.?,?(?:[ \t]+|-)(\d{4})$`)
|
||||
dateYMD = lazyre.New(`^(\d{4})` + dateSep + `(\d{1,2})` + dateSep + `(\d{1,2})\.?$`)
|
||||
dateCJK = lazyre.New(`^(\d{4})[ \t]*[年년][ \t]*(\d{1,2})[ \t]*[月월][ \t]*(\d{1,2})[ \t]*[日号號일]?$`)
|
||||
dateDMY = lazyre.New(`^(\d{1,2})` + dateSep + `(\d{1,2})` + dateSep + `(\d{4})$`)
|
||||
dateNameF = lazyre.New(`^([A-Za-z]+)\.?[ \t]+(\d{1,2})(?:st|nd|rd|th)?,?[ \t]+(\d{4})$`)
|
||||
dateNameB = lazyre.New(`^(\d{1,2})(?:st|nd|rd|th)?(?:[ \t]+|-)([A-Za-z]+)\.?,?(?:[ \t]+|-)(\d{4})$`)
|
||||
)
|
||||
|
||||
var monthNames = []string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// What follows a secret's name and a colon or = is not always the secret.
|
||||
@@ -71,7 +73,7 @@ func fieldAt(s string, a, b int) bool {
|
||||
// .RELEASE, +build.5) or a number alone. One letter on its own is a
|
||||
// part only with a number after it (b1, M2), so 3.14159abc is no
|
||||
// version.
|
||||
var versionRangeRe = regexp.MustCompile(`^(?:[~^]|[<>=!~]=?|==)?[vV]?\d+(?:\.\d+)+` +
|
||||
var versionRangeRe = lazyre.New(`^(?:[~^]|[<>=!~]=?|==)?[vV]?\d+(?:\.\d+)+` +
|
||||
`(?:[-+._]?(?:(?i:alpha|beta|rc|pre|preview|post|dev|canary|next|nightly|snapshot|release|final|ga|stable|build|incubating)\d*|[abcmABCM]\d+|\d+))*$`)
|
||||
|
||||
// versionValue says v is a release's version, which no secret is: the
|
||||
@@ -87,7 +89,7 @@ func versionValue(v string) bool { return versionRangeRe.MatchString(v) }
|
||||
// 2026-08-30T11 and the minutes went out as written (dchaofei, #5002). A
|
||||
// date alone has no letter in it and secretValue keeps it already; the T
|
||||
// and the hour are what read as a key's letters.
|
||||
var stampRe = regexp.MustCompile(`^\d{4}-\d{1,2}-\d{1,2}[Tt]\d{1,2}(?::\d{1,2}){0,2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:?\d{2})?$`)
|
||||
var stampRe = lazyre.New(`^\d{4}-\d{1,2}-\d{1,2}[Tt]\d{1,2}(?::\d{1,2}){0,2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:?\d{2})?$`)
|
||||
|
||||
// timestampValue says v is a moment's writing, which no secret is: an
|
||||
// expiry, a renewal, an update (fieldAt, keyAt, namedSecret).
|
||||
@@ -111,12 +113,12 @@ func skillName(s string, a, b int) bool {
|
||||
|
||||
// skillSlugRe is words in lower case joined by hyphens: a plugin's, a skill's
|
||||
// or a command's name.
|
||||
var skillSlugRe = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)+$`)
|
||||
var skillSlugRe = lazyre.New(`^[a-z0-9]+(?:-[a-z0-9]+)+$`)
|
||||
|
||||
// lineRefRe is a line or a range of lines, as an editor or a review names
|
||||
// them: L643, L643-669, L12-L40, 643-669, 643:12, with a sentence's
|
||||
// stop after it.
|
||||
var lineRefRe = regexp.MustCompile(`^L?\d+(?:[-–:]L?\d+)*[.,;:]?$`)
|
||||
var lineRefRe = lazyre.New(`^L?\d+(?:[-–:]L?\d+)*[.,;:]?$`)
|
||||
|
||||
// lineRef says v is a line or a range of lines, never a secret.
|
||||
func lineRef(v string) bool { return lineRefRe.MatchString(v) }
|
||||
@@ -208,7 +210,7 @@ var secretWords = map[string]bool{
|
||||
|
||||
// identRe is a name in code, read through others or not: camelCase,
|
||||
// snake_case, SCREAMING_CASE, env.SECRET_V2.
|
||||
var identRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$`)
|
||||
var identRe = lazyre.New(`^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$`)
|
||||
|
||||
// namesASecret says v is a name in code for a secret, not one: two words
|
||||
// or more, one of them token, secret, password or key, written as code
|
||||
@@ -261,7 +263,7 @@ func identWords(v string) []string {
|
||||
// (UI_ADDR=), one in lower case (addr=, data-dir=), or a flag
|
||||
// (--listen=); then =, and something other than another =, so a base64
|
||||
// value's padding (dGVzdA==) is never taken for one.
|
||||
var nextFieldRe = regexp.MustCompile(`^(?:[A-Z_][A-Z0-9_]*|[a-z_][a-z0-9_-]*|--?[A-Za-z][A-Za-z0-9_-]*)=[^=]`)
|
||||
var nextFieldRe = lazyre.New(`^(?:[A-Z_][A-Z0-9_]*|[a-z_][a-z0-9_-]*|--?[A-Za-z][A-Za-z0-9_-]*)=[^=]`)
|
||||
|
||||
// nextField says the value at s[a:b] is not the value of the field before
|
||||
// it but the next field: the name before it was set to nothing (UI_PASSWORD=
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package redact
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// TestAllCompile compiles every pattern this package compiles on first
|
||||
// use, so a bad one fails here and not on a user's request.
|
||||
func TestAllCompile(t *testing.T) {
|
||||
if n := lazyre.MustAll(); n == 0 {
|
||||
t.Fatal("no lazy patterns registered")
|
||||
}
|
||||
}
|
||||
+26
-25
@@ -1,11 +1,12 @@
|
||||
package redact
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// A local model (internal/pii, Settings → Privacy's "Find with a local
|
||||
@@ -193,23 +194,23 @@ func modelName(v string) bool {
|
||||
}
|
||||
|
||||
var (
|
||||
dashedRe = regexp.MustCompile(`^[a-z][a-z0-9.]*(?:-[a-z0-9.]+)+$`)
|
||||
sizePartRe = regexp.MustCompile(`^(?:\d+x)?\d+(?:\.\d+)?[bkm]$|^20\d{6}$`)
|
||||
dateIn = regexp.MustCompile(`(?:^|-)20\d\d-[01]\d-[0-3]\d(?:-|$)`)
|
||||
dashedRe = lazyre.New(`^[a-z][a-z0-9.]*(?:-[a-z0-9.]+)+$`)
|
||||
sizePartRe = lazyre.New(`^(?:\d+x)?\d+(?:\.\d+)?[bkm]$|^20\d{6}$`)
|
||||
dateIn = lazyre.New(`(?:^|-)20\d\d-[01]\d-[0-3]\d(?:-|$)`)
|
||||
)
|
||||
|
||||
var (
|
||||
uuidRe = regexp.MustCompile(`^(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
|
||||
uuidRe = lazyre.New(`^(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
|
||||
// a model's, a repo's or a package's name (qwen/qwen3-14b, acme/web)
|
||||
slugRe = regexp.MustCompile(`^[a-z0-9][a-z0-9._@-]*(?:/[a-z0-9._@-]+)+$`)
|
||||
slugRe = lazyre.New(`^[a-z0-9][a-z0-9._@-]*(?:/[a-z0-9._@-]+)+$`)
|
||||
// a file's name in lower case (make-icons.sh, run_all.py)
|
||||
fileNameRe = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]*(?:\.[a-z0-9_-]+)*\.[a-z][a-z0-9]{0,4}$`)
|
||||
digestRe = regexp.MustCompile(`^(?i)(?:md5|sha-?(?:1|224|256|384|512)|blake2b?|blake3)[ :=-]+[0-9a-f]{32,128}$`)
|
||||
fileNameRe = lazyre.New(`^[a-z0-9][a-z0-9_-]*(?:\.[a-z0-9_-]+)*\.[a-z][a-z0-9]{0,4}$`)
|
||||
digestRe = lazyre.New(`^(?i)(?:md5|sha-?(?:1|224|256|384|512)|blake2b?|blake3)[ :=-]+[0-9a-f]{32,128}$`)
|
||||
// a package's digest as a lock file pins it (Subresource Integrity:
|
||||
// package-lock.json's and pnpm-lock.yaml's "integrity"), sha512- and
|
||||
// the hash in base64, with the } or quote the model took in after it.
|
||||
// Privacy Filter took each one for a secret.
|
||||
sriRe = regexp.MustCompile(`^sha(?:256|384|512)-[A-Za-z0-9+/]{43,86}={0,2}[}"',;)\]]*$`)
|
||||
sriRe = lazyre.New(`^sha(?:256|384|512)-[A-Za-z0-9+/]{43,86}={0,2}[}"',;)\]]*$`)
|
||||
)
|
||||
|
||||
// madeID says v is an id of the shape vendors and tools give theirs: a
|
||||
@@ -406,7 +407,7 @@ func programWords(v string) bool {
|
||||
// _: drizzle-orm, reflect-metadata, lodash.merge, secretstorage; and a
|
||||
// folder's name as a path or Python writes it, with the slash after it
|
||||
// or underscores around it: node_modules/, __pycache__.
|
||||
var wordsOnlyRe = regexp.MustCompile(`^_*[a-z]+(?:[-._][a-z]+)*_*/?$`)
|
||||
var wordsOnlyRe = lazyre.New(`^_*[a-z]+(?:[-._][a-z]+)*_*/?$`)
|
||||
|
||||
// wordsOnly says v, which the model took for a secret, is made of words
|
||||
// in lower case alone, as a package's, a tool's or a setting's name is.
|
||||
@@ -467,7 +468,7 @@ func pinnedAfter(s string, b int) bool {
|
||||
|
||||
// moduleRe is what code names a module by: drizzle-orm, @scope/name/sub,
|
||||
// node:fs, ./db/schema, golang.org/x/net, serde_json::Value.
|
||||
var moduleRe = regexp.MustCompile(`^(?:[a-z]+:)?@?[A-Za-z0-9_.~-]+(?:(?:/|::)[A-Za-z0-9_.~@-]+)*$`)
|
||||
var moduleRe = lazyre.New(`^(?:[a-z]+:)?@?[A-Za-z0-9_.~-]+(?:(?:/|::)[A-Za-z0-9_.~@-]+)*$`)
|
||||
|
||||
// moduleAt says s[a:b] is the module a line of code loads: import { eq }
|
||||
// from 'drizzle-orm', require(' jsonwebtoken '), import('x'), from
|
||||
@@ -638,7 +639,7 @@ func depVersion(v string) bool {
|
||||
return v != ""
|
||||
}
|
||||
|
||||
var depRangeRe = regexp.MustCompile(`^(?:[~^]|[<>]=?|=)?[vV]?\d+(?:\.(?:\d+|[xX*]))*(?:[-+][0-9A-Za-z.-]+)?$`)
|
||||
var depRangeRe = lazyre.New(`^(?:[~^]|[<>]=?|=)?[vV]?\d+(?:\.(?:\d+|[xX*]))*(?:[-+][0-9A-Za-z.-]+)?$`)
|
||||
|
||||
// underPackages says the name at a is a folder packages are installed in:
|
||||
// node_modules/drizzle-orm/…, site-packages/secretstorage/….
|
||||
@@ -678,7 +679,7 @@ func missingModuleAt(s string, a, b int) bool {
|
||||
}
|
||||
|
||||
// installRe is a package manager's command that names packages after it.
|
||||
var installRe = regexp.MustCompile(`(?:^|[\s;&|(` + "`" + `$])(?:npm|pnpm|yarn|bun|npx|pip|pip3|uv|poetry|pipx|cargo|gem|composer|deno|go)(?: +(?:pip|-[\w-]+))* +(?:add|install|i|remove|rm|uninstall|un|get|require|update|upgrade|up)(?: |$)`)
|
||||
var installRe = lazyre.New(`(?:^|[\s;&|(` + "`" + `$])(?:npm|pnpm|yarn|bun|npx|pip|pip3|uv|poetry|pipx|cargo|gem|composer|deno|go)(?: +(?:pip|-[\w-]+))* +(?:add|install|i|remove|rm|uninstall|un|get|require|update|upgrade|up)(?: |$)`)
|
||||
|
||||
// installedAt says s[a:b] is one of the packages a command on its line
|
||||
// installs or removes: pnpm add drizzle-orm postgres, npm i -D x,
|
||||
@@ -731,7 +732,7 @@ func pinnedAt(s string, a, b int) bool {
|
||||
return m != "" && !(len(s) > b+1+len(m) && s[b+1+len(m)] == '.')
|
||||
}
|
||||
|
||||
var pinVersionRe = regexp.MustCompile(`^[\^~]?v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]*[0-9A-Za-z])?`)
|
||||
var pinVersionRe = lazyre.New(`^[\^~]?v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]*[0-9A-Za-z])?`)
|
||||
|
||||
// wordEnd says s ends in the word w.
|
||||
func wordEnd(s, w string) bool {
|
||||
@@ -826,7 +827,7 @@ func hostIn(s, w string) bool {
|
||||
|
||||
// hostTail is a domain's rest after its first part: .com, .greptile.com,
|
||||
// ending where the host does (not at an @ or more of a word)
|
||||
var hostTail = regexp.MustCompile(`^(?:\.[a-z0-9-]+)*\.[a-z]{2,6}(?:[/:\s"'),\x60]|$)`)
|
||||
var hostTail = lazyre.New(`^(?:\.[a-z0-9-]+)*\.[a-z]{2,6}(?:[/:\s"'),\x60]|$)`)
|
||||
|
||||
// nameParticles are the words in lower case a name may have between its
|
||||
// others: Ludwig van Beethoven, Ibn al Haytham.
|
||||
@@ -898,11 +899,11 @@ var assistantNames = map[string]bool{
|
||||
}
|
||||
|
||||
var (
|
||||
hexRe = regexp.MustCompile(`^[0-9a-f]{7,64}$`)
|
||||
hexRe = lazyre.New(`^[0-9a-f]{7,64}$`)
|
||||
// an EVM chain's address: 0x and 40 hex digits, in either case or
|
||||
// mixed (EIP-55's checksum)
|
||||
evmRe = regexp.MustCompile(`^0[xX][0-9a-fA-F]{40}$`)
|
||||
decimalRe = regexp.MustCompile(`^\d+\.\d+$`)
|
||||
evmRe = lazyre.New(`^0[xX][0-9a-fA-F]{40}$`)
|
||||
decimalRe = lazyre.New(`^\d+\.\d+$`)
|
||||
// a number written in hex as code and notes write one, of 64 bits at
|
||||
// most: a memory address (0x004EA5E0), a constant, a flag. The model
|
||||
// took such an address in reverse-engineering notes for a secret, and
|
||||
@@ -913,17 +914,17 @@ var (
|
||||
// function at an address is often named for a key (DecryptKey:
|
||||
// 0x004EA5E0). A key written so is longer (0x and 64 hex digits) and
|
||||
// is masked still.
|
||||
hexLiteral = regexp.MustCompile(`^0[xX][0-9a-fA-F]{1,16}$`)
|
||||
hexLiteral = lazyre.New(`^0[xX][0-9a-fA-F]{1,16}$`)
|
||||
// a time of day in words the model took for a passphrase (release
|
||||
// about 17:05Z)
|
||||
clockIn = regexp.MustCompile(`(?:^|\s)\d{1,2}:\d{2}(?::\d{2})?Z?(?:\s|$)`)
|
||||
versionRe = regexp.MustCompile(`^v?\d+(?:\.\d+)+$`)
|
||||
sizeRe = regexp.MustCompile(`^\d+ ?[x×] ?\d+$`)
|
||||
uuidIn = regexp.MustCompile(`(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`)
|
||||
clockIn = lazyre.New(`(?:^|\s)\d{1,2}:\d{2}(?::\d{2})?Z?(?:\s|$)`)
|
||||
versionRe = lazyre.New(`^v?\d+(?:\.\d+)+$`)
|
||||
sizeRe = lazyre.New(`^\d+ ?[x×] ?\d+$`)
|
||||
uuidIn = lazyre.New(`(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`)
|
||||
// a name in Go's module cache (d6426ecaaf0a28de@v31)
|
||||
modCacheRe = regexp.MustCompile(`^[0-9a-f]{16}@v\d+$`)
|
||||
modCacheRe = lazyre.New(`^[0-9a-f]{16}@v\d+$`)
|
||||
// a link, or a host's name with a path (discord.gg/…)
|
||||
linkRe = regexp.MustCompile(`^(?:[a-z][a-z0-9+.-]*://|[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/)`)
|
||||
linkRe = lazyre.New(`^(?:[a-z][a-z0-9+.-]*://|[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/)`)
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
+23
-22
@@ -2,10 +2,11 @@ package redact
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// More kinds of personal data, each a category the user turns on or off
|
||||
@@ -81,21 +82,21 @@ const (
|
||||
var moreRules = []rule{
|
||||
// US Social Security numbers: 123-45-6789 as it is written, or nine
|
||||
// digits after SSN; in the ranges the SSA gives out
|
||||
{kind: "SSN", cat: "ssn", re: regexp.MustCompile(`\d{3}-\d{2}-\d{4}`), markers: []string{"-"}, bound: alnum + "-", ok: ssnOK},
|
||||
{kind: "SSN", cat: "ssn", re: regexp.MustCompile(`(?i:\bssn|\bsocial[ \t]+security(?:[ \t]+(?:number|no\.?|#))?)` + sep + `(?:(?i:is)[ \t]+)?["']?(\d{9}|\d{3} \d{2} \d{4})`),
|
||||
{kind: "SSN", cat: "ssn", re: lazyre.New(`\d{3}-\d{2}-\d{4}`), markers: []string{"-"}, bound: alnum + "-", ok: ssnOK},
|
||||
{kind: "SSN", cat: "ssn", re: lazyre.New(`(?i:\bssn|\bsocial[ \t]+security(?:[ \t]+(?:number|no\.?|#))?)` + sep + `(?:(?i:is)[ \t]+)?["']?(\d{9}|\d{3} \d{2} \d{4})`),
|
||||
fold: []string{"ssn", "social"}, back: 8, ahead: 80, bound: digits, ok: ssnOK},
|
||||
|
||||
{kind: "PASSPORT", cat: "passport", anyGroup: true, bound: alnum, ok: passportOK,
|
||||
re: regexp.MustCompile(`(?i:\bpassport(?:[ \t]*(?:no\.?|number|num|#))?|\breisepass(?:nummer)?)` + sep + `(?:(?i:is|was)[ \t]+)?["']?([A-Z0-9]{6,9})` +
|
||||
re: lazyre.New(`(?i:\bpassport(?:[ \t]*(?:no\.?|number|num|#))?|\breisepass(?:nummer)?)` + sep + `(?:(?i:is|was)[ \t]+)?["']?([A-Z0-9]{6,9})` +
|
||||
`|(?:护照(?:号码|号)?|護照(?:號碼|号码|番号)?|パスポート(?:番号)?)[ \t]*(?:[::=][ \t]*)?(?:是[ \t]*|は[ \t]*)?["']?([A-Z0-9]{6,9})`),
|
||||
fold: []string{"passport", "reisepass", "护照", "護照", "パスポート"}, back: 8, ahead: 80},
|
||||
|
||||
// an IBAN, as one word or printed in groups of four, by its checksum
|
||||
{kind: "IBAN", cat: "iban", re: regexp.MustCompile(`[A-Z]{2}\d{2}(?:[A-Z0-9]{11,30}|(?: [A-Z0-9]{4}){2,7}(?: [A-Z0-9]{1,3})?)`), bound: alnum, fix: ibanAt},
|
||||
{kind: "IBAN", cat: "iban", re: lazyre.New(`[A-Z]{2}\d{2}(?:[A-Z0-9]{11,30}|(?: [A-Z0-9]{4}){2,7}(?: [A-Z0-9]{1,3})?)`), bound: alnum, fix: ibanAt},
|
||||
|
||||
// a date after the words that say it is a birthday; a date alone is not
|
||||
{kind: "BIRTHDAY", cat: "birthday", bound: digits, ok: dateOK,
|
||||
re: regexp.MustCompile(`(?:(?i:\bdate[ \t]+of[ \t]+birth|\bbirth[ \t_-]?date|\bbirthday|\bdob\b|\bd\.o\.b\.?|\bborn(?:[ \t]+on)?|\bgeburtsdatum|\bgeboren(?:[ \t]+am)?)|生日|出生日期|出生年月日|出生于|出生於|出生|誕生日|生年月日)` +
|
||||
re: lazyre.New(`(?:(?i:\bdate[ \t]+of[ \t]+birth|\bbirth[ \t_-]?date|\bbirthday|\bdob\b|\bd\.o\.b\.?|\bborn(?:[ \t]+on)?|\bgeburtsdatum|\bgeboren(?:[ \t]+am)?)|生日|出生日期|出生年月日|出生于|出生於|出生|誕生日|生年月日)` +
|
||||
sep + `(?:(?i:is|was)[ \t]+|是[ \t]*|为[ \t]*|為[ \t]*|は[ \t]*)?["']?` +
|
||||
`(\d{4}[-/.]\d{1,2}[-/.]\d{1,2}|\d{4}[ \t]*年[ \t]*\d{1,2}[ \t]*月[ \t]*\d{1,2}[ \t]*日?|\d{1,2}[-/.]\d{1,2}[-/.]\d{4}` +
|
||||
`|` + months + `[ \t]+\d{1,2}(?:st|nd|rd|th)?,?[ \t]+\d{4}|\d{1,2}(?:st|nd|rd|th)?[ \t]+` + months + `,?[ \t]+\d{4})`),
|
||||
@@ -103,22 +104,22 @@ var moreRules = []rule{
|
||||
|
||||
// a MAC address, aa:bb:cc:dd:ee:ff or aa-bb-cc-dd-ee-ff; not a piece of
|
||||
// an IPv6 address or a certificate's fingerprint
|
||||
{kind: "MAC", cat: "mac", re: regexp.MustCompile(`[0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){5}|[0-9A-Fa-f]{2}(?:-[0-9A-Fa-f]{2}){5}`), bound: alnum + ":-", ok: macOK},
|
||||
{kind: "MAC", cat: "mac", re: lazyre.New(`[0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){5}|[0-9A-Fa-f]{2}(?:-[0-9A-Fa-f]{2}){5}`), bound: alnum + ":-", ok: macOK},
|
||||
|
||||
// a serial number after S/N, Serial or 序列号, and a separator; not
|
||||
// "serial port" or Serial.println
|
||||
{kind: "SERIAL", cat: "serial", anyGroup: true, bound: alnum + "-", ok: serialOK,
|
||||
re: regexp.MustCompile(`(?i:\bserial[ \t_-]?(?:number|num|no\.?|#)?|\bs/n|\bsn)(?:[ \t]*\([^)\n]{1,20}\))?["']?[ \t]*[:#=:][ \t]*["']?([A-Za-z0-9][A-Za-z0-9-]{4,39})` +
|
||||
re: lazyre.New(`(?i:\bserial[ \t_-]?(?:number|num|no\.?|#)?|\bs/n|\bsn)(?:[ \t]*\([^)\n]{1,20}\))?["']?[ \t]*[:#=:][ \t]*["']?([A-Za-z0-9][A-Za-z0-9-]{4,39})` +
|
||||
`|(?:序列号|序列號|シリアル番号|(?i:seriennummer))[ \t]*[::=]?[ \t]*["']?([A-Za-z0-9][A-Za-z0-9-]{4,39})`),
|
||||
fold: []string{"serial", "s/n", "sn", "序列", "シリアル", "seriennummer"}, back: 8, ahead: 80},
|
||||
|
||||
// the user's name in a home folder: /Users/<name>, /home/<name>,
|
||||
// C:\Users\<name>; the rest of the path stays
|
||||
{kind: "USERNAME", cat: "home", fix: homeAt,
|
||||
re: regexp.MustCompile(`(?:^|[^A-Za-z0-9_.~/\\-])(?:file://)?(?:/mnt/[a-z])?/(?:Users|home)/(` + pathName + `)`),
|
||||
re: lazyre.New(`(?:^|[^A-Za-z0-9_.~/\\-])(?:file://)?(?:/mnt/[a-z])?/(?:Users|home)/(` + pathName + `)`),
|
||||
fold: []string{"/users/", "/home/"}, back: 16, ahead: 80},
|
||||
{kind: "USERNAME", cat: "home", anyGroup: true, fix: homeAt,
|
||||
re: regexp.MustCompile(`(?:^|[^A-Za-z0-9])[A-Za-z]:(?:\\{1,4}|/)(?i:users|documents and settings)(?:\\{1,4}|/)` +
|
||||
re: lazyre.New(`(?:^|[^A-Za-z0-9])[A-Za-z]:(?:\\{1,4}|/)(?i:users|documents and settings)(?:\\{1,4}|/)` +
|
||||
`(?:([A-Za-z0-9._-]+(?: [A-Za-z0-9._-]+)+)(?:\\|/)|(` + pathName + `))`),
|
||||
fold: []string{"users", "documents and settings"}, back: 12, ahead: 100},
|
||||
|
||||
@@ -127,39 +128,39 @@ var moreRules = []rule{
|
||||
// package pinned at its version,
|
||||
// js-tokens@4.0.0: in pnpm-lock.yaml, is no login (notPackagePin)
|
||||
{cat: "userhost", groups: []string{"USERNAME", "HOSTNAME"}, groupOK: []func(string) bool{userOK, hostOK}, markers: []string{"@"}, at: notPackagePin,
|
||||
re: regexp.MustCompile(`(?m)(?:^|[^A-Za-z0-9._%+-])(` + unixUser + `)@(` + hostRe + `)(?::[~/]|:[ \t]*$|[ \t]+[~/]|[ \t]*[$%#>][ \t]|[ \t]*[$%#>]$)`)},
|
||||
re: lazyre.New(`(?m)(?:^|[^A-Za-z0-9._%+-])(` + unixUser + `)@(` + hostRe + `)(?::[~/]|:[ \t]*$|[ \t]+[~/]|[ \t]*[$%#>][ \t]|[ \t]*[$%#>]$)`)},
|
||||
{cat: "userhost", groups: []string{"USERNAME", "HOSTNAME"}, groupOK: []func(string) bool{userOK, hostOK}, markers: []string{"@"}, at: notPackagePin,
|
||||
re: regexp.MustCompile(`(?i:\b(?:ssh|scp|sftp|rsync|mosh|ssh-copy-id))\b[^\n@]{0,80}?[ \t"'](` + unixUser + `)@(` + hostRe + `)`)},
|
||||
re: lazyre.New(`(?i:\b(?:ssh|scp|sftp|rsync|mosh|ssh-copy-id))\b[^\n@]{0,80}?[ \t"'](` + unixUser + `)@(` + hostRe + `)`)},
|
||||
// hostname: x, HOSTNAME=x, a line with the value alone after it; or
|
||||
// ssh config's HostName x, indented under its Host
|
||||
{kind: "HOSTNAME", cat: "userhost", anyGroup: true, ok: lineHostOK,
|
||||
re: regexp.MustCompile(`(?m)^[ \t]*["']?(?:(?i:host[ \t_-]?name|computer[ \t_-]?name|machine[ \t_-]?name|device[ \t_-]?name)|主机名|主機名|計算機名|コンピュータ名|コンピューター名)["']?` +
|
||||
re: lazyre.New(`(?m)^[ \t]*["']?(?:(?i:host[ \t_-]?name|computer[ \t_-]?name|machine[ \t_-]?name|device[ \t_-]?name)|主机名|主機名|計算機名|コンピュータ名|コンピューター名)["']?` +
|
||||
`[ \t]*[:=:][ \t]*(?:["'](` + hostRe + `)["'][ \t]*[,;]?|(` + hostRe + `))[ \t]*$|^[ \t]+HostName[ \t]+(` + hostRe + `)[ \t]*$`),
|
||||
fold: []string{"name", "主机", "主機", "計算機", "コンピュータ"}},
|
||||
// User: x, USER=x, a line with the name alone after it; or ssh config's
|
||||
// User x, indented under its Host
|
||||
{kind: "USERNAME", cat: "userhost", anyGroup: true, ok: lineUserOK, at: notLineIdent,
|
||||
re: regexp.MustCompile(`(?m)^[ \t]*["']?(?:(?i:user[ \t_-]?name|login[ \t_-]?name|user|login|logname)|用户名|用戶名|ユーザー名)["']?` +
|
||||
re: lazyre.New(`(?m)^[ \t]*["']?(?:(?i:user[ \t_-]?name|login[ \t_-]?name|user|login|logname)|用户名|用戶名|ユーザー名)["']?` +
|
||||
`[ \t]*[:=:][ \t]*(?:["'](` + lineUser + `)["'][ \t]*[,;]?|(` + lineUser + `))[ \t]*$|^[ \t]+User[ \t]+(` + lineUser + `)[ \t]*$`),
|
||||
fold: []string{"user", "login", "logname", "用户", "用戶", "ユーザー"}},
|
||||
|
||||
// a public IP address; not a private, loopback, link-local, CGNAT or
|
||||
// documentation one, nor a version
|
||||
{kind: "IP", cat: "ip", markers: []string{"."}, at: ipv4At,
|
||||
re: regexp.MustCompile(`(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}`)},
|
||||
re: lazyre.New(`(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}`)},
|
||||
{kind: "IP", cat: "ip", markers: []string{":"}, bound: alnum + ":_", ok: ipv6OK,
|
||||
re: regexp.MustCompile(`[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{0,4}){2,7}`)},
|
||||
re: lazyre.New(`[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{0,4}){2,7}`)},
|
||||
|
||||
// a cloud bucket: s3://<b>, gs://<b>, oss://, cos://, abfss://<c>@<account>…,
|
||||
// <b>.s3.amazonaws.com, s3.amazonaws.com/<b>, <account>.blob.core.windows.net/<c>
|
||||
{cat: "bucket", groups: []string{"BUCKET", "BUCKET"}, groupOK: []func(string) bool{bucketOK, bucketOK}, markers: []string{"://"},
|
||||
re: regexp.MustCompile(`(?i:\b(?:s3a?|s3n|gs|oss|cosn?|obs|r2|ks3|bos|tos|az|azure|wasbs?|abfss?)://)(` + bucketRe + `)(?:@([a-z0-9]{3,24})\.(?:blob|dfs)\.core\.windows\.net)?`)},
|
||||
re: lazyre.New(`(?i:\b(?:s3a?|s3n|gs|oss|cosn?|obs|r2|ks3|bos|tos|az|azure|wasbs?|abfss?)://)(` + bucketRe + `)(?:@([a-z0-9]{3,24})\.(?:blob|dfs)\.core\.windows\.net)?`)},
|
||||
{kind: "BUCKET", cat: "bucket", ok: bucketOK, fold: bucketHosts, back: 128, ahead: 32,
|
||||
re: regexp.MustCompile(`(?:^|[^A-Za-z0-9.-])([a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?)\.(?:s3(?:[.-](?:dualstack\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?|s3-accelerate\.amazonaws\.com` +
|
||||
re: lazyre.New(`(?:^|[^A-Za-z0-9.-])([a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?)\.(?:s3(?:[.-](?:dualstack\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?|s3-accelerate\.amazonaws\.com` +
|
||||
`|storage\.googleapis\.com|oss-[a-z0-9-]+\.aliyuncs\.com|cos\.[a-z0-9-]+\.myqcloud\.com|obs\.[a-z0-9-]+\.myhuaweicloud\.com|r2\.cloudflarestorage\.com` +
|
||||
`|(?:blob|dfs)\.core\.windows\.net|[a-z0-9-]+\.digitaloceanspaces\.com|tos-[a-z0-9-]+\.volces\.com)`)},
|
||||
{kind: "BUCKET", cat: "bucket", ok: bucketOK, fold: bucketHosts, back: 48, ahead: 80,
|
||||
re: regexp.MustCompile(`(?:^|[^A-Za-z0-9.-])(?:s3(?:[.-](?:dualstack\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?|storage\.googleapis\.com|storage\.cloud\.google\.com` +
|
||||
re: lazyre.New(`(?:^|[^A-Za-z0-9.-])(?:s3(?:[.-](?:dualstack\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?|storage\.googleapis\.com|storage\.cloud\.google\.com` +
|
||||
`|[a-z0-9]{3,24}\.blob\.core\.windows\.net|oss-[a-z0-9-]+\.aliyuncs\.com|[a-z0-9-]+\.digitaloceanspaces\.com)/(` + bucketRe + `)`)},
|
||||
}
|
||||
|
||||
@@ -239,7 +240,7 @@ func ibanAt(s string, a, b int) (int, int, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
var dateNums = regexp.MustCompile(`\d+`)
|
||||
var dateNums = lazyre.New(`\d+`)
|
||||
|
||||
// dateClock is what dateOK takes today from; a test holds it.
|
||||
var dateClock = time.Now
|
||||
@@ -372,7 +373,7 @@ func notPackagePin(s string, a, b int) bool {
|
||||
|
||||
// versionHostRe is a release's version as a host's characters can
|
||||
// spell it: 4.0.0, 18.2.0-rc.0.
|
||||
var versionHostRe = regexp.MustCompile(`^v?\d+(?:\.\d+)+(?:-[0-9A-Za-z.-]+)?$`)
|
||||
var versionHostRe = lazyre.New(`^v?\d+(?:\.\d+)+(?:-[0-9A-Za-z.-]+)?$`)
|
||||
|
||||
// versionHost says h, after a user's @, is a version and not a host: no
|
||||
// host's name is numbers and dots alone, but an address is.
|
||||
@@ -487,7 +488,7 @@ func nameAlone(s string, a, b int) bool {
|
||||
// paramRest is what is after a parameter's name in a list: the list goes
|
||||
// on or ends, or the parameter's type comes first (developer: str,
|
||||
// developer string, developer *Config).
|
||||
var paramRest = regexp.MustCompile(`^(?:[,):]|[*\[\]]*[A-Za-z_][\w.*\[\]]*[ \t]*[,)])`)
|
||||
var paramRest = lazyre.New(`^(?:[,):]|[*\[\]]*[A-Za-z_][\w.*\[\]]*[ \t]*[,)])`)
|
||||
|
||||
// declWords, before a name with a space, declare it.
|
||||
var declWords = []string{"const", "let", "var", "val", "def", "func", "fn", "function", "class", "struct", "interface", "enum", "return", "import", "typeof"}
|
||||
|
||||
+31
-29
@@ -33,6 +33,8 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/net/publicsuffix"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// Options says what to mask.
|
||||
@@ -120,7 +122,7 @@ func (o Options) covers(cat string) bool {
|
||||
// either side (a key inside a longer word is no key); ok checks it further.
|
||||
type rule struct {
|
||||
kind string
|
||||
re *regexp.Regexp
|
||||
re *lazyre.RE
|
||||
markers []string // one of these is in any text it can match
|
||||
// fold are markers too, looked for in the text in lower case, for a
|
||||
// pattern that matches its words in any case (Passport, PASSPORT)
|
||||
@@ -162,26 +164,26 @@ const (
|
||||
)
|
||||
|
||||
var rules = append([]rule{
|
||||
{kind: "PRIVATE_KEY", re: regexp.MustCompile(`-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]+?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----`), markers: []string{"PRIVATE KEY"}},
|
||||
{kind: "API_KEY", re: regexp.MustCompile(`sk-(?:ant-|proj-|or-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}`), markers: []string{"sk-"}, bound: tokenCh, ok: notASlug},
|
||||
{kind: "PRIVATE_KEY", re: lazyre.New(`-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]+?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----`), markers: []string{"PRIVATE KEY"}},
|
||||
{kind: "API_KEY", re: lazyre.New(`sk-(?:ant-|proj-|or-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}`), markers: []string{"sk-"}, bound: tokenCh, ok: notASlug},
|
||||
// a gateway's or a relay's own: oc_sk_…, or_sk_… (#195)
|
||||
{kind: "API_KEY", re: regexp.MustCompile(`[a-z]{2,4}_sk_[A-Za-z0-9_-]{20,}`), markers: []string{"_sk_"}, bound: tokenCh, ok: secretValue},
|
||||
{kind: "API_KEY", re: lazyre.New(`[a-z]{2,4}_sk_[A-Za-z0-9_-]{20,}`), markers: []string{"_sk_"}, bound: tokenCh, ok: secretValue},
|
||||
// Volcano Ark and the relays in front of it issue keys with an ark-
|
||||
// prefix (#2946)
|
||||
{kind: "API_KEY", re: regexp.MustCompile(`ark-[A-Za-z0-9][A-Za-z0-9_-]{15,}`), markers: []string{"ark-"}, bound: tokenCh, ok: secretValue},
|
||||
{kind: "API_KEY", re: regexp.MustCompile(`(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,}|glpat-[A-Za-z0-9_-]{20,})`), markers: []string{"gh", "github_pat_", "glpat-"}, bound: tokenCh},
|
||||
{kind: "API_KEY", re: regexp.MustCompile(`AIza[0-9A-Za-z_-]{35}`), markers: []string{"AIza"}, bound: tokenCh},
|
||||
{kind: "API_KEY", re: regexp.MustCompile(`xox[abposr]-[0-9A-Za-z-]{10,}`), markers: []string{"xox"}, bound: tokenCh},
|
||||
{kind: "API_KEY", re: regexp.MustCompile(`(?:sk|rk)_live_[0-9A-Za-z]{20,}`), markers: []string{"_live_"}, bound: tokenCh},
|
||||
{kind: "API_KEY", re: regexp.MustCompile(`(?:AKIA|ASIA)[0-9A-Z]{16}`), markers: []string{"AKIA", "ASIA"}, bound: alnum},
|
||||
{kind: "API_KEY", re: regexp.MustCompile(`(?:hf_[A-Za-z0-9]{30,}|gsk_[A-Za-z0-9]{40,}|xai-[A-Za-z0-9]{40,}|npm_[A-Za-z0-9]{36}|pypi-[A-Za-z0-9_-]{50,}|dop_v1_[a-f0-9]{64}|SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43})`),
|
||||
{kind: "API_KEY", re: lazyre.New(`ark-[A-Za-z0-9][A-Za-z0-9_-]{15,}`), markers: []string{"ark-"}, bound: tokenCh, ok: secretValue},
|
||||
{kind: "API_KEY", re: lazyre.New(`(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,}|glpat-[A-Za-z0-9_-]{20,})`), markers: []string{"gh", "github_pat_", "glpat-"}, bound: tokenCh},
|
||||
{kind: "API_KEY", re: lazyre.New(`AIza[0-9A-Za-z_-]{35}`), markers: []string{"AIza"}, bound: tokenCh},
|
||||
{kind: "API_KEY", re: lazyre.New(`xox[abposr]-[0-9A-Za-z-]{10,}`), markers: []string{"xox"}, bound: tokenCh},
|
||||
{kind: "API_KEY", re: lazyre.New(`(?:sk|rk)_live_[0-9A-Za-z]{20,}`), markers: []string{"_live_"}, bound: tokenCh},
|
||||
{kind: "API_KEY", re: lazyre.New(`(?:AKIA|ASIA)[0-9A-Z]{16}`), markers: []string{"AKIA", "ASIA"}, bound: alnum},
|
||||
{kind: "API_KEY", re: lazyre.New(`(?:hf_[A-Za-z0-9]{30,}|gsk_[A-Za-z0-9]{40,}|xai-[A-Za-z0-9]{40,}|npm_[A-Za-z0-9]{36}|pypi-[A-Za-z0-9_-]{50,}|dop_v1_[a-f0-9]{64}|SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43})`),
|
||||
markers: []string{"hf_", "gsk_", "xai-", "npm_", "pypi-", "dop_v1_", "SG."}, bound: tokenCh},
|
||||
{kind: "TOKEN", re: regexp.MustCompile(`eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}`), markers: []string{"eyJ"}, bound: tokenCh},
|
||||
{kind: "TOKEN", re: lazyre.New(`eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}`), markers: []string{"eyJ"}, bound: tokenCh},
|
||||
// the password of user:password@host, or of :password@host as a Redis
|
||||
// URL has it with no user
|
||||
{kind: "PASSWORD", re: regexp.MustCompile(`[A-Za-z][A-Za-z0-9+.-]*://[^\s:@/?#"'<>]*:([^\s@/?#"'<>]{3,})@`), markers: []string{"://"}, ok: notAVariable, at: hiddenInURL},
|
||||
{kind: "PASSWORD", re: lazyre.New(`[A-Za-z][A-Za-z0-9+.-]*://[^\s:@/?#"'<>]*:([^\s@/?#"'<>]{3,})@`), markers: []string{"://"}, ok: notAVariable, at: hiddenInURL},
|
||||
// password = …, API_KEY: "…", as .env files and configs have them
|
||||
{kind: "SECRET", re: regexp.MustCompile(`(?i)[A-Za-z0-9_.-]*(?:` + secretNames.pattern() + `)[A-Za-z0-9_.-]*` + quote + `[ \t]*[:=][ \t]*` + quote + `(` + secretCh + `{8,})`),
|
||||
{kind: "SECRET", re: lazyre.New(`(?i)[A-Za-z0-9_.-]*(?:` + secretNames.pattern() + `)[A-Za-z0-9_.-]*` + quote + `[ \t]*[:=][ \t]*` + quote + `(` + secretCh + `{8,})`),
|
||||
markers: secretNames.markers(), ok: secretValue, at: fieldAt, field: true},
|
||||
// an env var's name says what it holds in the upper case: a
|
||||
// SERVICE_X_KEY, a DB_PASS (#2946). The names above have a word for the
|
||||
@@ -189,16 +191,16 @@ var rules = append([]rule{
|
||||
// that a secret's name — in the lower case a name that ends in key is
|
||||
// code's: a sort key, a cache key, a public key (notAPlainKey turns the
|
||||
// upper-case ones of those away too).
|
||||
{kind: "SECRET", re: regexp.MustCompile(`(?:^|[^A-Za-z0-9_.-])[A-Za-z0-9_.-]*_(?:KEY|PASS)` + quote + `[ \t]*[:=][ \t]*` + quote + `(` + secretCh + `{8,})`),
|
||||
{kind: "SECRET", re: lazyre.New(`(?:^|[^A-Za-z0-9_.-])[A-Za-z0-9_.-]*_(?:KEY|PASS)` + quote + `[ \t]*[:=][ \t]*` + quote + `(` + secretCh + `{8,})`),
|
||||
markers: fieldNames{{"key", "key"}, {"pass", "pass"}}.markers(), ok: secretValue, at: namedSecretAt, field: true},
|
||||
// an Authorization or Cookie header's value is a secret whatever it
|
||||
// looks like: an opaque bearer token, a session value (#2946)
|
||||
{kind: "SECRET", re: regexp.MustCompile(`(?im)^[ \t]*(?:authorization|cookie)[ \t]*:[ \t]*(\S[^\r\n]{7,})`),
|
||||
{kind: "SECRET", re: lazyre.New(`(?im)^[ \t]*(?:authorization|cookie)[ \t]*:[ \t]*(\S[^\r\n]{7,})`),
|
||||
markers: fieldNames{{"authorization", "authorization"}, {"cookie", "cookie"}}.markers(), ok: headerValue},
|
||||
// a field called key and nothing more, as providers.json has one: "key":
|
||||
// "oc_sk_…" (#195). Only a long value of letters and digits both, since
|
||||
// code calls anything a key: a map's "key": "value", sort_key, keyboard.
|
||||
{kind: "SECRET", re: regexp.MustCompile(`(?i)(?:^|[^A-Za-z0-9_.-])` + quote + `key` + quote + `[ \t]*[:=][ \t]*` + quote + `(` + secretCh + `{16,})`),
|
||||
{kind: "SECRET", re: lazyre.New(`(?i)(?:^|[^A-Za-z0-9_.-])` + quote + `key` + quote + `[ \t]*[:=][ \t]*` + quote + `(` + secretCh + `{16,})`),
|
||||
markers: fieldNames{{"key", "key"}}.markers(), ok: secretValue, at: fieldAt, field: true},
|
||||
// a password after its name in Chinese, Japanese or Korean, as people
|
||||
// write one into a message: 密码:786kih, 密碼是 hunter2, パスワード: … .
|
||||
@@ -214,14 +216,14 @@ var rules = append([]rule{
|
||||
// an English name for one before 为, 為, 是 or :, as a Chinese message
|
||||
// has it: apikey 为 …, token 是 …, API Key:… (CyberCaius on Discord).
|
||||
// password = … and API_KEY: … in a config are the SECRET rule's above.
|
||||
{kind: "SECRET", re: regexp.MustCompile(`(?i)(?:` + secretNames.pattern() + `|pwd|api[ ]key|access[ ]key|secret[ ]key|key|\bpin(?:[ ]?code)?)` + quote +
|
||||
{kind: "SECRET", re: lazyre.New(`(?i)(?:` + secretNames.pattern() + `|pwd|api[ ]key|access[ ]key|secret[ ]key|key|\bpin(?:[ ]?code)?)` + quote +
|
||||
`[ \t]*(?:[为為是][ \t]*[::]?|:)[ \t]*(?:\\?["'“「])?(` + secretCh + `{3,}[A-Za-z0-9_\-/+=~!@#%^&*])`),
|
||||
fold: cjkCopulas, back: 24, ahead: 260, at: keyAt, field: true},
|
||||
|
||||
{kind: "EMAIL", re: regexp.MustCompile(`[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}`), markers: []string{"@"}, bound: alnum + "_%+-", ok: realEmail, at: emailAt, cat: catPersonal},
|
||||
{kind: "ID_CARD", re: regexp.MustCompile(`[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]`), bound: alnum, ok: chineseID, cat: catPersonal},
|
||||
{kind: "PHONE", re: regexp.MustCompile(`(?:\+?86[- ]?)?1[3-9]\d{9}`), bound: alnum, at: phoneAt, cat: catPersonal},
|
||||
{kind: "BANK_CARD", re: regexp.MustCompile(`[3-6]\d{3}(?:[ -]?\d{4}){2,3}(?:[ -]?\d{1,3})?`), bound: alnum, ok: luhn, cat: catPersonal},
|
||||
{kind: "EMAIL", re: lazyre.New(`[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}`), markers: []string{"@"}, bound: alnum + "_%+-", ok: realEmail, at: emailAt, cat: catPersonal},
|
||||
{kind: "ID_CARD", re: lazyre.New(`[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]`), bound: alnum, ok: chineseID, cat: catPersonal},
|
||||
{kind: "PHONE", re: lazyre.New(`(?:\+?86[- ]?)?1[3-9]\d{9}`), bound: alnum, at: phoneAt, cat: catPersonal},
|
||||
{kind: "BANK_CARD", re: lazyre.New(`[3-6]\d{3}(?:[ -]?\d{4}){2,3}(?:[ -]?\d{1,3})?`), bound: alnum, ok: luhn, cat: catPersonal},
|
||||
}, moreRules...)
|
||||
|
||||
// cjkPasswordNames are what a password is called in Chinese, Japanese and
|
||||
@@ -251,8 +253,8 @@ func lowerAll(names []string) []string {
|
||||
|
||||
// cjkNamed is a value after one of names: after :, :, =, 为, 為, 是, は
|
||||
// or 는, quoted or not, or after nothing but a space.
|
||||
func cjkNamed(names []string) *regexp.Regexp {
|
||||
return regexp.MustCompile(`(?i)(?:` + strings.Join(names, "|") + `)[ \t]*(?:[::=][ \t]*|[为為是][ \t]*[::]?[ \t]*|は[ \t]*|는[ \t]*)?(?:\\?["'“「])?(` + secretCh + `{3,63}[A-Za-z0-9_\-/+=~!@#%^&*])`)
|
||||
func cjkNamed(names []string) *lazyre.RE {
|
||||
return lazyre.New(`(?i)(?:` + strings.Join(names, "|") + `)[ \t]*(?:[::=][ \t]*|[为為是][ \t]*[::]?[ \t]*|は[ \t]*|는[ \t]*)?(?:\\?["'“「])?(` + secretCh + `{3,63}[A-Za-z0-9_\-/+=~!@#%^&*])`)
|
||||
}
|
||||
|
||||
// fieldNames are what a field that holds a secret is called: a pattern for
|
||||
@@ -301,7 +303,7 @@ const (
|
||||
)
|
||||
|
||||
// placeholderRe is a placeholder as Mask writes it.
|
||||
var placeholderRe = regexp.MustCompile(`\{\{[A-Z][A-Z0-9_]*_[a-z2-7]{8}\}\}`)
|
||||
var placeholderRe = lazyre.New(`\{\{[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.
|
||||
@@ -371,7 +373,7 @@ func secretValue(v string) bool {
|
||||
|
||||
// identPath is a name in code, or a field read through one: Uint8Array,
|
||||
// details.2, opts.token2.
|
||||
var identPath = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)*$`)
|
||||
var identPath = lazyre.New(`^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)*$`)
|
||||
|
||||
// notCode turns away a value at s[a:b] that is code naming a secret, not
|
||||
// the secret: a call (privateKey: toBase64Url(…), secretKey =
|
||||
@@ -677,7 +679,7 @@ var fileExt = map[string]bool{
|
||||
// address.
|
||||
var scaleExt = map[string]bool{"zip": true, "mov": true, "md": true, "map": true}
|
||||
|
||||
var scaleRe = regexp.MustCompile(`^[0-9]+(?:\.[0-9]+)?x$`)
|
||||
var scaleRe = lazyre.New(`^[0-9]+(?:\.[0-9]+)?x$`)
|
||||
|
||||
// fileHost says host, what follows the @ of what looks like an address,
|
||||
// is the end of a file's name: an extension no domain has (fileExt), or a
|
||||
@@ -1534,7 +1536,7 @@ func (r rule) matches(s, lower string) [][]int {
|
||||
// field (fieldMatches).
|
||||
func (r rule) findAll(s string) [][]int {
|
||||
if r.field {
|
||||
return fieldMatches(r.re, s)
|
||||
return fieldMatches(r.re.Regexp(), s)
|
||||
}
|
||||
return r.re.FindAllStringSubmatchIndex(s, -1)
|
||||
}
|
||||
@@ -1673,7 +1675,7 @@ func containsAny(s string, subs []string) bool {
|
||||
|
||||
// placeholderBody is a placeholder without its braces, as a model may write
|
||||
// one back: API_KEY_k3v9x2mq, phone_b5puzbfv, PHONE_B5PUZBFV.
|
||||
var placeholderBody = regexp.MustCompile(`[A-Za-z][A-Za-z0-9_]*_[A-Za-z2-7]{8}`)
|
||||
var placeholderBody = lazyre.New(`[A-Za-z][A-Za-z0-9_]*_[A-Za-z2-7]{8}`)
|
||||
|
||||
// Restore puts the values back in s. escaped is for text that is itself
|
||||
// JSON (a tool call's arguments), where a value goes in escaped.
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// Rule is one the user added (Settings → Privacy) for a secret magpie's own
|
||||
@@ -134,7 +136,7 @@ func customRules(in []Rule) []rule {
|
||||
if re == nil {
|
||||
continue
|
||||
}
|
||||
c := rule{kind: RuleKind(r.Kind), yours: true, re: re, ok: func(v string) bool { return len(v) >= minCustomLen }}
|
||||
c := rule{kind: RuleKind(r.Kind), yours: true, re: lazyre.Of(re), ok: func(v string) bool { return len(v) >= minCustomLen }}
|
||||
if r.Prefix != "" {
|
||||
c.markers = []string{r.Prefix}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,11 @@ package redact
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// Scrubbing is for what is kept rather than sent — the request archive: a
|
||||
@@ -22,7 +23,7 @@ func scrubbed(kind, _ string) string { return "[REDACTED:" + kind + "]" }
|
||||
// secretName is a field's or header's name that says its value is a secret.
|
||||
// A name that ends in pass (a db_pass) is one too (#2946); a name that only
|
||||
// ends in key is not — a sort key, a cache key, a public key hold no secret.
|
||||
var secretName = regexp.MustCompile(`(?i)` + secretNames.pattern() + `|authori[sz]ation|cookie|^key$|^pass$|_pass$`)
|
||||
var secretName = lazyre.New(`(?i)` + secretNames.pattern() + `|authori[sz]ation|cookie|^key$|^pass$|_pass$`)
|
||||
|
||||
// SecretName says a field or header called name holds a secret: a token,
|
||||
// key, password or cookie — not a count of tokens (max_tokens).
|
||||
|
||||
@@ -5,9 +5,10 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"net/netip"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// A key can go to the vendor as a made-up key of its own form instead of
|
||||
@@ -67,7 +68,7 @@ func keyHead(v string) string {
|
||||
}
|
||||
|
||||
// namedValue is a name before = or : and the value after it.
|
||||
var namedValue = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_.-]*[ \t]*[=:][ \t]*()`)
|
||||
var namedValue = lazyre.New(`^[A-Za-z_][A-Za-z0-9_.-]*[ \t]*[=:][ \t]*()`)
|
||||
|
||||
// splitName parts a value found with its name, as 密钥
|
||||
// OPENAI_API_KEY=sk_… is, into the name, which stays as written, and the
|
||||
|
||||
Reference in New Issue
Block a user