agy-cli 0.1.14: tool schema patterns are turned into RE2 or dropped, so an ECMA-262 pattern no longer aborts the turn (klarkxy #946)
Tool input schemas' `pattern` and `patternProperties` keys are translated to RE2 (re2-pattern.mjs) before they reach agy; a pattern RE2 can't hold is dropped with a hint, and `additionalProperties: false` is lifted when every patternProperties key was dropped. Closes #944. Reviewed head 99093088 (onc27ba5f7), landed onto maina0b1e491with the version moved to 0.1.14. Run at the reviewed head: WSL2 bun test packages/agy-cli 9 of 9, check.mjs ok; Windows 8 pass, 1 fail, the same smoke red as main (#973). A fuzz of 1,033 kept patterns compiled every one with Go's regexp (go1.26.8), against 222 failures before the `[:` fix. Broken by hand: the `[:` reject, the sanitizePatternFields call, the propertyNames / contains / if / then / else / unevaluated* recursion and the additionalProperties lift each turn re2-pattern-unit.mjs red. Run at this commit (WSL2 Ubuntu 24.04, Bun 1.4.2, temp HOME): bun test packages/agy-cli 9 of 9 pass; bun scripts/check.mjs agy-cli ok. Not tried: macOS (mote refused ssh), a real agy. Closes #946 Co-authored-by: klarkxy <klarkxy@users.noreply.github.com>
This commit is contained in:
@@ -30,6 +30,13 @@ for (const [name, mocks] of [
|
||||
}, 250_000)
|
||||
}
|
||||
|
||||
|
||||
test("test/re2-pattern-unit.mjs", () => {
|
||||
const { code, output } = run([path.join(dir, "re2-pattern-unit.mjs")], 60_000)
|
||||
expect(output).toMatch(/ALL OK/)
|
||||
expect(code).toBe(0)
|
||||
}, 70_000)
|
||||
|
||||
test("test/smoke.mjs against a fake agy", () => {
|
||||
const { code, output } = run([path.join(dir, "smoke.mjs")], 240_000)
|
||||
expect(output).toMatch(/ALL OK \(\d+ checks\)/)
|
||||
|
||||
@@ -8,6 +8,7 @@ import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import { createUsageReader } from "./usage.mjs"
|
||||
import { sanitizePatternFields } from "./re2-pattern.mjs"
|
||||
import { startLogin } from "./login.mjs"
|
||||
|
||||
const PROVIDER_ID = "agy-cli"
|
||||
@@ -2866,6 +2867,20 @@ function sanitizeInputSchema(schema) {
|
||||
)
|
||||
}
|
||||
}
|
||||
for (const key of ["propertyNames", "contains", "if", "then", "else", "unevaluatedProperties", "unevaluatedItems"]) {
|
||||
if (out[key] && typeof out[key] === "object" && !Array.isArray(out[key])) {
|
||||
out[key] = sanitizeInputSchema(out[key])
|
||||
}
|
||||
}
|
||||
if (out.dependentSchemas && typeof out.dependentSchemas === "object" && !Array.isArray(out.dependentSchemas)) {
|
||||
out.dependentSchemas = Object.fromEntries(
|
||||
Object.entries(out.dependentSchemas).map(([key, value]) => [key, sanitizeInputSchema(value)]),
|
||||
)
|
||||
}
|
||||
// agy (Go/RE2) will reject the whole toolbox if any pattern is only valid as
|
||||
// ECMA-262. Translate or drop those patterns here; tool-call arguments in
|
||||
// the response are plain JSON and do not need a reverse transform.
|
||||
sanitizePatternFields(out)
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -3934,6 +3949,8 @@ function makeAnthropicStream(proc, turn, body, msgId, signal, step = turn.regist
|
||||
send("content_block_start", {
|
||||
type: "content_block_start",
|
||||
index: blockIndex,
|
||||
// Schema sanitization is outbound only: tool_use carries id, name, and
|
||||
// JSON arguments, never the parameter schema, so nothing is rewritten here.
|
||||
content_block: { type: "tool_use", id: call.id, name: call.name, input: {} },
|
||||
})
|
||||
send("content_block_delta", {
|
||||
@@ -4564,4 +4581,5 @@ process.once("exit", () => {
|
||||
}
|
||||
})
|
||||
|
||||
export { sanitizeInputSchema }
|
||||
export default { id: PROVIDER_ID, server: AntigravityBridgePlugin }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-agy-cli-auth",
|
||||
"version": "0.1.13",
|
||||
"version": "0.1.14",
|
||||
"description": "Magpie/OpenCode model provider that connects your local agy CLI through the Agent Client Protocol (agy acp), so Antigravity subscription models run through the real CLI",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
@@ -18,7 +18,8 @@
|
||||
"README.md",
|
||||
"README.en.md",
|
||||
"LICENSE",
|
||||
"NOTICE.md"
|
||||
"NOTICE.md",
|
||||
"re2-pattern.mjs"
|
||||
],
|
||||
"keywords": [
|
||||
"magpie",
|
||||
|
||||
@@ -0,0 +1,604 @@
|
||||
// RE2-safe JSON Schema `pattern` / `patternProperties` handling for agy.
|
||||
//
|
||||
// agy validates every tool parameter schema against the JSON Schema 2020-12
|
||||
// metaschema using Go's `regexp` library (RE2). JSON Schema defines `pattern`
|
||||
// as an ECMA-262 regular expression, so constructs that are legal in JavaScript
|
||||
// — `\uXXXX` / `\u{...}` escapes, lookaheads, backreferences — make agy fail
|
||||
// "building toolbox" and abort the whole turn before any model call.
|
||||
//
|
||||
// We translate the Unicode escapes RE2 can express (`\uXXXX` → `\x{XXXX}`),
|
||||
// join UTF-16 surrogate pairs into one code point (including mixed escaped
|
||||
// and raw pairs), then drop anything still not compilable as RE2 — or whose
|
||||
// RE2 meaning is not the ECMA-262 meaning, such as `\z`, `\S`, `\Q…\E`,
|
||||
// `\a`, and `\A` — into a description hint. Common character classes
|
||||
// (`\s`, `\d`, `\w`) are kept even though RE2 is ASCII-only for these;
|
||||
// dropping `\s` would disable many ordinary tool schemas. The rewrite is
|
||||
// idempotent. Tool-call arguments are plain JSON values, not patterns, so
|
||||
// the response path needs no reverse transform.
|
||||
//
|
||||
// See: https://github.com/google-antigravity/antigravity-cli/issues/1327
|
||||
|
||||
const HINT_PREFIX = "pattern: "
|
||||
|
||||
export function appendHint(node, hint) {
|
||||
if (!hint || !node || typeof node !== "object" || Array.isArray(node)) return
|
||||
if (typeof node.description === "string" && node.description.trim()) {
|
||||
if (!node.description.includes(hint)) node.description = `${node.description} (${hint})`
|
||||
} else {
|
||||
node.description = hint
|
||||
}
|
||||
}
|
||||
|
||||
const HIGH_SURROGATE_START = 0xD800
|
||||
const HIGH_SURROGATE_END = 0xDBFF
|
||||
const LOW_SURROGATE_START = 0xDC00
|
||||
const LOW_SURROGATE_END = 0xDFFF
|
||||
const UNICODE_MAX = 0x10FFFF
|
||||
|
||||
function isHighSurrogate(cp) {
|
||||
return cp >= HIGH_SURROGATE_START && cp <= HIGH_SURROGATE_END
|
||||
}
|
||||
|
||||
function isLowSurrogate(cp) {
|
||||
return cp >= LOW_SURROGATE_START && cp <= LOW_SURROGATE_END
|
||||
}
|
||||
|
||||
function joinSurrogates(high, low) {
|
||||
return 0x10000 + ((high - HIGH_SURROGATE_START) << 10) + (low - LOW_SURROGATE_START)
|
||||
}
|
||||
|
||||
function isHex(char) {
|
||||
return /[0-9a-fA-F]/.test(char)
|
||||
}
|
||||
|
||||
function parseUnicodeEscape(source, idx) {
|
||||
if (source[idx] !== "\\") return null
|
||||
const rest = source.slice(idx + 1)
|
||||
let match = /^u\{([0-9a-fA-F]+)\}/.exec(rest)
|
||||
if (match) return { end: idx + 1 + match[0].length, cp: parseInt(match[1], 16), hex: match[1] }
|
||||
match = /^u([0-9a-fA-F]{4})/.exec(rest)
|
||||
if (match) return { end: idx + 1 + match[0].length, cp: parseInt(match[1], 16), hex: match[1] }
|
||||
match = /^U([0-9a-fA-F]{8})/.exec(rest)
|
||||
if (match) return { end: idx + 1 + match[0].length, cp: parseInt(match[1], 16), hex: match[1] }
|
||||
match = /^x\{([0-9a-fA-F]+)\}/.exec(rest)
|
||||
if (match) return { end: idx + 1 + match[0].length, cp: parseInt(match[1], 16), hex: match[1] }
|
||||
return null
|
||||
}
|
||||
|
||||
function emitHex(cp, hex = null) {
|
||||
if (hex != null && Number.parseInt(hex, 16) === cp) return `\\x{${hex}}`
|
||||
const digits = cp.toString(16).toUpperCase()
|
||||
return `\\x{${cp <= 0xFFFF ? digits.padStart(4, "0") : digits}}`
|
||||
}
|
||||
|
||||
// Escape-aware translation of ECMA-262 Unicode escapes into RE2 `\x{...}`.
|
||||
// Adjacent UTF-16 surrogate escapes (and raw surrogate pairs in the string)
|
||||
// are joined into one code point so `😀` stays a single character in RE2.
|
||||
// `\\u0000` (a literal backslash then the letters u0000) is left alone.
|
||||
export function translateUnicodeEscapes(source) {
|
||||
if (typeof source !== "string") return source
|
||||
let out = ""
|
||||
let i = 0
|
||||
const length = source.length
|
||||
while (i < length) {
|
||||
const parsed = parseUnicodeEscape(source, i)
|
||||
if (parsed) {
|
||||
const next = parseUnicodeEscape(source, parsed.end)
|
||||
if (Number.isFinite(parsed.cp) && isHighSurrogate(parsed.cp) && next && Number.isFinite(next.cp) && isLowSurrogate(next.cp)) {
|
||||
out += emitHex(joinSurrogates(parsed.cp, next.cp))
|
||||
i = next.end
|
||||
continue
|
||||
}
|
||||
// Mixed: escaped high surrogate + raw low surrogate code unit.
|
||||
if (Number.isFinite(parsed.cp) && isHighSurrogate(parsed.cp) && parsed.end < length) {
|
||||
const rawLow = source.charCodeAt(parsed.end)
|
||||
if (isLowSurrogate(rawLow)) {
|
||||
out += emitHex(joinSurrogates(parsed.cp, rawLow))
|
||||
i = parsed.end + 1
|
||||
continue
|
||||
}
|
||||
}
|
||||
out += emitHex(parsed.cp, parsed.hex)
|
||||
i = parsed.end
|
||||
continue
|
||||
}
|
||||
if (source[i] === "\\") {
|
||||
out += source[i++]
|
||||
if (i < length) out += source[i++]
|
||||
continue
|
||||
}
|
||||
const code = source.charCodeAt(i)
|
||||
if (isHighSurrogate(code) && i + 1 < length) {
|
||||
const next = parseUnicodeEscape(source, i + 1)
|
||||
if (next && Number.isFinite(next.cp) && isLowSurrogate(next.cp)) {
|
||||
out += emitHex(joinSurrogates(code, next.cp))
|
||||
i = next.end
|
||||
continue
|
||||
}
|
||||
const low = source.charCodeAt(i + 1)
|
||||
if (isLowSurrogate(low)) {
|
||||
out += emitHex(joinSurrogates(code, low))
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
}
|
||||
out += source[i++]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Letters accepted after a backslash outside a character class, when the
|
||||
// RE2 meaning matches ECMA-262 closely enough to keep. `\z` and `\S`
|
||||
// compile in RE2 but differ from JS (yetone called these out). `\a` is
|
||||
// BEL in RE2 and a literal `a` in non-unicode JS; `\A` is start-of-text
|
||||
// in RE2 and a literal `A` in JS; `\Q…\E` is quoting in RE2 and not
|
||||
// an ECMA-262 construct. All of those are dropped into a hint.
|
||||
// `\s` / `\d` / `\w` are kept (RE2 is ASCII-only for these).
|
||||
const RE2_LETTER_ESCAPES = new Set([
|
||||
"f", "n", "r", "t", "v",
|
||||
"b", "B", "d", "D", "s", "w", "W",
|
||||
])
|
||||
|
||||
// `\b` / `\B` / `\A` / `\z` / `\Q` / `\E` / `\a` are not kept inside a class.
|
||||
const RE2_CLASS_LETTER_ESCAPES = new Set([
|
||||
"f", "n", "r", "t", "v",
|
||||
"d", "D", "s", "w", "W",
|
||||
])
|
||||
|
||||
const SINGLE_ESCAPE_CP = {
|
||||
f: 0x0c,
|
||||
n: 0x0a,
|
||||
r: 0x0d,
|
||||
t: 0x09,
|
||||
v: 0x0b,
|
||||
}
|
||||
|
||||
const RE2_GROUP_FLAGS = new Set(["i", "m", "s", "U"])
|
||||
|
||||
// Names Go's `regexp` accepts in `\p{...}` / `\P{...}` (case-insensitive).
|
||||
// Includes general categories, scripts, and the aliases Go documents (Any,
|
||||
// ASCII, Assigned, Letter, …). `Script=Greek` and other key=value forms are
|
||||
// not in this set and are rejected. Generated against Go 1.27's `regexp`.
|
||||
const RE2_UNICODE_PROPERTIES = new Set([
|
||||
"adlam", "ahom", "anatolian_hieroglyphs", "any", "arabic", "armenian", "ascii", "assigned",
|
||||
"avestan", "balinese", "bamum", "bassa_vah", "batak", "bengali", "beria_erfe", "bhaiksuki",
|
||||
"bopomofo", "brahmi", "braille", "buginese", "buhid", "c", "canadian_aboriginal", "carian",
|
||||
"cased_letter", "caucasian_albanian", "cc", "cf", "chakma", "cham", "cherokee", "chorasmian",
|
||||
"close_punctuation", "cn", "cntrl", "co", "common", "connector_punctuation", "control", "coptic",
|
||||
"cs", "cuneiform", "currency_symbol", "cypriot", "cypro_minoan", "cyrillic", "dash_punctuation", "decimal_number",
|
||||
"deseret", "devanagari", "digit", "dives_akuru", "dogra", "duployan", "egyptian_hieroglyphs", "elbasan",
|
||||
"elymaic", "enclosing_mark", "ethiopic", "final_punctuation", "format", "garay", "georgian", "glagolitic",
|
||||
"gothic", "grantha", "greek", "gujarati", "gunjala_gondi", "gurmukhi", "gurung_khema", "han",
|
||||
"hangul", "hanifi_rohingya", "hanunoo", "hatran", "hebrew", "hiragana", "imperial_aramaic", "inherited",
|
||||
"initial_punctuation", "inscriptional_pahlavi", "inscriptional_parthian", "javanese", "kaithi", "kannada", "katakana", "kawi",
|
||||
"kayah_li", "kharoshthi", "khitan_small_script", "khmer", "khojki", "khudawadi", "kirat_rai", "l",
|
||||
"lao", "latin", "lc", "lepcha", "letter", "letter_number", "limbu", "line_separator",
|
||||
"linear_a", "linear_b", "lisu", "ll", "lm", "lo", "lowercase_letter", "lt",
|
||||
"lu", "lycian", "lydian", "m", "mahajani", "makasar", "malayalam", "mandaic",
|
||||
"manichaean", "marchen", "mark", "masaram_gondi", "math_symbol", "mc", "me", "medefaidrin",
|
||||
"meetei_mayek", "mende_kikakui", "meroitic_cursive", "meroitic_hieroglyphs", "miao", "mn", "modi", "modifier_letter",
|
||||
"modifier_symbol", "mongolian", "mro", "multani", "myanmar", "n", "nabataean", "nag_mundari",
|
||||
"nandinagari", "nd", "new_tai_lue", "newa", "nko", "nl", "no", "nonspacing_mark",
|
||||
"number", "nushu", "nyiakeng_puachue_hmong", "ogham", "ol_chiki", "ol_onal", "old_hungarian", "old_italic",
|
||||
"old_north_arabian", "old_permic", "old_persian", "old_sogdian", "old_south_arabian", "old_turkic", "old_uyghur", "open_punctuation",
|
||||
"oriya", "osage", "osmanya", "other", "other_letter", "other_number", "other_punctuation", "other_symbol",
|
||||
"p", "pahawh_hmong", "palmyrene", "paragraph_separator", "pau_cin_hau", "pc", "pd", "pe",
|
||||
"pf", "phags_pa", "phoenician", "pi", "po", "private_use", "ps", "psalter_pahlavi",
|
||||
"punct", "punctuation", "rejang", "runic", "s", "samaritan", "saurashtra", "sc",
|
||||
"separator", "sharada", "shavian", "siddham", "sidetic", "signwriting", "sinhala", "sk",
|
||||
"sm", "so", "sogdian", "sora_sompeng", "soyombo", "space_separator", "spacing_mark", "sundanese",
|
||||
"sunuwar", "surrogate", "syloti_nagri", "symbol", "syriac", "tagalog", "tagbanwa", "tai_le",
|
||||
"tai_tham", "tai_viet", "tai_yo", "takri", "tamil", "tangsa", "tangut", "telugu",
|
||||
"thaana", "thai", "tibetan", "tifinagh", "tirhuta", "titlecase_letter", "todhri", "tolong_siki",
|
||||
"toto", "tulu_tigalari", "ugaritic", "unassigned", "uppercase_letter", "vai", "vithkuqi", "wancho",
|
||||
"warang_citi", "yezidi", "yi", "z", "zanabazar_square", "zl", "zp", "zs",
|
||||
])
|
||||
|
||||
function isKnownUnicodeProperty(name) {
|
||||
if (typeof name !== "string" || !name) return false
|
||||
const body = name[0] === "^" ? name.slice(1) : name
|
||||
return body.length > 0 && RE2_UNICODE_PROPERTIES.has(body.toLowerCase())
|
||||
}
|
||||
|
||||
function isCodePointInRange(cp) {
|
||||
return Number.isInteger(cp) && cp >= 0 && cp <= UNICODE_MAX
|
||||
}
|
||||
|
||||
// Conservative RE2 compiler check. Returns true only when the pattern should
|
||||
// compile with Go's `regexp.Compile` (the same engine agy uses) *and* keep
|
||||
// its JavaScript meaning. Anything we cannot positively accept is rejected,
|
||||
// which drops the pattern into a hint rather than risking a toolbox failure.
|
||||
export function isRE2Safe(source) {
|
||||
if (typeof source !== "string") return false
|
||||
const length = source.length
|
||||
let i = 0
|
||||
let depth = 0
|
||||
let canQuantify = false
|
||||
|
||||
// Repeat-product tracking, matching Go's repeatIsValid(..., 1000):
|
||||
// the product of nested `{n}` / `{n,m}` / `{n,}` maxima (min if unbounded)
|
||||
// along any one path must not exceed 1000. Concat and alternation take
|
||||
// the max of their children, not the product. `*`, `+`, `?`, `{0,}`, and
|
||||
// `{1,}` are not OpRepeat product-checked in Go.
|
||||
const groupStack = [{ alt: 1, best: 1, last: 1 }]
|
||||
const ctx = () => groupStack[groupStack.length - 1]
|
||||
const foldLast = () => {
|
||||
const c = ctx()
|
||||
c.alt = Math.max(c.alt, c.last)
|
||||
}
|
||||
const noteAtom = (mass = 1) => {
|
||||
foldLast()
|
||||
ctx().last = mass
|
||||
canQuantify = true
|
||||
}
|
||||
|
||||
const parseEscape = (inCharClass) => {
|
||||
// Called at `\`. Returns null on error, or {set} / {cp}.
|
||||
if (i >= length || source[i] !== "\\") return null
|
||||
i++
|
||||
if (i >= length) return null
|
||||
const next = source[i++]
|
||||
if (next >= "1" && next <= "9") return null
|
||||
if (next === "0") {
|
||||
let extra = 0
|
||||
let oct = 0
|
||||
while (extra < 2 && i < length && source[i] >= "0" && source[i] <= "7") {
|
||||
oct = (oct << 3) + (source[i++] - "0")
|
||||
extra++
|
||||
}
|
||||
return { cp: oct }
|
||||
}
|
||||
if (next === "x") {
|
||||
if (i < length && source[i] === "{") {
|
||||
i++
|
||||
let hex = ""
|
||||
while (i < length && isHex(source[i])) hex += source[i++]
|
||||
if (!hex || i >= length || source[i] !== "}") return null
|
||||
i++
|
||||
const cp = Number.parseInt(hex, 16)
|
||||
if (!isCodePointInRange(cp)) return null
|
||||
return { cp }
|
||||
}
|
||||
if (i + 1 < length && isHex(source[i]) && isHex(source[i + 1])) {
|
||||
const cp = Number.parseInt(source.slice(i, i + 2), 16)
|
||||
i += 2
|
||||
return { cp }
|
||||
}
|
||||
return null
|
||||
}
|
||||
if (next === "p" || next === "P") {
|
||||
if (i < length && source[i] === "{") {
|
||||
i++
|
||||
let name = ""
|
||||
while (i < length && source[i] !== "}") {
|
||||
const char = source[i]
|
||||
if (!/[A-Za-z0-9_^]/.test(char)) return null
|
||||
name += char
|
||||
i++
|
||||
}
|
||||
if (!name || i >= length || source[i] !== "}") return null
|
||||
i++
|
||||
if (!isKnownUnicodeProperty(name)) return null
|
||||
return { set: true }
|
||||
}
|
||||
if (i < length && /[A-Za-z]/.test(source[i])) {
|
||||
const name = source[i++]
|
||||
if (!isKnownUnicodeProperty(name)) return null
|
||||
return { set: true }
|
||||
}
|
||||
return null
|
||||
}
|
||||
// `\Q…\E` is RE2 quoting, not ECMA-262. Drop it.
|
||||
if (next === "Q" || next === "E") return null
|
||||
if (next === "u" || next === "U" || next === "C" || next === "k" || next === "Z" || next === "G") return null
|
||||
// `\z` and `\S` compile in RE2 but differ from JS; drop them.
|
||||
// `\a` / `\A` also differ from JS (BEL / start-of-text vs literal letters).
|
||||
if (next === "z" || next === "S" || next === "a" || next === "A") return null
|
||||
if (/[A-Za-z]/.test(next)) {
|
||||
const allowed = (inCharClass ? RE2_CLASS_LETTER_ESCAPES : RE2_LETTER_ESCAPES).has(next)
|
||||
if (!allowed) return null
|
||||
if (next === "d" || next === "D" || next === "s" || next === "w" || next === "W") return { set: true }
|
||||
if (next === "b" || next === "B") return { set: true }
|
||||
if (Object.hasOwn(SINGLE_ESCAPE_CP, next)) return { cp: SINGLE_ESCAPE_CP[next] }
|
||||
return { set: true }
|
||||
}
|
||||
// Unknown letter-like or non-ASCII escapes (`\é`) are invalid in RE2.
|
||||
// Punctuation escapes (`\.`, `\ `, `\-`, …) are accepted as that character.
|
||||
if (/^[A-Za-z]$/.test(next) === false && next.charCodeAt(0) >= 0x80) return null
|
||||
return { cp: next.charCodeAt(0) }
|
||||
}
|
||||
|
||||
const parseClassItem = () => {
|
||||
if (i >= length) return null
|
||||
if (source[i] === "\\") return parseEscape(true)
|
||||
let cp = source.charCodeAt(i++)
|
||||
if (isHighSurrogate(cp) && i < length && isLowSurrogate(source.charCodeAt(i))) {
|
||||
cp = joinSurrogates(cp, source.charCodeAt(i++))
|
||||
}
|
||||
return { cp }
|
||||
}
|
||||
|
||||
const consumeClass = () => {
|
||||
// Called at `[`. Rejects inverted ranges (`[z-a]`) the way Go does
|
||||
// (`hi < lo` is ErrInvalidCharRange).
|
||||
i++
|
||||
if (i < length && source[i] === "^") i++
|
||||
let justOpened = true
|
||||
while (i < length) {
|
||||
if (source[i] === "]" && !justOpened) {
|
||||
i++
|
||||
return true
|
||||
}
|
||||
// Go treats `[:` inside a class as a POSIX named class (`[[:alpha:]]`).
|
||||
// JS does not, so keepers would either fail to compile in RE2 or
|
||||
// match a different set. Reject the pattern and drop it to a hint.
|
||||
if (source[i] === "[" && i + 1 < length && source[i + 1] === ":") return false
|
||||
const lo = parseClassItem()
|
||||
if (!lo) return false
|
||||
justOpened = false
|
||||
// `[a-]` : the '-' before ']' is literal, not a range.
|
||||
if (lo.cp != null && i < length && source[i] === "-" && i + 1 < length && source[i + 1] !== "]") {
|
||||
i++
|
||||
const hi = parseClassItem()
|
||||
if (!hi) return false
|
||||
if (hi.cp == null) return false
|
||||
if (hi.cp < lo.cp) return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const applyRepeatProduct = (min, maxStr) => {
|
||||
const hasMax = maxStr != null && maxStr !== ""
|
||||
const max = hasMax ? Number(maxStr) : null
|
||||
// Go only product-checks OpRepeat when min >= 2 or max >= 2.
|
||||
// `{0,}`, `{1,}`, `{1}` and `{0,1}` are not product-checked.
|
||||
const productChecked = min >= 2 || (hasMax && max >= 2)
|
||||
if (!productChecked) return true
|
||||
const m = hasMax ? max : min
|
||||
const last = ctx().last || 1
|
||||
if (m > 0 && last * m > 1000) return false
|
||||
ctx().last = last * m
|
||||
return true
|
||||
}
|
||||
|
||||
const consumeRepeat = () => {
|
||||
// Called at `{`. A well-formed bound is `{n}`, `{n,}` or `{n,m}`.
|
||||
// RE2 rejects a leading or nested well-formed bound, a bound above 1000,
|
||||
// min > max, and a nested product of maxima above 1000 (e.g. `(a{1000}){2}`).
|
||||
// A `{` that is not a well-formed bound is a literal.
|
||||
const start = i
|
||||
i++
|
||||
if (i >= length || source[i] < "0" || source[i] > "9") {
|
||||
i = start + 1
|
||||
noteAtom(1)
|
||||
return true
|
||||
}
|
||||
let minStr = ""
|
||||
while (i < length && source[i] >= "0" && source[i] <= "9") minStr += source[i++]
|
||||
let maxStr = null
|
||||
if (i < length && source[i] === ",") {
|
||||
i++
|
||||
maxStr = ""
|
||||
while (i < length && source[i] >= "0" && source[i] <= "9") maxStr += source[i++]
|
||||
}
|
||||
if (i >= length || source[i] !== "}") {
|
||||
i = start + 1
|
||||
noteAtom(1)
|
||||
return true
|
||||
}
|
||||
if (!canQuantify) return false
|
||||
const min = Number(minStr)
|
||||
if (min > 1000) return false
|
||||
if (maxStr != null && maxStr !== "") {
|
||||
const max = Number(maxStr)
|
||||
if (max > 1000 || min > max) return false
|
||||
}
|
||||
i++
|
||||
if (i < length && source[i] === "?") i++
|
||||
else if (i < length && source[i] === "+") return false
|
||||
if (!applyRepeatProduct(min, maxStr)) return false
|
||||
canQuantify = false
|
||||
return true
|
||||
}
|
||||
|
||||
const consumeNamedGroup = () => {
|
||||
// Called after `(?<` or `(?P<`.
|
||||
let name = 0
|
||||
while (i < length && source[i] !== ">") {
|
||||
if (!/[A-Za-z0-9_]/.test(source[i])) return false
|
||||
i++
|
||||
name++
|
||||
}
|
||||
if (name === 0 || i >= length || source[i] !== ">") return false
|
||||
i++
|
||||
depth++
|
||||
foldLast()
|
||||
groupStack.push({ alt: 1, best: 1, last: 1 })
|
||||
canQuantify = false
|
||||
return true
|
||||
}
|
||||
|
||||
const consumeGroup = () => {
|
||||
// Called at `(`.
|
||||
i++
|
||||
if (i < length && source[i] === "?") {
|
||||
i++
|
||||
if (i >= length) return false
|
||||
const next = source[i]
|
||||
if (next === ":") {
|
||||
i++
|
||||
depth++
|
||||
foldLast()
|
||||
groupStack.push({ alt: 1, best: 1, last: 1 })
|
||||
canQuantify = false
|
||||
return true
|
||||
}
|
||||
if (next === "P") {
|
||||
i++
|
||||
if (i >= length || source[i] !== "<") return false
|
||||
i++
|
||||
return consumeNamedGroup()
|
||||
}
|
||||
if (next === "<") {
|
||||
// Go 1.26+ accepts `(?<name>…)` as well as `(?P<name>…)`.
|
||||
// Lookbehinds `(?<=` / `(?<!` are still rejected.
|
||||
i++
|
||||
if (i < length && (source[i] === "=" || source[i] === "!")) return false
|
||||
return consumeNamedGroup()
|
||||
}
|
||||
// Flags: (?imsU) or (?imsU-imsU) or (?imsU:...) — not lookaheads.
|
||||
let flags = 0
|
||||
while (i < length && RE2_GROUP_FLAGS.has(source[i])) {
|
||||
i++
|
||||
flags++
|
||||
}
|
||||
if (i < length && source[i] === "-") {
|
||||
i++
|
||||
while (i < length && RE2_GROUP_FLAGS.has(source[i])) {
|
||||
i++
|
||||
flags++
|
||||
}
|
||||
}
|
||||
if (i < length && source[i] === ":") {
|
||||
if (flags === 0) return false
|
||||
i++
|
||||
depth++
|
||||
foldLast()
|
||||
groupStack.push({ alt: 1, best: 1, last: 1 })
|
||||
canQuantify = false
|
||||
return true
|
||||
}
|
||||
if (i < length && source[i] === ")") {
|
||||
if (flags === 0) return false
|
||||
i++
|
||||
canQuantify = false
|
||||
return true
|
||||
}
|
||||
// `(?=`, `(?!`, `(?>`, `(?(` …
|
||||
return false
|
||||
}
|
||||
depth++
|
||||
foldLast()
|
||||
groupStack.push({ alt: 1, best: 1, last: 1 })
|
||||
canQuantify = false
|
||||
return true
|
||||
}
|
||||
|
||||
while (i < length) {
|
||||
const char = source[i]
|
||||
if (char === "\\") {
|
||||
if (!parseEscape(false)) return false
|
||||
noteAtom(1)
|
||||
continue
|
||||
}
|
||||
if (char === "[") {
|
||||
if (!consumeClass()) return false
|
||||
noteAtom(1)
|
||||
continue
|
||||
}
|
||||
if (char === "]") return false
|
||||
if (char === "(") {
|
||||
if (!consumeGroup()) return false
|
||||
continue
|
||||
}
|
||||
if (char === ")") {
|
||||
if (depth <= 0 || groupStack.length <= 1) return false
|
||||
depth--
|
||||
const inner = groupStack.pop()
|
||||
ctx().last = Math.max(inner.best, inner.alt, inner.last)
|
||||
canQuantify = true
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if (char === "*" || char === "+" || char === "?") {
|
||||
if (!canQuantify) return false
|
||||
i++
|
||||
if (i < length && source[i] === "?") i++
|
||||
else if (i < length && source[i] === "+") return false
|
||||
canQuantify = false
|
||||
continue
|
||||
}
|
||||
if (char === "{") {
|
||||
if (!consumeRepeat()) return false
|
||||
continue
|
||||
}
|
||||
if (char === "|") {
|
||||
const c = ctx()
|
||||
c.best = Math.max(c.best, c.alt, c.last)
|
||||
c.alt = 1
|
||||
c.last = 1
|
||||
canQuantify = false
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if (char === "^" || char === "$") {
|
||||
canQuantify = false
|
||||
i++
|
||||
continue
|
||||
}
|
||||
// Ordinary literal, including UTF-16 surrogate pairs as one atom.
|
||||
if (isHighSurrogate(source.charCodeAt(i)) && i + 1 < length && isLowSurrogate(source.charCodeAt(i + 1))) {
|
||||
i += 2
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
noteAtom(1)
|
||||
}
|
||||
return depth === 0 && groupStack.length === 1
|
||||
}
|
||||
|
||||
export function sanitizePatternString(original) {
|
||||
if (typeof original !== "string") {
|
||||
return { ok: false, pattern: undefined, original }
|
||||
}
|
||||
const translated = translateUnicodeEscapes(original)
|
||||
if (isRE2Safe(translated)) {
|
||||
return { ok: true, pattern: translated, original }
|
||||
}
|
||||
return { ok: false, pattern: undefined, original }
|
||||
}
|
||||
|
||||
// Mutates a single schema node: `pattern` and `patternProperties` keys.
|
||||
// Recursion into child schemas is the caller's job (sanitizeInputSchema).
|
||||
export function sanitizePatternFields(node) {
|
||||
if (!node || typeof node !== "object" || Array.isArray(node)) return node
|
||||
|
||||
if (Object.hasOwn(node, "pattern")) {
|
||||
const result = sanitizePatternString(node.pattern)
|
||||
if (result.ok) {
|
||||
node.pattern = result.pattern
|
||||
} else {
|
||||
const shown = typeof result.original === "string" ? result.original : JSON.stringify(result.original)
|
||||
appendHint(node, `${HINT_PREFIX}${shown}`)
|
||||
delete node.pattern
|
||||
}
|
||||
}
|
||||
|
||||
if (node.patternProperties && typeof node.patternProperties === "object" && !Array.isArray(node.patternProperties)) {
|
||||
const next = {}
|
||||
const dropped = []
|
||||
for (const [key, value] of Object.entries(node.patternProperties)) {
|
||||
const result = sanitizePatternString(key)
|
||||
if (result.ok) next[result.pattern] = value
|
||||
else dropped.push(key)
|
||||
}
|
||||
if (dropped.length) {
|
||||
appendHint(node, `dropped patternProperties: ${dropped.join(", ")}`)
|
||||
}
|
||||
if (Object.keys(next).length) {
|
||||
node.patternProperties = next
|
||||
} else {
|
||||
delete node.patternProperties
|
||||
// If every key was dropped and additionalProperties is false, the
|
||||
// object would now reject every property. Lift that so the schema
|
||||
// stays usable; the hint already records what was dropped.
|
||||
if (node.additionalProperties === false) {
|
||||
delete node.additionalProperties
|
||||
appendHint(node, "additionalProperties:false was lifted because every patternProperties key was dropped")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return node
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Helper for re2-pattern-unit.mjs: compile each stdin JSON line's "pattern"
|
||||
// with Go's regexp (RE2) and print whether it succeeded.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
type req struct {
|
||||
Pattern string `json:"pattern"`
|
||||
}
|
||||
|
||||
type res struct {
|
||||
Pattern string `json:"pattern"`
|
||||
OK bool `json:"ok"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Match *bool `json:"match,omitempty"`
|
||||
Input string `json:"input,omitempty"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
// Patterns can be long; raise the limit.
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
|
||||
out := json.NewEncoder(os.Stdout)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Bytes()
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
var r req
|
||||
var extra struct {
|
||||
Pattern string `json:"pattern"`
|
||||
Input string `json:"input"`
|
||||
}
|
||||
if err := json.Unmarshal(line, &extra); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "bad json: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
r.Pattern = extra.Pattern
|
||||
re, err := regexp.Compile(r.Pattern)
|
||||
row := res{Pattern: r.Pattern, OK: err == nil}
|
||||
if err != nil {
|
||||
row.Error = err.Error()
|
||||
} else if extra.Input != "" || (err == nil && jsonHasInput(line)) {
|
||||
matched := re.MatchString(extra.Input)
|
||||
row.Match = &matched
|
||||
row.Input = extra.Input
|
||||
}
|
||||
if err := out.Encode(row); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "encode: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "stdin: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func jsonHasInput(line []byte) bool {
|
||||
var m map[string]any
|
||||
if json.Unmarshal(line, &m) != nil {
|
||||
return false
|
||||
}
|
||||
_, ok := m["input"]
|
||||
return ok
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
// Standalone checks for RE2 pattern sanitization. Run with:
|
||||
// node test/re2-pattern-unit.mjs
|
||||
import { strict as assert } from "node:assert"
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import path from "node:path"
|
||||
import {
|
||||
translateUnicodeEscapes,
|
||||
isRE2Safe,
|
||||
sanitizePatternString,
|
||||
sanitizePatternFields,
|
||||
} from "../re2-pattern.mjs"
|
||||
import { sanitizeInputSchema } from "../index.mjs"
|
||||
|
||||
const NUL_CLASS = "^[^\\u0000]*$"
|
||||
const NUL_CLASS_RE2 = "^[^\\x{0000}]*$"
|
||||
const PATH_LOOKAHEAD = "^/(?!/)(?:[^\\u0000-\\u0020\\u007f\\\\#%]|%[0-9a-fA-F]{2})*(?![\\s\\S])"
|
||||
|
||||
let failed = 0
|
||||
function check(name, ok, detail) {
|
||||
if (ok) {
|
||||
console.log(`ok ${name}`)
|
||||
return
|
||||
}
|
||||
failed++
|
||||
console.error(`FAIL ${name}${detail ? " :: " + detail : ""}`)
|
||||
}
|
||||
|
||||
check("translate \\u0000 in a character class",
|
||||
translateUnicodeEscapes(NUL_CLASS) === NUL_CLASS_RE2,
|
||||
translateUnicodeEscapes(NUL_CLASS))
|
||||
|
||||
check("translate \\u{0000} and \\u007f",
|
||||
translateUnicodeEscapes("\\u{0000}\\u007f") === "\\x{0000}\\x{007f}",
|
||||
translateUnicodeEscapes("\\u{0000}\\u007f"))
|
||||
|
||||
check("translate is idempotent on \\x{0000}",
|
||||
translateUnicodeEscapes(NUL_CLASS_RE2) === NUL_CLASS_RE2)
|
||||
|
||||
check("does not translate a literal backslash-u sequence",
|
||||
translateUnicodeEscapes("\\\\u0000") === "\\\\u0000")
|
||||
|
||||
check("translated NUL class is RE2-safe", isRE2Safe(NUL_CLASS_RE2))
|
||||
check("untranslated \\u0000 is not RE2-safe", !isRE2Safe(NUL_CLASS))
|
||||
check("lookahead path pattern is not RE2-safe even after translation",
|
||||
!isRE2Safe(translateUnicodeEscapes(PATH_LOOKAHEAD)))
|
||||
|
||||
check("plain ^[a-z]+$ is RE2-safe", isRE2Safe("^[a-z]+$"))
|
||||
check("non-capturing group and digits are RE2-safe", isRE2Safe("(?:foo){1,3}"))
|
||||
check("\\p{L} is RE2-safe", isRE2Safe("\\p{L}+"))
|
||||
check("named group (?P<name>) is RE2-safe", isRE2Safe("(?P<name>[a-z]+)"))
|
||||
check("JS named group (?<name>) is RE2-safe", isRE2Safe("(?<name>[a-z]+)"))
|
||||
check("flags group is RE2-safe", isRE2Safe("(?i)abc"))
|
||||
check("possessive *+ is not RE2-safe", !isRE2Safe("a*+"))
|
||||
check("lookahead is not RE2-safe", !isRE2Safe("(?=a)"))
|
||||
check("lookbehind is not RE2-safe", !isRE2Safe("(?<=a)"))
|
||||
check("backreference is not RE2-safe", !isRE2Safe("(a)\\1"))
|
||||
check("unclosed class is not RE2-safe", !isRE2Safe("[a-z"))
|
||||
check("trailing backslash is not RE2-safe", !isRE2Safe("abc\\"))
|
||||
|
||||
// Repeat bounds: RE2 rejects a count over 1000, min > max, and nested or leading repeats.
|
||||
check("repeat count 1000 is RE2-safe", isRE2Safe("^.{0,1000}$"))
|
||||
check("repeat count over 1000 is not RE2-safe", !isRE2Safe("^.{0,2000}$"))
|
||||
check("repeat count 1001 is not RE2-safe", !isRE2Safe("a{1001}"))
|
||||
check("open repeat with min over 1000 is not RE2-safe", !isRE2Safe("a{1001,}"))
|
||||
check("min greater than max is not RE2-safe", !isRE2Safe("a{3,2}"))
|
||||
check("nested repeats are not RE2-safe", !isRE2Safe("a{2}{3}"))
|
||||
check("leading bare {2} is not RE2-safe", !isRE2Safe("{2}"))
|
||||
check("a well-formed {2} after an atom is RE2-safe", isRE2Safe("a{2}"))
|
||||
check("grouped repeat product (a{1000}){2} is not RE2-safe", !isRE2Safe("(a{1000}){2}"))
|
||||
check("grouped repeat product (a{500}){3} is not RE2-safe", !isRE2Safe("(a{500}){3}"))
|
||||
check("grouped repeat product (a{32}){32} is not RE2-safe", !isRE2Safe("(a{32}){32}"))
|
||||
check("grouped repeat product (a{3}){333} is RE2-safe", isRE2Safe("(a{3}){333}"))
|
||||
check("grouped repeat product (a{3}){334} is not RE2-safe", !isRE2Safe("(a{3}){334}"))
|
||||
check("(a{1000}){1} does not trip the product limit", isRE2Safe("(a{1000}){1}"))
|
||||
check("(a{1000})+ is RE2-safe (star/plus are not product-checked)", isRE2Safe("(a{1000})+"))
|
||||
check("concat siblings are not multiplied: (a{10}b{10}){100}", isRE2Safe("(a{10}b{10}){100}"))
|
||||
check("concat siblings product (a{10}b{10}){101} is not RE2-safe", !isRE2Safe("(a{10}b{10}){101}"))
|
||||
check("alternation takes the heavier branch: (a{10}|b{20}){50}", isRE2Safe("(a{10}|b{20}){50}"))
|
||||
check("alternation product (a{10}|b{20}){51} is not RE2-safe", !isRE2Safe("(a{10}|b{20}){51}"))
|
||||
check("inverted class range [z-a] is not RE2-safe", !isRE2Safe("[z-a]"))
|
||||
check("ordinary class range [a-z] is RE2-safe", isRE2Safe("[a-z]"))
|
||||
check("[a-] trailing hyphen is RE2-safe", isRE2Safe("[a-]"))
|
||||
check("[a--] inverted range is not RE2-safe", !isRE2Safe("[a--]"))
|
||||
check("inverted hex range is not RE2-safe", !isRE2Safe("[\\x{5A}-\\x{41}]"))
|
||||
check("hex class range is RE2-safe", isRE2Safe("[\\x{41}-\\x{5A}]"))
|
||||
|
||||
// `[:` inside a class is a POSIX named class in Go's regexp, but literal
|
||||
// characters in JS. Drop every such pattern, including ones Go can compile.
|
||||
check("[^é[:alpha:] is not RE2-safe (POSIX class, missing closing ])", !isRE2Safe("[^é[:alpha:]"))
|
||||
check("[*?\\-[:alpha:] is not RE2-safe (POSIX class, missing closing ])", !isRE2Safe("[*?\\-[:alpha:]"))
|
||||
check("[[:alpha:]a-\\d is not RE2-safe (POSIX class, invalid escape)", !isRE2Safe("[[:alpha:]a-\\d"))
|
||||
check("[[:alpha:]] is not RE2-safe (would compile in Go but match differently)", !isRE2Safe("[[:alpha:]]"))
|
||||
check("[a-z] without a POSIX class stays RE2-safe", isRE2Safe("[a-z]"))
|
||||
{
|
||||
const dropped = sanitizePatternString("[^é[:alpha:]")
|
||||
check("sanitizePatternString drops a POSIX class inside a bracket",
|
||||
!dropped.ok && dropped.pattern === undefined, JSON.stringify(dropped))
|
||||
}
|
||||
|
||||
// Escapes RE2 does not take, inside or outside a class.
|
||||
check("[\\b] is not RE2-safe", !isRE2Safe("[\\b]"))
|
||||
check("[\\Qa] is not RE2-safe", !isRE2Safe("[\\Qa]"))
|
||||
check("\\é is not RE2-safe", !isRE2Safe("\\é"))
|
||||
check("\\b outside a class is RE2-safe", isRE2Safe("\\bword"))
|
||||
check("\\Q...\\E is dropped (RE2 quoting, not ECMA-262)", !isRE2Safe("\\Qabc\\E"))
|
||||
check("\\a is dropped (BEL in RE2, literal a in JS)", !isRE2Safe("\\a"))
|
||||
check("\\A is dropped (start-of-text in RE2, literal A in JS)", !isRE2Safe("\\A"))
|
||||
|
||||
// \\p names Go does not know, including the ECMA Script= form.
|
||||
check("\\p{Greek} is RE2-safe", isRE2Safe("\\p{Greek}"))
|
||||
check("\\p{Script=Greek} is not RE2-safe", !isRE2Safe("\\p{Script=Greek}"))
|
||||
check("unknown \\p name is not RE2-safe", !isRE2Safe("\\p{NotARealScript}"))
|
||||
check("\\p{^L} negation is RE2-safe", isRE2Safe("\\p{^L}"))
|
||||
|
||||
// Out-of-range code points.
|
||||
check("\\x{10FFFF} is RE2-safe", isRE2Safe("\\x{10FFFF}"))
|
||||
check("\\u{110000} is not RE2-safe after translation",
|
||||
!isRE2Safe(translateUnicodeEscapes("\\u{110000}")))
|
||||
check("translated \\x{110000} is not RE2-safe", !isRE2Safe("\\x{110000}"))
|
||||
|
||||
// Surrogate pairs must be joined into one code point.
|
||||
{
|
||||
const joined = translateUnicodeEscapes("\\uD83D\\uDE00")
|
||||
check("escaped surrogate pair joins into one code point",
|
||||
joined === "\\x{1F600}", joined)
|
||||
const literal = translateUnicodeEscapes("😀")
|
||||
check("literal emoji joins into one code point",
|
||||
literal === "\\x{1F600}", literal)
|
||||
check("joined emoji escape is RE2-safe", isRE2Safe(joined))
|
||||
check("joining is idempotent on \\x{1F600}",
|
||||
translateUnicodeEscapes("\\x{1F600}") === "\\x{1F600}")
|
||||
check("mixed escaped-high + raw-low surrogates join",
|
||||
translateUnicodeEscapes("\\uD83D" + String.fromCharCode(0xDE00)) === "\\x{1F600}")
|
||||
check("mixed raw-high + escaped-low surrogates join",
|
||||
translateUnicodeEscapes(String.fromCharCode(0xD83D) + "\\uDE00") === "\\x{1F600}")
|
||||
}
|
||||
|
||||
// \\z and \\S compile in RE2 but differ from JS; drop them into a hint.
|
||||
check("\\z is not treated as RE2-safe (JS vs RE2 semantics)", !isRE2Safe("\\z"))
|
||||
check("\\S is not treated as RE2-safe (JS vs RE2 semantics)", !isRE2Safe("\\S"))
|
||||
check("\\s stays RE2-safe", isRE2Safe("\\s+"))
|
||||
{
|
||||
const droppedZ = sanitizePatternString("end\\z")
|
||||
check("sanitizePatternString drops \\z into a failed result",
|
||||
!droppedZ.ok && droppedZ.pattern === undefined, JSON.stringify(droppedZ))
|
||||
const droppedS = sanitizePatternString("\\S+")
|
||||
check("sanitizePatternString drops \\S into a failed result",
|
||||
!droppedS.ok, JSON.stringify(droppedS))
|
||||
}
|
||||
|
||||
{
|
||||
const kept = sanitizePatternString(NUL_CLASS)
|
||||
check("sanitizePatternString keeps translated NUL class",
|
||||
kept.ok && kept.pattern === NUL_CLASS_RE2, JSON.stringify(kept))
|
||||
const dropped = sanitizePatternString(PATH_LOOKAHEAD)
|
||||
check("sanitizePatternString drops lookahead path pattern",
|
||||
!dropped.ok && dropped.pattern === undefined, JSON.stringify(dropped))
|
||||
const named = sanitizePatternString("(?<name>[a-z]+)")
|
||||
check("sanitizePatternString keeps (?<name>…)",
|
||||
named.ok && named.pattern === "(?<name>[a-z]+)", JSON.stringify(named))
|
||||
}
|
||||
|
||||
{
|
||||
const node = { type: "string", description: "a path", pattern: PATH_LOOKAHEAD }
|
||||
sanitizePatternFields(node)
|
||||
check("sanitizePatternFields drops invalid pattern and hints with the original",
|
||||
node.pattern === undefined && typeof node.description === "string"
|
||||
&& node.description.includes("pattern: ")
|
||||
&& node.description.includes("(?!/)")
|
||||
&& !node.description.includes("pattern: pattern:"),
|
||||
JSON.stringify(node))
|
||||
}
|
||||
|
||||
{
|
||||
const node = { type: "string", pattern: NUL_CLASS }
|
||||
sanitizePatternFields(node)
|
||||
check("sanitizePatternFields rewrites a translatable pattern in place",
|
||||
node.pattern === NUL_CLASS_RE2 && node.description === undefined,
|
||||
JSON.stringify(node))
|
||||
sanitizePatternFields(node)
|
||||
check("sanitizePatternFields is idempotent after a rewrite",
|
||||
node.pattern === NUL_CLASS_RE2 && node.description === undefined,
|
||||
JSON.stringify(node))
|
||||
}
|
||||
|
||||
{
|
||||
const node = {
|
||||
type: "object",
|
||||
patternProperties: {
|
||||
[NUL_CLASS]: { type: "string" },
|
||||
[PATH_LOOKAHEAD]: { type: "number" },
|
||||
},
|
||||
}
|
||||
sanitizePatternFields(node)
|
||||
check("patternProperties: translatable key is rewritten, invalid key is dropped",
|
||||
Object.keys(node.patternProperties).length === 1
|
||||
&& Object.hasOwn(node.patternProperties, NUL_CLASS_RE2)
|
||||
&& (node.description || "").includes("dropped patternProperties"),
|
||||
JSON.stringify(node))
|
||||
}
|
||||
|
||||
{
|
||||
const node = {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
patternProperties: {
|
||||
"^(?!x)": { type: "string" },
|
||||
},
|
||||
}
|
||||
sanitizePatternFields(node)
|
||||
check("dropping every patternProperties key does not leave additionalProperties:false (reject-all)",
|
||||
node.patternProperties === undefined
|
||||
&& node.additionalProperties !== false
|
||||
&& (node.description || "").includes("dropped patternProperties")
|
||||
&& (node.description || "").includes("additionalProperties:false was lifted"),
|
||||
JSON.stringify(node))
|
||||
}
|
||||
|
||||
{
|
||||
const schema = sanitizeInputSchema({
|
||||
type: "object",
|
||||
properties: {
|
||||
sourcePath: { type: "string", description: "source", pattern: NUL_CLASS },
|
||||
path: { type: "string", description: "unix path", pattern: PATH_LOOKAHEAD },
|
||||
nested: {
|
||||
type: "object",
|
||||
properties: {
|
||||
inner: { type: "string", pattern: NUL_CLASS },
|
||||
},
|
||||
},
|
||||
list: {
|
||||
type: "array",
|
||||
items: { type: "string", pattern: PATH_LOOKAHEAD },
|
||||
},
|
||||
either: {
|
||||
anyOf: [
|
||||
{ type: "string", pattern: NUL_CLASS },
|
||||
{ type: "string", pattern: PATH_LOOKAHEAD },
|
||||
],
|
||||
},
|
||||
},
|
||||
required: ["sourcePath"],
|
||||
})
|
||||
const source = schema.properties.sourcePath
|
||||
const pathNode = schema.properties.path
|
||||
const inner = schema.properties.nested.properties.inner
|
||||
const item = schema.properties.list.items
|
||||
const [okBranch, badBranch] = schema.properties.either.anyOf
|
||||
check("sanitizeInputSchema rewrites nested sourcePath",
|
||||
source.pattern === NUL_CLASS_RE2, JSON.stringify(source))
|
||||
check("sanitizeInputSchema drops nested lookahead path and hints",
|
||||
pathNode.pattern === undefined && /pattern: /.test(pathNode.description || ""),
|
||||
JSON.stringify(pathNode))
|
||||
check("sanitizeInputSchema rewrites items / anyOf / nested objects",
|
||||
inner.pattern === NUL_CLASS_RE2
|
||||
&& item.pattern === undefined
|
||||
&& okBranch.pattern === NUL_CLASS_RE2
|
||||
&& badBranch.pattern === undefined,
|
||||
JSON.stringify({ inner, item, okBranch, badBranch }))
|
||||
const again = sanitizeInputSchema(schema)
|
||||
check("sanitizeInputSchema is idempotent on an already-sanitized tree",
|
||||
JSON.stringify(again) === JSON.stringify(schema))
|
||||
}
|
||||
|
||||
// Recursion into propertyNames / contains / if/then/else / dependentSchemas / unevaluated*.
|
||||
{
|
||||
const schema = sanitizeInputSchema({
|
||||
type: "object",
|
||||
propertyNames: { type: "string", pattern: "^(?!x)" },
|
||||
if: { type: "string", pattern: "^(?!if)" },
|
||||
then: { type: "string", pattern: "^(?!then)" },
|
||||
else: { type: "string", pattern: "^(?!else)" },
|
||||
dependentSchemas: {
|
||||
flag: { type: "string", pattern: "^(?!dep)" },
|
||||
},
|
||||
unevaluatedProperties: { type: "string", pattern: "^(?!uP)" },
|
||||
properties: {
|
||||
list: {
|
||||
type: "array",
|
||||
contains: { type: "string", pattern: "^(?!y)" },
|
||||
unevaluatedItems: { type: "string", pattern: "^(?!uI)" },
|
||||
},
|
||||
},
|
||||
})
|
||||
const spots = [
|
||||
schema.propertyNames,
|
||||
schema.if,
|
||||
schema.then,
|
||||
schema.else,
|
||||
schema.dependentSchemas.flag,
|
||||
schema.unevaluatedProperties,
|
||||
schema.properties.list.contains,
|
||||
schema.properties.list.unevaluatedItems,
|
||||
]
|
||||
check("sanitizeInputSchema recurses into propertyNames/contains/if/then/else/dependentSchemas/unevaluated*",
|
||||
spots.every((node) => node && node.pattern === undefined && /pattern: /.test(node.description || "")),
|
||||
JSON.stringify(schema))
|
||||
}
|
||||
|
||||
// Existing sanitizer behaviour should still hold (enum / union / dangling required).
|
||||
{
|
||||
const schema = sanitizeInputSchema({
|
||||
type: "object",
|
||||
properties: {
|
||||
union_arr: { type: ["object", "array"], items: { type: "string" } },
|
||||
stale_items: { type: ["string", "number"], items: { type: "string" }, properties: { bad: { type: "string" } } },
|
||||
num_enum: { type: "integer", enum: [0, 1, 2] },
|
||||
},
|
||||
required: ["union_arr", "missing_field"],
|
||||
})
|
||||
check("existing union / stale / enum / required sanitizer still applies",
|
||||
schema.properties.union_arr.type === "array"
|
||||
&& schema.properties.stale_items.items === undefined
|
||||
&& schema.properties.stale_items.properties === undefined
|
||||
&& schema.properties.num_enum.enum === undefined
|
||||
&& /Allowed values: 0, 1, 2/.test(schema.properties.num_enum.description || "")
|
||||
&& JSON.stringify(schema.required) === JSON.stringify(["union_arr"]),
|
||||
JSON.stringify(schema))
|
||||
}
|
||||
|
||||
// Cross-check accepted patterns against Go's regexp.Compile when `go` is present.
|
||||
{
|
||||
const helper = fileURLToPath(new URL("./re2-compile.go", import.meta.url))
|
||||
const corpus = [
|
||||
"^[a-z]+$",
|
||||
"(?:foo){1,3}",
|
||||
"\\p{L}+",
|
||||
"\\p{Greek}",
|
||||
"(?P<name>[a-z]+)",
|
||||
"(?<name>[a-z]+)",
|
||||
"(?i)abc",
|
||||
"^.{0,1000}$",
|
||||
"a{2}",
|
||||
"a{0,}",
|
||||
"a{0002}",
|
||||
"\\bword",
|
||||
"\\s+",
|
||||
"(a{3}){333}",
|
||||
"(a{10}b{10}){100}",
|
||||
"[\\x{41}-\\x{5A}]",
|
||||
"\\x{10FFFF}",
|
||||
translateUnicodeEscapes("\\uD83D\\uDE00"),
|
||||
translateUnicodeEscapes(NUL_CLASS),
|
||||
"^😀$",
|
||||
]
|
||||
const rejected = [
|
||||
"^.{0,2000}$",
|
||||
"a{3,2}",
|
||||
"a{2}{3}",
|
||||
"{2}",
|
||||
"[\\b]",
|
||||
"[\\Qa]",
|
||||
"\\é",
|
||||
"\\p{Script=Greek}",
|
||||
"\\x{110000}",
|
||||
"a*+",
|
||||
"(?=a)",
|
||||
"(a)\\1",
|
||||
"(a{1000}){2}",
|
||||
"(a{32}){32}",
|
||||
"(a{10}b{10}){101}",
|
||||
"[z-a]",
|
||||
"[a--]",
|
||||
"[\\x{5A}-\\x{41}]",
|
||||
"[^é[:alpha:]",
|
||||
"[*?\\-[:alpha:]",
|
||||
"[[:alpha:]a-\\d",
|
||||
]
|
||||
const input = [
|
||||
...corpus.map((pattern) => JSON.stringify({ pattern })),
|
||||
JSON.stringify({ pattern: "\\x{1F600}", input: "😀" }),
|
||||
JSON.stringify({ pattern: "\\x{D83D}\\x{DE00}", input: "😀" }),
|
||||
...rejected.map((pattern) => JSON.stringify({ pattern })),
|
||||
].join("\n") + "\n"
|
||||
const result = spawnSync("go", ["run", helper], {
|
||||
input,
|
||||
encoding: "utf8",
|
||||
cwd: path.dirname(helper),
|
||||
timeout: 60_000,
|
||||
})
|
||||
if (result.error && result.error.code === "ENOENT") {
|
||||
// Keep this visible: a silent pass hid a missing toolchain.
|
||||
console.log("skip Go regexp cross-check (go not on PATH)")
|
||||
} else if (result.status !== 0) {
|
||||
check("Go regexp cross-check runner", false, (result.stderr || result.stdout || result.error)?.toString())
|
||||
} else {
|
||||
const rows = result.stdout.trim().split("\n").map((line) => JSON.parse(line))
|
||||
const byPattern = new Map(rows.filter((row) => !("match" in row) || row.input === undefined).map((row) => [row.pattern, row]))
|
||||
// The first corpus.length rows correspond to corpus (no input).
|
||||
const compiled = rows.slice(0, corpus.length)
|
||||
const joinMatch = rows.find((row) => row.pattern === "\\x{1F600}" && row.input === "😀")
|
||||
const splitMatch = rows.find((row) => row.pattern === "\\x{D83D}\\x{DE00}" && row.input === "😀")
|
||||
const rejectedRows = rows.slice(-rejected.length)
|
||||
check("every pattern isRE2Safe accepts is compiled by Go regexp",
|
||||
compiled.every((row) => row.ok) && compiled.length === corpus.length,
|
||||
JSON.stringify(compiled.filter((row) => !row.ok)))
|
||||
check("isRE2Safe is not true for any Go-rejected review case",
|
||||
rejected.every((pattern, i) => !isRE2Safe(pattern) && rejectedRows[i] && rejectedRows[i].ok === false),
|
||||
JSON.stringify(rejectedRows))
|
||||
check("Go matches 😀 against the joined \\x{1F600}",
|
||||
joinMatch && joinMatch.ok && joinMatch.match === true, JSON.stringify(joinMatch))
|
||||
check("Go does not match 😀 against split surrogate escapes",
|
||||
splitMatch && splitMatch.ok && splitMatch.match === false, JSON.stringify(splitMatch))
|
||||
void byPattern
|
||||
}
|
||||
}
|
||||
|
||||
if (failed) {
|
||||
console.error(`\n${failed} check(s) failed`)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log("\nALL OK")
|
||||
@@ -1,8 +1,8 @@
|
||||
// magpie-agy 插件的受控加载夹具(仅供仓内 test-catalog / test-usage-settlement /
|
||||
// test-repeat-batch 使用)。源自 configs 仓 scripts/continuity/tests/agy_bridge_testkit.mjs。
|
||||
//
|
||||
// 用 vm.SourceTextModule 在当前上下文里加载**真实**仓内 index.mjs,相对的 ./usage.mjs
|
||||
// 与 ./platform.mjs 链接到同目录的真实文件;生产文件只读,不落盘任何副本。
|
||||
// 用 vm.SourceTextModule 在当前上下文里加载**真实**仓内 index.mjs,相对的 ./usage.mjs、
|
||||
// ./platform.mjs、./login.mjs 与 ./re2-pattern.mjs 链接到同目录的真实文件;生产文件只读,不落盘任何副本。
|
||||
// 边界替身:
|
||||
// - node:child_process 的 spawn:`agy models` 与 `agy acp` 都换成进程内假子进程,
|
||||
// 后者讲真实 ACP JSON-RPC(initialize / session/new / set_model / prompt / cancel)。
|
||||
@@ -32,6 +32,7 @@ export const INDEX_FILE = process.env.AGY_BRIDGE_TEST_INDEX || path.join(REPO_DI
|
||||
export const USAGE_FILE = path.join(REPO_DIR, "usage.mjs")
|
||||
export const PLATFORM_FILE = path.join(REPO_DIR, "platform.mjs")
|
||||
export const LOGIN_FILE = path.join(REPO_DIR, "login.mjs")
|
||||
export const RE2_PATTERN_FILE = path.join(REPO_DIR, "re2-pattern.mjs")
|
||||
export const MESSAGES_URL = "agy://local/v1/messages"
|
||||
export const COUNT_TOKENS_URL = "agy://local/v1/messages/count_tokens"
|
||||
export const CATALOG_TTL_MS = 5 * 60 * 1000
|
||||
@@ -487,6 +488,7 @@ export async function createBridgeKit(options = {}) {
|
||||
const usageUrl = pathToFileURL(USAGE_FILE).href
|
||||
const platformUrl = pathToFileURL(PLATFORM_FILE).href
|
||||
const loginUrl = pathToFileURL(LOGIN_FILE).href
|
||||
const re2Url = pathToFileURL(RE2_PATTERN_FILE).href
|
||||
const linker = (specifier) => {
|
||||
const key = specifier.startsWith("node:") || specifier.startsWith("./") || specifier === RUNTIME_SPECIFIER
|
||||
? specifier
|
||||
@@ -496,6 +498,7 @@ export async function createBridgeKit(options = {}) {
|
||||
if (key === "./usage.mjs") module = sourceModule(USAGE_FILE, "", usageUrl)
|
||||
else if (key === "./platform.mjs") module = sourceModule(PLATFORM_FILE, "", platformUrl)
|
||||
else if (key === "./login.mjs") module = sourceModule(LOGIN_FILE, "", loginUrl)
|
||||
else if (key === "./re2-pattern.mjs") module = sourceModule(RE2_PATTERN_FILE, "", re2Url)
|
||||
else if (key.startsWith("node:")) module = builtinModule(key, overrides[key])
|
||||
else throw new Error(`testkit: 未登记的依赖 ${specifier}`)
|
||||
cache.set(key, module)
|
||||
|
||||
Reference in New Issue
Block a user