phosphor-harness 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,7 @@ from pathlib import Path
11
11
  import secrets
12
12
  import sys
13
13
  from unittest.mock import patch
14
+ from uuid import UUID
14
15
 
15
16
  from .terminal_input import terminal_with_spoken_input
16
17
 
@@ -34,12 +35,14 @@ def read_token(path: Path, *, create: bool = False) -> str:
34
35
 
35
36
  def make_app(checkout: Path, state: Path, workspace: Path, *, enable_camera: bool,
36
37
  camera_devices: tuple[str, ...] = (), helper_url: str | None = None,
37
- episodic_memory: bool = False, host_cameras=None):
38
+ episodic_memory: bool = False, episodic_root: Path | None = None,
39
+ episodic_embeddings_cpu: bool = False, host_cameras=None):
38
40
  sys.path.insert(0, str(checkout))
39
41
  sys.path.insert(0, str(checkout / "src"))
40
42
  from flask import abort, jsonify, request
41
43
  from portal.app import PortalConfig, create_app
42
44
  from portal.documents import DocumentError, MAX_DOCUMENT_BYTES, SessionDocumentStore
45
+ from portal.episodic_memory import MemoryCapture
43
46
  from portal.terminals import TerminalError, TerminalStore
44
47
  from portal.tools import SessionLocationStore, SessionWorkspaceStore, ToolInputError
45
48
 
@@ -53,6 +56,7 @@ def make_app(checkout: Path, state: Path, workspace: Path, *, enable_camera: boo
53
56
  tool_workspace_root=workspace, file_delivery_roots=(workspace,),
54
57
  file_delivery_root=state / "deliveries", mcp_enabled=True, mcp_root=state / "mcp",
55
58
  session_log_dir=state / "diagnostics", episodic_memory_enabled=episodic_memory,
59
+ episodic_memory_root=episodic_root,
56
60
  )
57
61
  documents = SessionDocumentStore(ttl_s=profile.session_log_ttl_s)
58
62
  session_workspace = SessionWorkspaceStore(ttl_s=profile.session_log_ttl_s)
@@ -94,13 +98,49 @@ def make_app(checkout: Path, state: Path, workspace: Path, *, enable_camera: boo
94
98
  ):
95
99
  app = create_app(profile, host_cameras=host_cameras)
96
100
  owner = hashlib.sha256(b"omni-voice-session\0" + token.encode()).hexdigest()
101
+ memory = app.extensions.get("episodic_memory")
102
+ if memory is not None:
103
+ search_hybrid = memory.search
104
+
105
+ def search_recall(session_id, query, **filters):
106
+ result = search_hybrid(session_id, query, **filters)
107
+ scope = memory._scope(memory._key(session_id), create=False)
108
+ if scope is None or not query.strip():
109
+ return result
110
+ with scope.lock:
111
+ exact = scope.store.search(query, **filters)["results"] if not scope.closed else []
112
+ matches = [row for row in exact if "lexical" in row.get("channels", ())][:2]
113
+ priority_ids = {row["event_id"] for row in matches}
114
+ rest = [row for row in result["results"] if row["event_id"] not in priority_ids]
115
+ return {**result, "results": (matches + rest)[:filters.get("limit", 8)]}
116
+
117
+ memory.search = search_recall
118
+ if memory is not None and episodic_embeddings_cpu:
119
+ from httpx import Client
120
+
121
+ def embed(text):
122
+ # Leave enough unified memory for the resident voice models.
123
+ with Path("/proc/meminfo").open() as meminfo:
124
+ available = next((int(line.split()[1]) for line in meminfo if line.startswith("MemAvailable:")), 0)
125
+ if available < 3_300_000:
126
+ return None
127
+ with Client(base_url="http://127.0.0.1:11434", timeout=4, trust_env=False) as client:
128
+ response = client.post("/api/embeddings", json={
129
+ "model": os.environ.get("OMNI_MEMORY_EMBED_MODEL", "nomic-embed-text"),
130
+ "prompt": text[:4000], "keep_alive": 0, "options": {"num_gpu": 0},
131
+ })
132
+ response.raise_for_status()
133
+ vector = response.json().get("embedding")
134
+ return vector if isinstance(vector, list) and vector else None
135
+
136
+ memory.embed = embed
97
137
 
98
138
  @app.before_request
99
139
  def only_tool_routes():
100
140
  path = request.path
