Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
Preserve Artifact regex restrictions in shared Claude conversions (#1772)
Ali Khokhar39b9c272a5db
diff --git a/e2e/test_tool_schema_patterns.py b/e2e/test_tool_schema_patterns.pynew file mode 100644index 00000000..2a2bcff8--- /dev/null+++ b/e2e/test_tool_schema_patterns.py@@ -0,0 +1,49 @@+"""Compare emitted regexes with the client's JavaScript Unicode semantics."""++import unicodedata++from free_claude_code.core.tool_schema_patterns import translate_tool_schema_patterns+from tests.core.test_tool_schema_patterns import ARTIFACT_PATTERN+++def test_artifact_pattern_matches_javascript_reference(page):+ converted = translate_tool_schema_patterns({"pattern": ARTIFACT_PATTERN})["pattern"]+ samples = [+ "",+ "demo",+ "é名字😀",+ "__name__",+ "__name",+ "name__",+ "-name-",+ "a" * 200,+ "a" * 201,+ *["x" + char + "y" for char in r'"\/.[]'],+ *[+ chr(point)+ for point in range(0x110000)+ if unicodedata.category(chr(point)) in {"Cc", "Cf", "Zl", "Zp"}+ ],+ "\U000110bc",+ "\U000110be",+ "\U000e0000",+ "\U000e0080",+ ]+ mismatches = page.evaluate(+ """({original, converted, samples}) => {+ const before = new RegExp(original, 'u');+ const after = new RegExp(converted, 'u');+ const mismatches = samples.filter(text => before.test(text) !== after.test(text));+ for (let point = 0; point < 0x110000; point++) {+ if (point >= 0xD800 && point <= 0xDFFF) continue;+ const text = String.fromCodePoint(point);+ if (before.test(text) !== after.test(text)) {+ mismatches.push(`U+${point.toString(16)}`);+ if (mismatches.length >= 10) break;+ }+ }+ return mismatches;+ }""",+ {"original": ARTIFACT_PATTERN, "converted": converted, "samples": samples},+ )+ assert mismatches == [], f"Unicode {unicodedata.unidata_version}: {mismatches!r}"diff --git a/pyproject.toml b/pyproject.tomlindex 3c9cbfe3..67266d78 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "6.2.15"+version = "6.2.16"description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"diff --git a/src/free_claude_code/core/anthropic/conversion.py b/src/free_claude_code/core/anthropic/conversion.pyindex f232cd8f..0091fe8b 100644--- a/src/free_claude_code/core/anthropic/conversion.py+++ b/src/free_claude_code/core/anthropic/conversion.py@@ -22,6 +22,7 @@ from free_claude_code.core.openai_chat import (close_chat_tool_result_turns,image_tool_result_label,)+from free_claude_code.core.tool_schema_patterns import translate_tool_schema_patternsfrom .content import get_block_attr, get_block_typefrom .image_sources import AnthropicImageSourceError, portable_anthropic_image_url@@ -786,7 +787,9 @@ class AnthropicToOpenAIConverter:"function": {"name": tool.name,"description": tool.description or "",- "parameters": _tool_input_schema(tool),+ "parameters": translate_tool_schema_patterns(+ _tool_input_schema(tool)+ ),},}for tool in toolsdiff --git a/src/free_claude_code/core/openai_responses/provider_input.py b/src/free_claude_code/core/openai_responses/provider_input.pyindex 35bb3f31..d6d11396 100644--- a/src/free_claude_code/core/openai_responses/provider_input.py+++ b/src/free_claude_code/core/openai_responses/provider_input.py@@ -31,6 +31,7 @@ from free_claude_code.core.history_replay import (from free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_tool_names import OpenAIToolNameCodecfrom free_claude_code.core.reasoning import ReasoningPolicy+from free_claude_code.core.tool_schema_patterns import translate_tool_schema_patternsfrom .errors import ResponsesConversionErrorfrom .reasoning import responses_reasoning_config@@ -91,7 +92,9 @@ def build_responses_provider_request("type": "function","name": tool_names.encode(tool.name),"description": tool.description,- "parameters": tool.input_schema or {"type": "object", "properties": {}},+ "parameters": translate_tool_schema_patterns(+ tool.input_schema or {"type": "object", "properties": {}}+ ),"strict": False,}for tool in request.toolsdiff --git a/src/free_claude_code/core/tool_schema_patterns.py b/src/free_claude_code/core/tool_schema_patterns.pynew file mode 100644index 00000000..5ce07bbc--- /dev/null+++ b/src/free_claude_code/core/tool_schema_patterns.py@@ -0,0 +1,168 @@+"""Portable Unicode exclusions for Claude tool parameter schemas."""++import re+import unicodedata+from functools import cache+from typing import Any++_CATEGORIES = frozenset({"Cc", "Cf", "Zl", "Zp"})+_SCHEMA_MAP_KEYS = frozenset(+ {+ "$defs",+ "definitions",+ "properties",+ "patternProperties",+ "dependentSchemas",+ "dependencies",+ }+)+_SCHEMA_KEYS = frozenset(+ {+ "additionalProperties",+ "additionalItems",+ "unevaluatedProperties",+ "unevaluatedItems",+ "items",+ "contains",+ "propertyNames",+ "if",+ "then",+ "else",+ "not",+ "contentSchema",+ "allOf",+ "anyOf",+ "oneOf",+ "prefixItems",+ }+)+++def translate_tool_schema_patterns(schema: Any) -> Any:+ """Copy changed schema paths only; instance data and unsupported regexes pass through."""+ if isinstance(schema, list):+ items = [translate_tool_schema_patterns(item) for item in schema]+ return (+ items+ if any(a is not b for a, b in zip(items, schema, strict=True))+ else schema+ )+ if not isinstance(schema, dict):+ return schema+ result = {}+ changed = False+ for key, value in schema.items():+ replacement = value+ if key == "pattern" and isinstance(value, str):+ replacement = _translate_pattern(value)+ elif key in _SCHEMA_MAP_KEYS and isinstance(value, dict):+ mapped = {+ name: translate_tool_schema_patterns(child)+ for name, child in value.items()+ }+ if any(mapped[name] is not child for name, child in value.items()):+ replacement = mapped+ elif key in _SCHEMA_KEYS:+ replacement = translate_tool_schema_patterns(value)+ result[key] = replacement+ changed |= replacement is not value+ return result if changed else schema+++def _translate_pattern(pattern: str) -> str:+ # A bounded scanner for four standalone atoms in ordinary negated classes,+ # not a general regex transpiler. Never partially translate unsupported input.+ if r"\p{" not in pattern:+ return pattern+ replacements: list[tuple[int, int, str]] = []+ in_class = False+ negated = False+ previous = ""+ index = 0+ while index < len(pattern):+ char = pattern[index]+ if char == "\\":+ if index + 1 == len(pattern):+ return pattern+ if pattern[index + 1] in "pP":+ end = pattern.find("}", index + 3)+ category = pattern[index + 3 : end]+ if (+ not pattern.startswith(r"\p{", index)+ or end == -1+ or category not in _CATEGORIES+ or not in_class+ or not negated+ or previous == "-"+ or pattern[end + 1 : end + 2] == "-"+ ):+ return pattern+ replacements.append((index, end + 1, category))+ previous = pattern[index : end + 1]+ index = end + 1+ continue+ previous = pattern[index : index + 2]+ index += 2+ continue+ if char == "[":+ if in_class:+ # Artifact's ordinary class includes a literal '[' before '\]'.+ # Other nested forms may be Unicode set syntax; leave them alone.+ if not pattern.startswith(r"[\]]", index):+ return pattern+ else:+ in_class = True+ negated = pattern[index + 1 : index + 2] == "^"+ elif char == "]":+ if not in_class:+ return pattern+ in_class = False+ elif in_class and pattern[index : index + 2] in {"&&", "--", "~~", "||"}:+ return pattern+ previous = char+ index += 1+ if in_class or not replacements:+ return pattern+ ranges = _category_ranges()+ parts = []+ offset = 0+ for start, end, category in replacements:+ parts.extend((pattern[offset:start], ranges[category]))+ offset = end+ parts.append(pattern[offset:])+ translated = "".join(parts)+ try:+ re.compile(translated)+ except re.error, OverflowError, RecursionError:+ return pattern+ return translated+++@cache+def _category_ranges() -> dict[str, str]:+ """Build the four finite tables lazily, using Python's Unicode database."""+ ranges: dict[str, list[tuple[int, int]]] = {key: [] for key in _CATEGORIES}+ for point in range(0x110000):+ category = unicodedata.category(chr(point))+ if category not in ranges:+ continue+ spans = ranges[category]+ if spans and spans[-1][1] == point - 1:+ spans[-1] = (spans[-1][0], point)+ else:+ spans.append((point, point))+ return {+ category: "".join(+ _codepoint(start)+ if start == end+ else f"{_codepoint(start)}-{_codepoint(end)}"+ for start, end in spans+ )+ for category, spans in ranges.items()+ }+++def _codepoint(point: int) -> str:+ # Actual astral scalars work in JS Unicode mode and Python. Surrogate ranges+ # would change the exclusion; \U and \u{...} escapes are dialect-specific.+ return f"\\u{point:04X}" if point <= 0xFFFF else chr(point)diff --git a/tests/core/test_tool_schema_patterns.py b/tests/core/test_tool_schema_patterns.pynew file mode 100644index 00000000..127cc468--- /dev/null+++ b/tests/core/test_tool_schema_patterns.py@@ -0,0 +1,280 @@+"""Regressions for issue #1730 at the shared Claude conversion boundary."""++import re+import unicodedata+from copy import deepcopy++import pytest++from free_claude_code.core.anthropic.conversion import build_base_request_body+from free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.openai_responses.provider_input import (+ build_responses_provider_request,+)+from free_claude_code.core.reasoning import ReasoningPolicy+from free_claude_code.core.tool_schema_patterns import translate_tool_schema_patterns++ARTIFACT_PATTERN = r'^(?!__.*__$)[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}"\\./[\]]{1,200}$'++[email protected]("wire_format", ["chat", "responses"])+ "pattern", [r"^[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}]{1,200}$", ARTIFACT_PATTERN]+)+def test_claude_converters_preserve_artifact_rules_in_portable_pattern(+ wire_format, pattern+):+ schema = {+ "type": "object",+ "properties": {"name": {"type": "string", "pattern": pattern}},+ "required": ["name"],+ }+ request = MessagesRequest.model_validate(+ {+ "model": "test-model",+ "messages": [{"role": "user", "content": "Call Artifact with demo"}],+ "tools": [+ {"name": "Artifact", "description": "Save", "input_schema": schema}+ ],+ }+ )+ original = deepcopy(request.model_dump())+ if wire_format == "chat":+ body = build_base_request_body(request)+ parameters = body["tools"][0]["function"]["parameters"]+ else:+ body = build_responses_provider_request(+ request, reasoning=ReasoningPolicy.provider_default()+ )+ parameters = body["tools"][0]["parameters"]+ translated = parameters["properties"]["name"]["pattern"]+ assert r"\p{" not in translated+ regex = re.compile(translated)+ assert regex.fullmatch("demo")+ assert not regex.fullmatch("bad\u2028name")+ assert not regex.fullmatch("bad\U000e0001name")+ assert not regex.fullmatch("a" * 201)+ assert not regex.fullmatch("")+ assert parameters["required"] == ["name"]+ assert request.model_dump() == original+++def translated_pattern(pattern):+ return translate_tool_schema_patterns({"pattern": pattern})["pattern"]++[email protected]("wire_format", ["chat", "responses"])+ "pattern",+ [r"^[^\p{Cc}]{4294967296}$", "(" * 500 + r"[^\p{Cc}]" + ")" * 500],+ ids=["repeat-overflow", "group-recursion"],+)+def test_compiler_limits_preserve_original_schema_in_both_converters(+ wire_format, pattern+):+ schema = {"type": "string", "pattern": pattern}+ request = MessagesRequest.model_validate(+ {+ "model": "test-model",+ "messages": [{"role": "user", "content": "Test schema passthrough"}],+ "tools": [{"name": "Artifact", "input_schema": schema}],+ }+ )+ original = deepcopy(request.model_dump())+ if wire_format == "chat":+ parameters = build_base_request_body(request)["tools"][0]["function"][+ "parameters"+ ]+ else:+ body = build_responses_provider_request(+ request, reasoning=ReasoningPolicy.provider_default()+ )+ parameters = body["tools"][0]["parameters"]+ assert parameters == schema+ assert request.model_dump() == original++[email protected]("category", ["Cc", "Cf", "Zl", "Zp"])+def test_category_expansion_preserves_every_unicode_scalar(category):+ regex = re.compile(translated_pattern(r"[^\p{" + category + "}]+"))+ for point in range(0x110000):+ if 0xD800 <= point <= 0xDFFF:+ continue+ char = chr(point)+ assert bool(regex.fullmatch(char)) == (+ unicodedata.category(char) != category+ ), f"U+{point:04X}, category {category}, Unicode {unicodedata.unidata_version}"+++ "name,accepted",+ [+ ("demo", True),+ ("é名字😀", True),+ ("__name", True),+ ("name__", True),+ ("-name-", True),+ ("a", True),+ ("a" * 200, True),+ ("", False),+ ("a" * 201, False),+ ("__name__", False),+ *[("x" + char + "y", False) for char in r'"\/.[]'],+ *[+ ("x" + char + "y", False)+ for char in [+ "\x00",+ "\x1f",+ "\x7f",+ "\x9f",+ "\u200d",+ "\u2028",+ "\u2029",+ "\U000110bd",+ "\U000e0001",+ "\U000e0020",+ "\U000e007f",+ ]+ ],+ ],+)+def test_artifact_restrictions_survive_translation(name, accepted):+ assert bool(re.fullmatch(translated_pattern(ARTIFACT_PATTERN), name)) == accepted+++ "pattern",+ [+ r"^[a-z]+$",+ r"[^\\p{Cc}]",+ r"\\p{Cc}",+ r"[\p{Cc}]",+ r"\p{Cc}",+ r"[^\P{Cc}]",+ r"[^\p{L}]",+ r"[^\p{cc}]",+ r"[^\p{Cc}\p{L}]",+ r"[^\p{Cc}]\P{Cf}",+ r"[^\p{Cc}]\p{Cf}",+ r"[^\p{Cc}\p{General_Category=Format}]",+ r"[^\p{Cc}\p{Cf]",+ r"[^\p{Cc}",+ r"[^\p{Cc}]" + "\\",+ r"([^\p{Cc}]",+ r"[^\p{Cc}-z]",+ r"[^a-\p{Cc}]",+ r"[^\p{Cc}--a]",+ r"[^\p{Cc}&&a]",+ r"[^\p{Cc}~~a]",+ r"[^\p{Cc}||a]",+ r"[^\p{Cc}[a]]",+ r"\[^\p{Cc}]",+ ],+)+def test_unsupported_or_literal_patterns_remain_unchanged(pattern):+ schema = {"type": "string", "pattern": pattern}+ assert translate_tool_schema_patterns(schema) is schema+++ "pattern,excluded,accepted",+ [+ (r"[^\\\p{Cc}]", "\\\x00", "p{}C"),+ (r"[^\p{Cc}\-]", "-\x00", "az"),+ (r"[^\]\p{Cc}]", "]\x00", "["),+ (r"[^\p{Cc}[\]]", "[]\x00", "az"),+ (r"[^\p{Zl}][^\p{Zp}]", "\u2028x", "ab"),+ ],+)+def test_class_escaping_is_preserved(pattern, excluded, accepted):+ translated = translated_pattern(pattern)+ assert translated != pattern+ regex = re.compile(translated)+ if pattern == r"[^\p{Zl}][^\p{Zp}]":+ assert regex.fullmatch(accepted)+ assert not regex.fullmatch(excluded)+ else:+ assert all(not regex.fullmatch(char) for char in excluded)+ assert all(regex.fullmatch(char) for char in accepted)+++ "container",+ [+ "$defs",+ "definitions",+ "properties",+ "patternProperties",+ "dependentSchemas",+ "dependencies",+ ],+)+def test_schema_maps_visit_values_and_preserve_names(container):+ child = {"type": "string", "pattern": r"[^\p{Cc}]"}+ schema = {container: {"pattern": child, r"\p{Cc}": True, "required": ["name"]}}+ original = deepcopy(schema)+ converted = translate_tool_schema_patterns(schema)+ assert converted[container]["pattern"]["pattern"] != child["pattern"]+ assert converted[container][r"\p{Cc}"] is True+ assert converted[container]["required"] == ["name"]+ assert schema == original+++ "keyword",+ [+ "additionalProperties",+ "additionalItems",+ "unevaluatedProperties",+ "unevaluatedItems",+ "items",+ "contains",+ "propertyNames",+ "if",+ "then",+ "else",+ "not",+ "contentSchema",+ ],+)+def test_single_schema_keywords_are_translated(keyword):+ schema = {keyword: {"pattern": r"[^\p{Cf}]"}}+ converted = translate_tool_schema_patterns(schema)+ assert converted[keyword]["pattern"] != schema[keyword]["pattern"]++[email protected]("keyword", ["allOf", "anyOf", "oneOf", "prefixItems", "items"])+def test_schema_arrays_preserve_boolean_and_unchanged_children(keyword):+ child = {"type": "string", "pattern": r"[a-z]"}+ schema = {keyword: [child, False, {"pattern": r"[^\p{Cf}]"}]}+ converted = translate_tool_schema_patterns(schema)+ assert converted[keyword][0] is child+ assert converted[keyword][1] is False+ assert converted[keyword][2]["pattern"] != r"[^\p{Cf}]"+++def test_instance_data_is_untouched_and_translation_is_idempotent():+ literal = {"pattern": r"[^\p{Cc}]"}+ schema = {+ "type": "object",+ "properties": {"name": literal},+ "default": literal,+ "const": literal,+ "enum": [literal],+ "examples": [literal],+ "x-custom": literal,+ "description": r"\p{Cc}",+ }+ before = deepcopy(schema)+ converted = translate_tool_schema_patterns(schema)+ for key in ("default", "const", "enum", "examples", "x-custom", "description"):+ assert converted[key] is schema[key]+ assert schema == before+ assert translate_tool_schema_patterns(converted) is converted+++ "schema", [True, False, {}, {"pattern": 123}, {"type": "string"}]+)+def test_non_patterns_remain_unchanged(schema):+ assert translate_tool_schema_patterns(schema) is schemadiff --git a/tests/providers/test_openai_responses_transport.py b/tests/providers/test_openai_responses_transport.pyindex 93afe39e..2247c4ef 100644--- a/tests/providers/test_openai_responses_transport.py+++ b/tests/providers/test_openai_responses_transport.py@@ -2,6 +2,7 @@import asyncioimport json+import refrom collections.abc import Callable, Mappingimport httpx2@@ -1148,3 +1149,48 @@ async def test_preflight_rejects_fields_responses_cannot_represent() -> None:transport.preflight_messages(request, reasoning=REASONING_ON)finally:await client.close()+++async def test_claude_artifact_pattern_is_portable_on_the_sdk_wire():+ captured = []++ def handler(request):+ body = json.loads(request.content)+ captured.append(body)+ return httpx2.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ text=_sse(_text_delta("ok"), _completed_event()),+ )++ pattern = r"^[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}]{1,200}$"+ request = _request(+ tools=[+ {+ "name": "Artifact",+ "description": "Test artifact",+ "input_schema": {+ "type": "object",+ "properties": {+ "name": {"type": "string", "pattern": pattern},+ "slug": {"type": "string", "pattern": "^[a-z]+$"},+ },+ },+ }+ ]+ )+ client = _client(handler)+ try:+ await _collect(_transport(client), request)+ finally:+ await client.close()+ assert len(captured) == 1+ properties = captured[0]["tools"][0]["parameters"]["properties"]+ assert properties["slug"]["pattern"] == "^[a-z]+$"+ regex = re.compile(properties["name"]["pattern"])+ assert regex.fullmatch("demo")+ assert not regex.fullmatch("bad\U000e0001name")+ assert request.tools is not None+ assert request.tools[0].input_schema is not None+ assert request.tools[0].input_schema["properties"]["name"]["pattern"] == patterndiff --git a/uv.lock b/uv.lockindex d4dd1907..3cb86639 100644--- a/uv.lock+++ b/uv.lock@@ -598,7 +598,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "6.2.15"+version = "6.2.16"source = { editable = "." }dependencies = [{ name = "aiohttp" },