101
141
  if path not in {"/api/tools", "/api/status", "/api/voice/camera-qr",
102
142
  "/api/harness/attachments", "/api/harness/location", "/api/harness/camera",
103
- "/api/harness/terminal-password"} and not path.startswith(
143
+ "/api/harness/terminal-password", "/api/harness/memory"} and not path.startswith(
104
144
  ("/api/tools/", "/api/mcp/servers", "/api/files/")
105
145
  ):
106
146
  abort(404)
@@ -152,6 +192,45 @@ def make_app(checkout: Path, state: Path, workspace: Path, *, enable_camera: boo
152
192
  if not hmac.compare_digest(request.cookies.get("omni_portal_session", ""), owner):
153
193
  abort(403)
154
194
 
195
+ @app.get("/api/harness/memory")
196
+ def voice_memory_status():
197
+ require_voice_session()
198
+ if memory is None:
199
+ return jsonify({"enabled": False})
200
+ snapshot = memory.snapshot(owner)["device"]
201
+ return jsonify({"enabled": True, "cpu_embeddings": episodic_embeddings_cpu, **{
202
+ name: int(snapshot.get(name, 0)) for name in ("events", "episodes", "facts", "vectors", "pending")
203
+ }})
204
+
205
+ @app.post("/api/harness/memory")
206
+ def remember_voice_turn():
207
+ require_voice_session()
208
+ if memory is None:
209
+ return jsonify({"enabled": False}), 503
210
+ if not request.content_length or request.content_length > 262_144:
211
+ abort(400)
212
+ data = request.get_json(silent=True)
213
+ if not isinstance(data, dict) or set(data) != {"id", "transcript", "reply", "tools"}:
214
+ abort(400)
215
+ try:
216
+ episode = str(UUID(data["id"]))
217
+ except (AttributeError, TypeError, ValueError):
218
+ abort(400)
219
+ words, reply, calls = data["transcript"], data["reply"], data["tools"]
220
+ if (not isinstance(words, str) or not 0 < len(words.strip()) <= 16_384
221
+ or not isinstance(reply, str) or len(reply) > 18_000 or not isinstance(calls, list) or len(calls) > 32
222
+ or any(not isinstance(call, dict) or set(call) != {"name", "ok"}
223
+ or not isinstance(call["name"], str) or not 1 <= len(call["name"]) <= 128
224
+ or type(call["ok"]) is not bool for call in calls)):
225
+ abort(400)
226
+ capture = MemoryCapture(memory, owner, episode, live_turn=True, media={"has_audio_input": True})
227
+ capture.observation({"transcript": words, "speech_addressee": "SELF"})
228
+ for call in calls:
229
+ capture.tool(call["name"], {}, ok=call["ok"])
230
+ capture.response({"message": {"content": reply},
231
+ "adapter": {"speech_synthesized": bool(reply), "speech_addressee": "SELF"}})
232
+ return jsonify({"recorded": True}), 201
233
+
155
234
  @app.post("/api/harness/terminal-password")
156
235
  def send_terminal_password():
157
236
  require_voice_session()
@@ -210,17 +289,22 @@ def main() -> None:
210
289
  parser.add_argument("--camera", action="store_true", help="Enable on-demand local camera stills")
211
290
  parser.add_argument("--camera-device", action="append", default=[], help="Restrict capture to the given device")
212
291
  parser.add_argument("--episodic-memory", action="store_true", help="Enable the adapter's configured memory service")
292
+ parser.add_argument("--episodic-memory-root", type=Path, help="Reuse the local adapter's episodic memory store")
293
+ parser.add_argument("--episodic-embeddings-cpu", action="store_true", help="Use the local Ollama CPU embedding worker for recall")
213
294
  parser.add_argument("--helper-url", help="Optional operator-configured Ollama-style text endpoint")
214
295
  args = parser.parse_args()
215
296
  if args.camera_device and not args.camera:
216
297
  parser.error("--camera-device requires --camera")
298
+ if (args.episodic_memory_root or args.episodic_embeddings_cpu) and not args.episodic_memory:
299
+ parser.error("episodic memory settings require --episodic-memory")
217
300
  os.umask(0o077)
218
301
  state = args.state.resolve()
219
302
  state.mkdir(parents=True, exist_ok=True, mode=0o700)
220
303
  workspace = args.workspace.resolve(strict=True)
221
304
  app = make_app(args.adapters.resolve(strict=True), state, workspace,
222
305
  enable_camera=args.camera, camera_devices=tuple(args.camera_device),
223
- helper_url=args.helper_url, episodic_memory=args.episodic_memory)
306
+ helper_url=args.helper_url, episodic_memory=args.episodic_memory,
307
+ episodic_root=args.episodic_memory_root, episodic_embeddings_cpu=args.episodic_embeddings_cpu)
224
308
  print(f"Qwen Omni tool API listening at 127.0.0.1:{args.port}", flush=True)
225
309
  serve(app, host="127.0.0.1", port=args.port, threads=4)
226
310
 
@@ -0,0 +1,77 @@
1
+ """Find and maintain the harness's own PulseAudio routes."""
2
+
3
+ from contextlib import contextmanager, suppress
4
+ import json
5
+ import os
6
+ import subprocess
7
+
8
+
9
+ class AudioRouteChanged(RuntimeError):
10
+ """A configured PulseAudio device or capture stream needs to reconnect."""
11
+
12
+
13
+ def _pactl(*arguments):
14
+ try:
15
+ return subprocess.check_output(["pactl", *arguments], text=True, stderr=subprocess.DEVNULL, timeout=3)
16
+ except (OSError, subprocess.SubprocessError) as error:
17
+ raise AudioRouteChanged("PulseAudio route is unavailable") from error
18
+
19
+
20
+ def _inventory(kind):
21
+ return json.loads(_pactl("-f", "json", "list", kind))
22
+
23
+
24
+ def select_input(sources, configured, default):
25
+ names = [source["name"] for source in sources]
26
+ if configured is not None:
27
+ return configured if configured in names else None
28
+ physical = [name for name in names if not name.endswith(".monitor") and (
29
+ name.startswith(("alsa_input.", "bluez_input."))
30
+ )]
31
+ respeakers = [name for name in physical if "respeaker" in name.casefold()]
32
+ preferred = respeakers or physical
33
+ if default in preferred:
34
+ return default
35
+ return next(iter(preferred), None)
36
+
37
+
38
+ def select_devices(source, sink, sources=None):
39
+ if sources is None:
40
+ sources = _inventory("sources")
41
+ defaults = json.loads(_pactl("-f", "json", "info"))
42
+ microphone = select_input(sources, source, defaults["default_source_name"])
43
+ speaker = sink or defaults["default_sink_name"]
44
+ if not microphone or not speaker or speaker.startswith("phosphor_duplex_"):
45
+ raise AudioRouteChanged("waiting for the microphone and speaker")
46
+ return microphone, speaker
47
+
48
+
49
+ def restore_capture(pid, name, sources=None):
50
+ if sources is None:
51
+ sources = _inventory("sources")
52
+ target = next((source["index"] for source in sources if source["name"] == name), None)
53
+ capture = next((stream for stream in _inventory("source-outputs")
54
+ if stream.get("properties", {}).get("application.process.id") == str(pid)), None)
55
+ if target is None or capture is None:
56
+ raise AudioRouteChanged("the microphone stream disappeared")
57
+ if capture["source"] == target:
58
+ return False
59
+ _pactl("move-source-output", str(capture["index"]), name)
60
+ return True
61
+
62
+
63
+ @contextmanager
64
+ def echo_cancel(source, sink, enabled):
65
+ if not enabled:
66
+ yield source, sink
67
+ return
68
+ name = f"phosphor_duplex_{os.getpid()}"
69
+ microphone, speaker = f"{name}_input", f"{name}_output"
70
+ module = _pactl("load-module", "module-echo-cancel", f"source_master={source}", f"sink_master={sink}",
71
+ f"source_name={microphone}", f"sink_name={speaker}", "aec_method=webrtc",
72
+ "use_master_format=0", "rate=16000", "channels=1").strip()
73
+ try:
74
+ yield microphone, speaker
75
+ finally:
76
+ with suppress(AudioRouteChanged):
77
+ _pactl("unload-module", module)
@@ -0,0 +1,337 @@
1
+ """Build complete-line Python regex patterns from typed components."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import PurePath
7
+ import re
8
+ import subprocess
9
+ import sys
10
+
11
+
12
+ KINDS = ("literal", "choice", "shape", "date_format", "unsigned_integer", "quoted_text")
13
+ REGEX_EXAMPLE_TOOL = {
14
+ "type": "function", "function": {
15
+ "name": "regex_example",
16
+ "description": "Read one representative positive example from a named fixture in the current workspace.",
17
+ "parameters": {"type": "object", "properties": {}, "additionalProperties": False},
18
+ },
19
+ }
20
+ REGEX_FIELDS_TOOL = {
21
+ "type": "function", "function": {
22
+ "name": "regex_infer_fields",
23
+ "description": ("Infer a regex for structured key=value records from positive workspace examples. "
24
+ "Omit captures to use the workspace specification. For explicit captures, use number for digits before a unit."),
25
+ "parameters": {"type": "object", "additionalProperties": False, "properties": {
26
+ "captures": {"type": "array", "maxItems": 16, "items": {
27
+ "type": "object", "additionalProperties": False, "required": ["field", "name", "part"],
28
+ "properties": {"field": {"type": "string"}, "name": {"type": "string"},
29
+ "part": {"type": "string", "enum": ["value", "number"]}},
30
+ }},
31
+ }},
32
+ },
33
+ }
34
+ REGEX_BUILD_TOOL = {
35
+ "type": "function",
36
+ "function": {
37
+ "name": "regex_build",
38
+ "description": ("Build a complete-line Python regex from typed components. With an actual valid example, "
39
+ "give the verbatim span for each varying field and the tool preserves all other text. "
40
+ "Shape uses A for uppercase ASCII, a for lowercase, and 0 for a digit, such as AA-0000. "
41
+ "Date format accepts strftime directives. Quoted text takes the quote delimiter as its value."),
42
+ "parameters": {
43
+ "type": "object", "required": ["parts"], "additionalProperties": False,
44
+ "properties": {"example": {"type": "string", "maxLength": 512,
45
+ "description": "An observed valid line which the complete pattern must match."},
46
+ "parts": {
47
+ "type": "array", "minItems": 1, "maxItems": 24,
48
+ "items": {"type": "object", "required": ["kind"], "additionalProperties": False, "properties": {
49
+ "kind": {"type": "string", "enum": list(KINDS)},
50
+ "value": {"type": "string", "maxLength": 128,
51
+ "description": "Literal, shape, date format, or quote delimiter."},
52
+ "choices": {"type": "array", "minItems": 1, "maxItems": 12,
53
+ "items": {"type": "string", "maxLength": 128}},
54
+ "capture": {"type": "string", "maxLength": 40, "description": "Optional named capture."},
55
+ "span": {"type": "string", "minLength": 1, "maxLength": 128,
56
+ "description": "Verbatim example substring this component replaces."},
57
+ "after": {"type": "string", "maxLength": 128,
58
+ "description": "Optional fixed prefix immediately before a repeated example span."},
59
+ }},
60
+ }},
61
+ },
62
+ },
63
+ }
64
+ _SHAPE = {"A": "[A-Z]", "a": "[a-z]", "0": "[0-9]"}
65
+ _DATE = {"Y": r"[0-9]{4}", **dict.fromkeys("mdHMS", r"[0-9]{2}"), "%": "%"}
66
+ _UTC = r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z"
67
+ _UINT = r"(?:0|[1-9][0-9]*)"
68
+ _NUMBER = re.compile(r"(0|[1-9][0-9]*)([A-Za-z%]{0,12})\Z")
69
+ _FIELD = re.compile(r'(?:(?P<key>[A-Za-z_][\w.-]*)=)?(?P<value>"(?:[^"\\\r\n]|\\["\\])*"|[^\s"]+)(?P<gap> +|$)')
70
+ _DECLARED_CAPTURE = re.compile(r"\bcapture\s+(?:the\s+)?([A-Za-z_][\w.-]*)([^.?!\n]{0,150}?)"
71
+ r"\bgroup\s+[`'\"]?([A-Za-z_][A-Za-z0-9_]{0,39})", re.I)
72
+
73
+
74
+ def _read_workspace_fixture(invoke, specifications=False):
75
+ listing = invoke("workspace_file", {"action": "list", "path": ".", "depth": 1})
76
+ root = listing.get("path")
77
+ if not isinstance(root, str):
78
+ return {"available": False, "reason": "workspace listing unavailable"}
79
+ candidates = []
80
+ for entry in listing.get("entries", ()):
81
+ if not isinstance(entry, dict) or entry.get("kind") != "file" or not isinstance(entry.get("path"), str):
82
+ continue
83
+ path = PurePath(entry["path"])
84
+ if (path.is_absolute() or len(path.parts) != 1 or path.suffix.lower() not in {".txt", ".log", ".csv", ".tsv", ".jsonl"}
85
+ or re.search(r"negative|invalid|reject|bad", path.name, re.I)):
86
+ continue
87
+ if specifications and re.search(r"\b(?:spec(?:ification)?|requirements?|contract)\b", path.stem, re.I):
88
+ candidates.append((2, str(path)))
89
+ elif not specifications and re.search(r"positive|valid", path.name, re.I):
90
+ candidates.append((2, str(path)))
91
+ elif not specifications and re.search(r"examples?|samples?", path.name, re.I):
92
+ candidates.append((1, str(path)))
93
+ if not candidates:
94
+ return {"available": False, "reason": "no matching named fixture in the workspace"}
95
+ _, path = max(candidates)
96
+ selected = invoke("workspace_file", {"action": "read", "path": path, "max_chars": 4096 if specifications else 2048})
97
+ source = selected.get("path")
98
+ if not isinstance(source, str) or PurePath(source).parent != PurePath(root):
99
+ return {"available": False, "reason": "the listed example did not resolve inside the workspace"}
100
+ return selected | {"source": path}
101
+
102
+
103
+ def read_regex_example(invoke):
104
+ selected = _read_workspace_fixture(invoke)
105
+ content = selected.get("content", "")
106
+ lines = [line for line in content.splitlines() if line.strip() and len(line) <= 512] if isinstance(content, str) else []
107
+ if selected.get("truncated") and lines:
108
+ lines.pop()
109
+ if lines:
110
+ return {"available": True, "example": lines[0], "examples": lines[:16], "source": selected["source"]}
111
+ return {"available": False, "reason": "no complete example line within the preview"}
112
+
113
+
114
+ def _split_fields(line):
115
+ result = []
116
+ cursor = 0
117
+ for match in _FIELD.finditer(line):
118
+ if cursor != match.start():
119
+ raise ValueError("records must contain space-separated fields with consistent quoting")
120
+ result.append((match["key"], match["value"], match["gap"]))
121
+ cursor = match.end()
122
+ if cursor != len(line) or not result:
123
+ raise ValueError("a record could not be tokenized")
124
+ return result
125
+
126
+
127
+ def _shape_of(value):
128
+ return "".join("A" if "A" <= c <= "Z" else "a" if "a" <= c <= "z" else "0" if "0" <= c <= "9" else c
129
+ for c in value)
130
+
131
+
132
+ def _infer_value(values, capture):
133
+ name, part = capture or (None, "value")
134
+ if all(re.fullmatch(_UTC, value) for value in values):
135
+ expression = _UTC
136
+ elif all(value.startswith('"') and value.endswith('"') for value in values):
137
+ expression = _component({"kind": "quoted_text", "value": '"'})
138
+ else:
139
+ numbers = [_NUMBER.fullmatch(value) for value in values]
140
+ if all(numbers) and len({match[2] for match in numbers}) == 1 and (part == "number" or len(set(values)) > 1):
141
+ suffix = re.escape(numbers[0][2])
142
+ if part == "number":
143
+ return f"(?P<{name}>{_UINT})" + suffix
144
+ expression = _UINT + suffix
145
+ elif part == "number":
146
+ raise ValueError("a number capture needs canonical integer prefixes and a shared literal suffix")
147
+ elif (len({_shape_of(value) for value in values}) == 1 and len(set(values)) > 1
148
+ and all(re.search(r"[A-Za-z]", value) and re.search(r"[0-9]", value) for value in values)):
149
+ expression = _component({"kind": "shape", "value": _shape_of(values[0])})
150
+ else:
151
+ options = sorted(set(values))
152
+ expression = re.escape(options[0]) if len(options) == 1 else "(?:" + "|".join(map(re.escape, options)) + ")"
153
+ return expression if name is None else f"(?P<{name}>{expression})"
154
+
155
+
156
+ def _requested_captures(specification, fields):
157
+ captures = []
158
+ for label, wording, name in _DECLARED_CAPTURE.findall(specification):
159
+ keys = [key for key in fields if label.casefold() == key.casefold()]
160
+ if not keys:
161
+ keys = [key for key in fields if len(key) >= 3 and label.casefold().startswith(key.casefold())]
162
+ if len(keys) != 1:
163
+ raise ValueError(f"capture {name!r} does not identify a unique field")
164
+ part = "number" if re.search(r"\b(?:digits|integer|numeric)\b", wording, re.I) else "value"
165
+ captures.append({"field": keys[0], "name": name, "part": part})
166
+ return captures
167
+
168
+
169
+ def infer_field_regex(arguments, source, specification=None):
170
+ try:
171
+ examples = source.get("examples", [])
172
+ if not 2 <= len(examples) <= 16:
173
+ raise ValueError("provide at least two positive records")
174
+ records = [_split_fields(line) for line in examples]
175
+ layout = [(key, gap) for key, _, gap in records[0]]
176
+ if any([(key, gap) for key, _, gap in record] != layout for record in records[1:]):
177
+ raise ValueError("positive records must share the same field order and spacing")
178
+ captures = {}
179
+ names = set()
180
+ fields = {key for key, _ in layout if key is not None}
181
+ requested = arguments.get("captures")
182
+ if requested is None:
183
+ if not isinstance(specification, str):
184
+ raise ValueError("give captures explicitly or supply a workspace specification")
185
+ requested = _requested_captures(specification, fields)
186
+ for item in requested:
187
+ field, name, part = item["field"], item["name"], item["part"]
188
+ if (field not in fields or field in captures or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{0,39}", name)
189
+ or name in names or part not in {"value", "number"}):
190
+ raise ValueError("captures must name unique known fields and unique group names")
191
+ captures[field] = (name, part)
192
+ names.add(name)
193
+ parts = []
194
+ for index, (key, gap) in enumerate(layout):
195
+ prefix = "" if key is None else re.escape(f"{key}=")
196
+ parts.append(prefix + _infer_value([record[index][1] for record in records], captures.get(key)) + re.escape(gap))
197
+ pattern = r"\A" + "".join(parts) + r"\Z"
198
+ rule = re.compile(pattern)
199
+ if not all(rule.fullmatch(example) for example in examples):
200
+ raise ValueError("the inferred pattern did not match all positive records")
201
+ return {"pattern": pattern, "flavor": "python-re", "captures": sorted(names),
202
+ "example_matched": True, "examples_checked": len(examples), "source": source.get("source")}
203
+ except (KeyError, TypeError, ValueError, re.error) as error:
204
+ return {"ok": False, "error": "ToolInputError", "message": str(error)}
205
+
206
+
207
+ def infer_workspace_field_regex(arguments, invoke):
208
+ source = read_regex_example(invoke)
209
+ spec = _read_workspace_fixture(invoke, specifications=True) if "captures" not in arguments else {}
210
+ return infer_field_regex(arguments, source, spec.get("content"))
211
+
212
+
213
+ def _date_format(value):
214
+ fragments = []
215
+ characters = iter(value)
216
+ for char in characters:
217
+ if char != "%":
218
+ fragments.append(re.escape(char))
219
+ continue
220
+ directive = next(characters, None)
221
+ if directive not in _DATE:
222
+ raise ValueError("unsupported date format directive")
223
+ fragments.append(_DATE[directive])
224
+ return "".join(fragments)
225
+
226
+
227
+ def _component(part):
228
+ kind = part["kind"]
229
+ value = part.get("value", "")
230
+ if not isinstance(value, str) or len(value) > 128:
231
+ raise ValueError("component value must be a short string")
232
+ if kind == "literal":
233
+ return re.escape(value)
234
+ if kind == "choice":
235
+ choices = part.get("choices")
236
+ if choices is None and "|" in value:
237
+ choices = value.split("|")
238
+ if not isinstance(choices, list) or not 1 <= len(choices) <= 12 or any(
239
+ not isinstance(choice, str) or len(choice) > 128 for choice in choices
240
+ ):
241
+ raise ValueError("choice requires one or more short literals")
242
+ return "(?:" + "|".join(re.escape(choice) for choice in choices) + ")"
243
+ if kind == "shape":
244
+ return "".join(_SHAPE.get(char, re.escape(char)) for char in value)
245
+ if kind == "date_format":
246
+ return _date_format(value)
247
+ if kind == "unsigned_integer":
248
+ return r"(?:0|[1-9][0-9]*)"
249
+ if kind == "quoted_text":
250
+ if value not in {"'", '"'}:
251
+ raise ValueError("quoted_text requires a single or double quote delimiter")
252
+ quote = re.escape(value)
253
+ return rf"{quote}(?:[^{quote}\\\r\n]|\\[{quote}\\])*{quote}"
254
+ raise ValueError("unsupported regex component")
255
+
256
+
257
+ def tighten_quoted_escapes(pattern):
258
+ """Restrict a unique quoted field's wildcard escape to its delimiter and backslash."""
259
+ replacements = []
260
+ for delimiter in ('"', "'"):
261
+ quote = re.escape(delimiter)
262
+ allowed = rf"\\[{quote}\\]"
263
+ quoted = _component({"kind": "quoted_text", "value": delimiter})
264
+ for strict in (quoted, quoted.replace(r"\r\n", "")):
265
+ loose = strict.replace(allowed, r"\\.")
266
+ if pattern.count(loose) == 1:
267
+ replacements.append((loose, strict))
268
+ if len(replacements) != 1:
269
+ return None
270
+ loose, strict = replacements[0]
271
+ replacement = pattern.replace(loose, strict)
272
+ try:
273
+ re.compile(replacement)
274
+ except re.error:
275
+ return None
276
+ return replacement
277
+
278
+
279
+ def build_regex(arguments):
280
+ parts = arguments.get("parts")
281
+ if not isinstance(parts, list) or not 1 <= len(parts) <= 24:
282
+ return {"ok": False, "error": "ToolInputError", "message": "Provide one to 24 ordered parts."}
283
+ fragments = []
284
+ names = set()
285
+ try:
286
+ example = arguments.get("example")
287
+ if example is not None and (not isinstance(example, str) or len(example) > 512):
288
+ raise ValueError("provide one valid example of at most 512 characters")
289
+ spans = any(isinstance(part, dict) and "span" in part for part in parts)
290
+ if spans and not example:
291
+ raise ValueError("provide the actual example when using spans")
292
+ for part in parts:
293
+ if (spans and part.get("kind") == "literal" and part.get("capture") is None
294
+ and part.get("value", part.get("span")) == part.get("span")):
295
+ continue
296
+ fragment = _component(part)
297
+ name = part.get("capture")
298
+ if name is not None:
299
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{0,39}", name) or name in names:
300
+ raise ValueError("capture names must be unique Python identifiers")
301
+ names.add(name)
302
+ fragment = f"(?P<{name}>{fragment})"
303
+ if spans:
304
+ span, after = part.get("span"), part.get("after", "")
305
+ if not isinstance(span, str) or not span or len(span) > 128 or not isinstance(after, str):
306
+ raise ValueError("each component needs a verbatim example span")
307
+ anchor = after + span
308
+ start = example.find(anchor)
309
+ if start == -1 or example.find(anchor, start + 1) != -1:
310
+ raise ValueError(f"span {span!r} must occur once; use the preceding literal to distinguish repeats")
311
+ start += len(after)
312
+ fragments.append((start, start + len(span), fragment))
313
+ else:
314
+ fragments.append(fragment)
315
+ if spans:
316
+ assembled = []
317
+ cursor = 0
318
+ for start, end, fragment in sorted(fragments):
319
+ if start < cursor:
320
+ raise ValueError("example spans must not overlap")
321
+ assembled.extend((re.escape(example[cursor:start]), fragment))
322
+ cursor = end
323
+ fragments = [*assembled, re.escape(example[cursor:])]
324
+ pattern = r"\A" + "".join(fragments) + r"\Z"
325
+ re.compile(pattern)
326
+ if example is not None:
327
+ check = subprocess.run([
328
+ sys.executable, "-c", "import json,re,sys; p,s=json.load(sys.stdin); sys.exit(re.fullmatch(p,s) is None)",
329
+ ], input=json.dumps([pattern, example]), text=True, capture_output=True, timeout=2)
330
+ if check.returncode:
331
+ raise ValueError("the pattern does not match the example; compare each literal and component in input order")
332
+ except subprocess.TimeoutExpired:
333
+ return {"ok": False, "error": "ToolInputError", "message": "The regex example check timed out."}
334
+ except (KeyError, AttributeError, ValueError, TypeError, re.error) as error:
335
+ return {"ok": False, "error": "ToolInputError", "message": str(error)}
336
+ return {"pattern": pattern, "flavor": "python-re", "captures": sorted(names),
337
+ "example_matched": example is not None}