phosphor-harness 0.4.4 → 0.4.6

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.
@@ -3,14 +3,20 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import base64
6
+ import asyncio
6
7
  from collections import Counter
8
+ from contextlib import contextmanager, suppress
9
+ from contextvars import ContextVar
7
10
  from dataclasses import dataclass
11
+ from datetime import date
8
12
  from io import BytesIO
9
13
  import json
10
14
  import logging
11
15
  import re
16
+ import time
12
17
  from urllib.parse import urlsplit
13
18
  import wave
19
+ from uuid import uuid4
14
20
 
15
21
  import httpx
16
22
  from jsonschema import Draft202012Validator
@@ -20,17 +26,90 @@ from training_suite.models.native_turn import NativeAssistantTurn, NativeToolCal
20
26
  from training_suite.sophon_speech import validate_speech_text
21
27
  from training_suite.training.audio_bridge_training import MEDIA_INSTRUCTION, MEDIA_SYSTEM_PROMPT
22
28
 
23
- from .tools import VOICE_TOOL_ROUNDS, active_tools, current_turn, requested_tool
29
+ from .regex_tools import tighten_quoted_escapes
30
+ from .speak_thinking import ProgressChatStream, TOOL_NAME as THINKING_TOOL, requested_setting
31
+ from .tools import FILE_TOOL_ROUNDS, VOICE_TOOL_ROUNDS, active_tools, current_turn, requested_tools
24
32
  from .terminal_input import PASSWORD_REQUEST, TERMINAL_HANDLE
25
33
 
26
34
  FAILURE_INSTRUCTIONS = (
27
35
  "Use the tool receipt to diagnose failure. For correct_arguments, fix the evidenced problem. "
28
36
  "For change_capability, consider the offered tools. For repeat_read_once, the same read may be retried once. "
37
+ "After a verified file change, rerun a failed shell verification to check the correction. "
29
38
  "For needs_location, ask for an updated location. For report_failure, state what failed or use an "
30
39
  "independent permitted tool when appropriate. Respect access controls. "
31
40
  "Speak plain text and omit URLs, markup, and command syntax."
32
41
  )
33
42
  _EXPLICIT_READ_ONLY = {"safe_math_eval", "scan_wifi_networks", "get_current_time", "get_system_snapshot", "capture_view"}
43
+ _FILE_TOOLS = {"shell", "workspace_file", "regex_build", "regex_example", "regex_infer_fields", "regex_save"}
44
+ _REGEX_SAVE_TOOL = {"type": "function", "function": {
45
+ "name": "regex_save",
46
+ "description": "Write the compiled pattern from this turn to the requested workspace file.",
47
+ "parameters": {"type": "object", "required": ["path"], "additionalProperties": False,
48
+ "properties": {"path": {"type": "string", "minLength": 1}}},
49
+ }}
50
+ _LITERAL_REPLACEMENT = re.compile(r"\breplace\s+([\w-]+)\s+with\s+([\w-]+)\b", re.I)
51
+ _COUNT_WORDS = dict(zip("one two three four five six seven eight nine ten".split(), range(1, 11)))
52
+ _ORDINALS = dict(zip("first second third fourth fifth sixth seventh eighth ninth tenth".split(), range(1, 11)))
53
+ _DICTATED_LINES = re.compile(
54
+ r"\b(\d{1,2}|" + "|".join(_COUNT_WORDS) + r")\s+(?:(?:newline[- ]|newly )terminated\s+)?lines\s*[:.]\s*"
55
+ r"([A-Za-z-]+(?:\s*,\s*[A-Za-z-]+)+)\s*[.!?]", re.I,
56
+ )
57
+ _DICTATED_REPEAT = re.compile(
58
+ r"\bthe first\s+(\d{1,2}|" + "|".join(_COUNT_WORDS) + r")\s+say\s+([A-Za-z-]+)[.?!]", re.I,
59
+ )
60
+ _DICTATED_ORDINAL = re.compile(
61
+ r"\bthe\s+(" + "|".join(_ORDINALS) + r")\s+says?\s+([A-Za-z-]+)[.?!]", re.I,
62
+ )
63
+ _REQUESTED_OCCURRENCES = re.compile(
64
+ r"\b(?:expected\s+count(?:\s+of)?|requiring(?:\s+a\s+count\s+of)?|with\s+exactly|count\s+of)"
65
+ r"\s+(?:exactly\s+)?(\d{1,4}|" + "|".join(_COUNT_WORDS) + r")\b", re.I,
66
+ )
67
+ _OCCURRENCE_ERROR = re.compile(r"old_text occurrence mismatch: expected \d+, found (\d+)\Z")
68
+ _REGEX_REQUEST = re.compile(r"\b(?:regex|regular expression)\b", re.I)
69
+ _RERUN_VERIFICATION = re.compile(r"\b(?:re[- ]?run|repeat)\b[^.!?\n]{0,160}"
70
+ r"\b(?:validat\w*|verif\w*|check\w*|test\w*)\b", re.I)
71
+ _SHELL_STDIN_REQUEST = re.compile(r"\bstdin\s+(?:argument|field|parameter)\b", re.I)
72
+ _DIRECT_DATE = re.compile(
73
+ r"(?:what(?:'s| is)|tell me|can you tell me) (?:the )?(?:current |today's )?date(?: today| right now)?"
74
+ r"|(?:can you tell me )?what (?:day|date) is (?:it(?: today)?|today)"
75
+ r"|(?:can you tell me )?what (?:the date is today|today's date is)", re.I,
76
+ )
77
+ _RECALL_REQUEST = re.compile(
78
+ r"\b(?:do you remember|can you recall|what did (?:i|we) (?:say|discuss|talk about|tell you)|"
79
+ r"(?:find|search|recall) (?:our |my )?(?:past|earlier|previous) (?:conversation|discussion))\b", re.I,
80
+ )
81
+ _LITERAL_STDIN_PIPE = re.compile(r"\A\s*printf\s+'([^']+)'\s*\|\s*(?![|&])")
82
+ _SOURCE_FOR_SCRIPT = re.compile(r"\b(?:create|write)\s+[\w./-]+\.py\s+(?:to|that)\s+reads?\s+"
83
+ r"([\w./-]+\.[A-Za-z0-9]{1,12})\b", re.I)
84
+ _QUOTED_ESCAPE_READ = re.compile(r"\bread\s+([\w./-]+\.[A-Za-z0-9]{1,12})\s+and\s+repair\s+only\s+[^.!?\n]*\bquoted\b", re.I)
85
+ _VERIFY_SCRIPT = re.compile(r"\brun\s+(?:python3\s+|the\s+unchanged\s+)([\w./-]+\.py)\b", re.I)
86
+ _CAPTURE_REQUIREMENT = re.compile(
87
+ r"\b(?:named\s+group|capture\b[^.?!\n]{0,90}?\bgroup)\s+[`'\"]?([A-Za-z_][A-Za-z0-9_]{0,39})", re.I,
88
+ )
89
+ _SPAN_GUIDANCE = (
90
+ "In example mode, omit all literal separators, spaces, and fixed fields. Each part covers an entire varying value. "
91
+ "Example line: SKU=DX-914 QTY=37 AREA=west TAG='ready'. To allow different SKUs, quantities, east or west, "
92
+ "and single-quoted tags, send these parts: "
93
+ '[{"kind":"shape","span":"DX-914","value":"AA-000","capture":"sku"},'
94
+ '{"kind":"unsigned_integer","span":"37","capture":"qty"},'
95
+ '{"kind":"choice","span":"west","choices":["east","west"]},'
96
+ '{"kind":"quoted_text","span":"\'ready\'","value":"\'"}]. '
97
+ "A shape is a mask, not regex syntax. The compiler inserts fixed text from the example. For a date use "
98
+ "date_format and give the corresponding strftime layout. A quoted span includes its opening and closing quotes."
99
+ )
100
+ _FILE_TOOL_INSTRUCTIONS = (
101
+ "For file and shell tasks, use relative workspace paths unless the user supplied an absolute path. "
102
+ "The receipt's artifact paths are logs, not the shell working directory. Keep tool calls concise. "
103
+ "Interpret dictated slash, dot, and letter names as filename punctuation and spelling when clear. "
104
+ "When a check fails, use the specification and the reported failing case to make a correction, "
105
+ "then rerun the exact check. Once you have the relevant evidence, make the requested edit without further reads. "
106
+ "For a regex, construct it in the order of the input fields. Use the requested capture names only on the "
107
+ "corresponding fields and check a valid and invalid example before reporting success. "
108
+ "When available, use regex_build for typed components and quoted-text escaping, then save the returned pattern. "
109
+ "Use the verify intent for a shell check. A standard checksum manifest includes both the digest and filename. "
110
+ "When checking a saved SHA-256 manifest, pass that file to sha256sum -c in a separate call. "
111
+ "Keep source files intact unless the user asks to modify them. Report what the final receipt actually shows."
112
+ )
34
113
 
35
114
 
36
115
  @dataclass
@@ -68,12 +147,49 @@ class OrnithTokenLimit(ValueError):
68
147
  """The response ran out of generation tokens before it could finish."""
69
148
 
70
149
 
71
- def _audio_part(pcm: bytes) -> dict:
150
+ class OrnithTurnInterrupted(RuntimeError):
151
+ """The acoustic session superseded an in-flight request."""
152
+
153
+
154
+ def _wave_bytes(pcm: bytes) -> bytes:
72
155
  output = BytesIO()
73
156
  with wave.open(output, "wb") as wav:
74
157
  wav.setparams((1, 2, 16_000, 0, "NONE", "not compressed"))
75
158
  wav.writeframes(pcm)
76
- return {"type": "input_audio", "input_audio": {"data": base64.b64encode(output.getvalue()).decode("ascii")}}
159
+ return output.getvalue()
160
+
161
+
162
+ def _audio_part(pcm: bytes) -> dict:
163
+ return {"type": "input_audio", "input_audio": {"data": base64.b64encode(_wave_bytes(pcm)).decode("ascii")}}
164
+
165
+
166
+ def _spoken_extensions(text):
167
+ if re.search(r"\b(?:upper\s*case|case[- ]sensitive|including the hyphen|verbatim)\b", text, re.I):
168
+ return text
169
+ return re.sub(r"(\bdot\s+|\.)sha-256\b", r"\g<1>sha256", text, flags=re.I)
170
+
171
+
172
+ def _dictated_lines(text):
173
+ if (not text or not re.search(r"\b(?:write|create|text file)\b", text, re.I)
174
+ or not re.search(r"\b(?:newline|new line|terminate|terminated)\b", text, re.I)
175
+ or re.search(r"\b(?:upper\s*case|capitalize|case[- ]sensitive|verbatim)\b", text, re.I)):
176
+ return None
177
+ if listed := _DICTATED_LINES.search(text):
178
+ count = int(listed[1]) if listed[1].isdecimal() else _COUNT_WORDS[listed[1].lower()]
179
+ items = [item.strip().lower() for item in listed[2].split(",")]
180
+ if len(items) == count:
181
+ return "\n".join(items) + "\n"
182
+ if repeated := _DICTATED_REPEAT.search(text):
183
+ count = int(repeated[1]) if repeated[1].isdecimal() else _COUNT_WORDS[repeated[1].lower()]
184
+ positions = {index: repeated[2].lower() for index in range(1, count + 1)}
185
+ for ordinal, word in _DICTATED_ORDINAL.findall(text):
186
+ index = _ORDINALS[ordinal.lower()]
187
+ if index in positions:
188
+ return None
189
+ positions[index] = word.lower()
190
+ if len(positions) > count and set(positions) == set(range(1, len(positions) + 1)):
191
+ return "\n".join(positions[index] for index in range(1, len(positions) + 1)) + "\n"
192
+ return None
77
193
 
78
194
 
79
195
  def _arguments(raw: str) -> dict:
@@ -104,16 +220,199 @@ def _system_instruction(messages, text):
104
220
  return [{"role": "system", "content": text}, *messages]
105
221
 
106
222
 
223
+ def _compact_completed_turns(messages):
224
+ last_user = max((i for i, message in enumerate(messages) if message["role"] == "user"), default=0)
225
+ earlier = messages[:last_user]
226
+ compact = [message for message in earlier
227
+ if message["role"] != "tool" and not message.get("tool_calls")]
228
+ if len(compact) != len(earlier):
229
+ return [*compact, *messages[last_user:]]
230
+ user_turns = [i for i, message in enumerate(earlier) if message["role"] == "user"]
231
+ if not user_turns:
232
+ return messages
233
+ first_user = user_turns[0]
234
+ next_user = user_turns[1] if len(user_turns) > 1 else last_user
235
+ return [*messages[:first_user], *messages[next_user:]]
236
+
237
+
238
+ def _context_rejected(response):
239
+ if response.status_code != 400:
240
+ return False
241
+ try:
242
+ message = response.json()["error"]["message"]
243
+ except (ValueError, KeyError, TypeError):
244
+ return False
245
+ return isinstance(message, str) and "exceeds the available context size" in message
246
+
247
+
248
+ def _shell_context(content):
249
+ envelope = json.loads(content)
250
+ data = envelope.get("data")
251
+ if isinstance(data, dict) and "output_artifacts" in data and not any(
252
+ data.get(key) for key in ("stdout_truncated", "stderr_truncated", "truncated")
253
+ ):
254
+ data.pop("output_artifacts")
255
+ return json.dumps(envelope)
256
+ return content
257
+
258
+
259
+ def _shell_stdin_arguments(arguments):
260
+ data = arguments.get("stdin")
261
+ if not isinstance(data, str) or not data.strip():
262
+ raise ValueError("put the requested input in stdin and read from standard input")
263
+ command = arguments["command"]
264
+ literal = data.rstrip("\n")
265
+ if "\n" not in literal or (literal not in command and literal.replace("\n", r"\n") not in command):
266
+ return arguments
267
+ prefix = _LITERAL_STDIN_PIPE.match(command)
268
+ if prefix and command[prefix.end():].strip() and not any(symbol in data for symbol in ("%", "\\")):
269
+ printed = prefix[1].replace(r"\n", "\n")
270
+ if printed in {data, data + "\n"}:
271
+ return {**arguments, "command": command[prefix.end():], "stdin": printed}
272
+ raise ValueError("put the input only in stdin and have the command read from standard input")
273
+
274
+
275
+ def _current_date_turn(receipts):
276
+ for entry in reversed(receipts):
277
+ if entry["role"] == "tool" and entry.get("name") == "get_current_time":
278
+ envelope = json.loads(entry["content"])
279
+ try:
280
+ if envelope.get("status") == "ok":
281
+ current = date.fromisoformat(envelope["data"]["date"])
282
+ return NativeAssistantTurn(f"Today is {current:%A, %B} {current.day}, {current.year}.", ())
283
+ except (TypeError, ValueError, KeyError):
284
+ pass
285
+ return NativeAssistantTurn("I couldn't read the current date from the device clock.", ())
286
+ return NativeAssistantTurn("", (NativeToolCall(uuid4().hex, "get_current_time", {}),))
287
+
288
+
289
+ def _thinking_setting_turn(receipts, enabled):
290
+ for entry in reversed(receipts):
291
+ if entry["role"] == "tool" and entry.get("name") == THINKING_TOOL:
292
+ envelope = json.loads(entry["content"])
293
+ result = envelope.get("data") or {}
294
+ if envelope.get("status") == "ok" and result.get("enabled") is enabled and result.get("durable") is True:
295
+ return NativeAssistantTurn("The progress voice is " + ("on." if enabled else "off."), ())
296
+ return NativeAssistantTurn("I couldn't confirm the progress voice setting.", ())
297
+ return NativeAssistantTurn("", (NativeToolCall(uuid4().hex, THINKING_TOOL, {"enabled": enabled}),))
298
+
299
+
300
+ @dataclass(frozen=True)
301
+ class _ReplacementPrecondition:
302
+ old: str
303
+ new: str
304
+ expected_count: int | None
305
+ retry_path: str | None = None
306
+
307
+ def validate(self, call):
308
+ args = call.arguments
309
+ if call.name != "workspace_file" or args.get("action") != "replace":
310
+ return
311
+ if (args.get("old_text"), args.get("new_text")) != (self.old, self.new):
312
+ raise ValueError(f"use the requested literal old_text {self.old!r} and new_text {self.new!r}")
313
+ if self.expected_count is not None and args.get("expected_occurrences") != self.expected_count:
314
+ raise ValueError(f"set expected_occurrences to {self.expected_count}")
315
+
316
+ def constrain(self, definition):
317
+ values = {"action": "replace", "old_text": self.old, "new_text": self.new,
318
+ "expected_occurrences": self.expected_count}
319
+ if self.retry_path is not None:
320
+ values["path"] = self.retry_path
321
+ return _constrain_tool(definition, values)
322
+
323
+
324
+ def _constrain_tool(definition, values):
325
+ function = definition["function"]
326
+ parameters = function["parameters"]
327
+ properties = {**parameters.get("properties", {}),
328
+ **{key: {"const": value} for key, value in values.items()}}
329
+ required = list(dict.fromkeys([*parameters.get("required", ()), *values]))
330
+ return {**definition, "function": {**function, "parameters": {
331
+ **parameters, "properties": properties, "required": required,
332
+ }}}
333
+
334
+
335
+ def _require_regex_example(definition, example):
336
+ function = definition["function"]
337
+ parameters = function["parameters"]
338
+ parts = parameters["properties"]["parts"]
339
+ item = parts["items"]
340
+ return {**definition, "function": {**function, "parameters": {
341
+ **parameters, "required": [*parameters["required"], "example"],
342
+ "properties": {**parameters["properties"], "example": {"const": example}, "parts": {**parts, "items": {
343
+ **item, "required": [*item["required"], "span"],
344
+ }}},
345
+ }}}
346
+
347
+
348
+ def _workspace_file_observed(messages, path):
349
+ reads_or_writes = {call["id"] for message in messages for call in (message.get("tool_calls") or ())
350
+ if call["function"]["name"] == "workspace_file"
351
+ and call["function"]["arguments"].get("path") == path
352
+ and call["function"]["arguments"].get("action") in {"read", "write"}}
353
+ return any(message.get("role") == "tool" and message.get("tool_call_id") in reads_or_writes
354
+ and json.loads(message["content"]).get("status") == "ok" for message in messages)
355
+
356
+
357
+ def _replacement_precondition(request, rounds, current):
358
+ if not request or not (literal := _LITERAL_REPLACEMENT.search(request)):
359
+ return None
360
+ count = _REQUESTED_OCCURRENCES.search(request[literal.end():literal.end() + 240])
361
+ if not count:
362
+ return None
363
+ value = count[1].lower()
364
+ expected = int(value) if value.isdecimal() else _COUNT_WORDS[value]
365
+ if not 1 <= expected <= 1000:
366
+ return None
367
+ calls_by_id = {call["id"]: call["function"]["arguments"] for calls in rounds for call in calls
368
+ if call["function"]["name"] == "workspace_file"}
369
+ if not any(args.get("action") == "replace" for args in calls_by_id.values()):
370
+ return _ReplacementPrecondition(*literal.groups(), expected)
371
+ pending = None
372
+ retry = None
373
+ if re.search(r"\b(?:retry|repeat|try again)\b", request, re.I):
374
+ for item in current:
375
+ if item["role"] != "tool" or item.get("name") != "workspace_file":
376
+ continue
377
+ args = calls_by_id.get(item["tool_call_id"], {})
378
+ result = json.loads(item["content"])
379
+ data = result.get("data") or {}
380
+ if args.get("action") == "replace":
381
+ pending = None
382
+ retry = None
383
+ if result.get("status") == "error" and data.get("error") == "ToolInputError":
384
+ actual = _OCCURRENCE_ERROR.fullmatch(data.get("message", ""))
385
+ if actual and 1 <= int(actual[1]) <= 1000:
386
+ pending = (args.get("path"), int(actual[1]))
387
+ elif (pending and args.get("action") == "read" and args.get("path") == pending[0]
388
+ and result.get("status") == "ok"):
389
+ retry = pending
390
+ return _ReplacementPrecondition(*literal.groups(), retry[1], retry[0]) if retry else (
391
+ _ReplacementPrecondition(*literal.groups(), None)
392
+ )
393
+
394
+
107
395
  class OrnithBackplane:
108
396
  prior_audio = ()
397
+ tool_rounds = FILE_TOOL_ROUNDS
109
398
 
110
- def __init__(self, url: str, model: str, *, transport=None):
399
+ def __init__(self, url: str, model: str, *, transcription_url=None, transport=None):
111
400
  address = urlsplit(url)
112
401
  if (address.scheme != "http" or address.hostname not in {"127.0.0.1", "::1"}
113
402
  or address.username is not None or address.path not in {"", "/"} or address.query or address.fragment):
114
403
  raise ValueError("Ornith requires an HTTP loopback server address")
404
+ if transcription_url is not None:
405
+ endpoint = urlsplit(transcription_url)
406
+ if (endpoint.scheme != "http" or endpoint.hostname not in {"127.0.0.1", "::1"}
407
+ or endpoint.username is not None or endpoint.path != "/v1/audio/transcriptions"
408
+ or endpoint.query or endpoint.fragment):
409
+ raise ValueError("transcription_url must point to a loopback audio transcription endpoint")
410
+ self.transcription_url = transcription_url
115
411
  self.model = model
116
412
  self.client = httpx.Client(base_url=url, timeout=90, trust_env=False, transport=transport)
413
+ self.transport = transport
414
+ self._cancel = ContextVar("ornith_cancel", default=None)
415
+ self._progress = ContextVar("ornith_progress", default=None)
117
416
 
118
417
  def __enter__(self):
119
418
  return self
@@ -121,13 +420,94 @@ class OrnithBackplane:
121
420
  def __exit__(self, *exc):
122
421
  self.client.close()
123
422
 
124
- def _chat(self, messages, *, max_tokens, **options):
423
+ @contextmanager
424
+ def interruptible(self, cancelled, *, progress=None):
425
+ token = self._cancel.set(cancelled)
426
+ progress_token = self._progress.set(progress)
125
427
  try:
126
- response = self.client.post("/v1/chat/completions", json={
127
- "model": self.model, "messages": messages, "max_tokens": max_tokens,
128
- "chat_template_kwargs": {"enable_thinking": False}, "temperature": 0, **options,
129
- })
130
- response.raise_for_status()
428
+ yield
429
+ finally:
430
+ self._cancel.reset(token)
431
+ self._progress.reset(progress_token)
432
+
433
+ @staticmethod
434
+ async def _wait_connection(awaitable, cancelled):
435
+ request = asyncio.create_task(awaitable)
436
+ while not request.done() and not cancelled.is_set():
437
+ await asyncio.wait((request,), timeout=0.025)
438
+ if cancelled.is_set():
439
+ request.cancel()
440
+ with suppress(asyncio.CancelledError, httpx.HTTPError):
441
+ await request
442
+ raise OrnithTurnInterrupted()
443
+ return request.result()
444
+
445
+ def _post(self, path, **options):
446
+ cancelled = self._cancel.get()
447
+ if cancelled is None:
448
+ return self.client.post(path, **options)
449
+
450
+ async def post():
451
+ async with httpx.AsyncClient(base_url=self.client.base_url, timeout=self.client.timeout,
452
+ trust_env=False, transport=self.transport) as client:
453
+ if cancelled.is_set():
454
+ raise OrnithTurnInterrupted()
455
+ return await self._wait_connection(client.post(path, **options), cancelled)
456
+
457
+ return asyncio.run(post())
458
+
459
+ def _stream_chat(self, payload, progress):
460
+ cancelled = self._cancel.get()
461
+
462
+ async def decode():
463
+ async with httpx.AsyncClient(base_url=self.client.base_url, timeout=self.client.timeout,
464
+ trust_env=False, transport=self.transport) as client:
465
+ request = client.build_request("POST", "/v1/chat/completions", json={
466
+ **payload, "stream": True, "timings_per_token": True,
467
+ })
468
+ response = await self._wait_connection(client.send(request, stream=True), cancelled)
469
+ try:
470
+ if not response.is_success:
471
+ await self._wait_connection(response.aread(), cancelled)
472
+ return response
473
+ stream = ProgressChatStream(progress)
474
+ lines = response.aiter_lines()
475
+ while True:
476
+ try:
477
+ line = await self._wait_connection(lines.__anext__(), cancelled)
478
+ except StopAsyncIteration:
479
+ break
480
+ if line == "data: [DONE]":
481
+ break
482
+ if line.startswith("data: "):
483
+ stream.feed(json.loads(line[6:]))
484
+ return httpx.Response(response.status_code, json=stream.response(), request=request)
485
+ finally:
486
+ await response.aclose()
487
+
488
+ return asyncio.run(decode())
489
+
490
+ def _chat(self, messages, *, max_tokens, narrate_progress=False, request_timeout=None, **options):
491
+ progress = self._progress.get() if narrate_progress else None
492
+ if progress is not None:
493
+ options["chat_template_kwargs"] = {**options.get("chat_template_kwargs", {}), "enable_thinking": True}
494
+ options.setdefault("reasoning_budget_tokens", 64)
495
+ try:
496
+ while True:
497
+ payload = {
498
+ "model": self.model, "messages": messages, "max_tokens": max_tokens,
499
+ "chat_template_kwargs": {"enable_thinking": False}, "temperature": 0, **options,
500
+ }
501
+ request_options = {} if request_timeout is None else {"timeout": request_timeout}
502
+ response = (self._stream_chat(payload, progress) if progress is not None else
503
+ self._post("/v1/chat/completions", json=payload, **request_options))
504
+ if not _context_rejected(response):
505
+ response.raise_for_status()
506
+ break
507
+ compact = _compact_completed_turns(messages)
508
+ if len(compact) == len(messages):
509
+ response.raise_for_status()
510
+ messages = compact
131
511
  choice = response.json()["choices"][0]
132
512
  if choice["finish_reason"] == "length":
133
513
  raise OrnithTokenLimit("the response reached its token limit")
@@ -182,12 +562,57 @@ class OrnithBackplane:
182
562
  return {"valid": False}
183
563
  return parse_tagged_audio_evidence("".join(f"<{name}>{result[name]}</{name}>" for name in properties))
184
564
 
565
+ def _confirm_spoken_setting(self, audio, command):
566
+ started = time.monotonic()
567
+ agreed = False
568
+ try:
569
+ message = self._chat([
570
+ {"role": "system", "content": "Check the entire audio. Set exact to true only if the spoken words "
571
+ "match the supplied command and there is no additional spoken sentence."},
572
+ {"role": "user", "content": [audio, {"type": "text", "text": command}]},
573
+ ], max_tokens=20, request_timeout=2.5, cache_prompt=False, response_format={
574
+ "type": "json_schema", "json_schema": {"name": "spoken_command", "strict": True, "schema": {
575
+ "type": "object", "properties": {"exact": {"type": "boolean"}},
576
+ "required": ["exact"], "additionalProperties": False,
577
+ }},
578
+ })
579
+ agreed = _arguments(message.get("content")).get("exact") is True
580
+ except RuntimeError as error:
581
+ if not isinstance(error.__cause__, httpx.TimeoutException):
582
+ raise
583
+ except ValueError:
584
+ pass
585
+ logging.getLogger(__name__).info("Voice setting verification took %.3fs (confirmed=%s)",
586
+ time.monotonic() - started, agreed)
587
+ return agreed
588
+
185
589
  def recognize_password(self, pcm):
186
590
  return self._recognize(pcm)["speech_transcript"]
187
591
 
188
592
  def _perceive(self, turn):
593
+ if self.transcription_url:
594
+ try:
595
+ response = self._post(self.transcription_url, files={
596
+ "file": ("utterance.wav", _wave_bytes(turn.pcm), "audio/wav"),
597
+ }, timeout=25)
598
+ response.raise_for_status()
599
+ text = response.json()["text"]
600
+ except (httpx.HTTPError, ValueError, KeyError, TypeError) as error:
601
+ raise InvalidAcousticEvidence("configured transcription endpoint failed") from error
602
+ if not isinstance(text, str) or len(text) > 8192:
603
+ raise InvalidAcousticEvidence("invalid transcript from configured endpoint")
604
+ if not text.strip():
605
+ raise NoIntelligibleSpeech("no intelligible speech from configured endpoint")
606
+ turn.user_text = _spoken_extensions(text.strip())
607
+ turn.pcm = b""
608
+ return
189
609
  evidence = self._recognize(turn.pcm)
190
- turn.user_text = evidence["speech_transcript"]
610
+ transcript = evidence["speech_transcript"]
611
+ parts = re.split(r"(?<=[.!?])\s+", transcript, maxsplit=1)
612
+ if (len(parts) == 2 and requested_setting(parts[0]) is not None
613
+ and self._confirm_spoken_setting(_audio_part(turn.pcm), parts[0])):
614
+ transcript = parts[0]
615
+ turn.user_text = _spoken_extensions(transcript)
191
616
  if observation := evidence["audio_observation"]:
192
617
  turn.user_text += f"\n\nBackground sounds: {observation}"
193
618
  turn.pcm = b""
@@ -249,26 +674,54 @@ class OrnithBackplane:
249
674
  return None
250
675
  return NativeAssistantTurn(failure_text, ())
251
676
 
252
- def _structured_generation(self, rendered, tools, max_new_tokens, cancelled, *, require_tool=False):
677
+ def _structured_generation(self, rendered, tools, max_new_tokens, cancelled, *, require_tool=False,
678
+ replacement=None, dictated_content=None, require_stdin=False):
253
679
  options = {"tools": tools, "tool_choice": "required" if require_tool else "auto"} if tools else {}
254
680
  schemas = {tool["function"]["name"]: tool["function"]["parameters"] for tool in tools}
681
+ file_work = bool(_FILE_TOOLS.intersection(schemas))
682
+ if file_work:
683
+ rendered = _system_instruction(rendered, _FILE_TOOL_INSTRUCTIONS)
684
+ if schemas.keys() == {"regex_build"}:
685
+ options["reasoning_budget_tokens"] = 384
686
+ options["chat_template_kwargs"] = {"enable_thinking": True}
687
+ max_new_tokens = max(max_new_tokens, 1536)
688
+ elif schemas.keys() == {"regex_infer_fields"}:
689
+ options["reasoning_budget_tokens"] = 128
690
+ options["chat_template_kwargs"] = {"enable_thinking": True}
691
+ max_new_tokens = max(max_new_tokens, 640)
692
+ else:
693
+ options["reasoning_budget_tokens"] = 96
694
+ max_new_tokens = max(max_new_tokens, 640)
255
695
  for attempt in range(2):
256
696
  if cancelled.is_set():
257
697
  return None
258
698
  try:
259
- message = self._chat(rendered, max_tokens=max_new_tokens, **options)
699
+ message = self._chat(rendered, max_tokens=max_new_tokens, narrate_progress=True, **options)
260
700
  if cancelled.is_set():
261
701
  return None
262
702
  turn = validate_visible_turn(self._decode(message, tools))
263
703
  if require_tool and not turn.calls:
264
704
  raise ValueError("the requested tool call was omitted")
705
+ calls = []
265
706
  for call in turn.calls:
266
707
  validate_visible_turn(NativeAssistantTurn(json.dumps(call.arguments), ()))
267
708
  validator = Draft202012Validator(schemas[call.name], registry=Registry())
268
709
  error = next(validator.iter_errors(call.arguments), None)
269
710
  if error is not None:
711
+ if error.validator == "const" and error.absolute_path:
712
+ field = error.absolute_path[-1]
713
+ raise ValueError(f"set {call.name}.{field} to {error.validator_value!r}")
270
714
  raise ValueError(f"{call.name} failed its {error.validator} schema rule")
271
- return turn
715
+ if replacement is not None:
716
+ replacement.validate(call)
717
+ if require_stdin and call.name == "shell":
718
+ call = NativeToolCall(call.id, call.name, _shell_stdin_arguments(call.arguments))
719
+ if (dictated_content is not None and call.name == "workspace_file"
720
+ and call.arguments.get("action") == "write"
721
+ and call.arguments.get("content") != dictated_content):
722
+ raise ValueError(f"write the dictated lines with this exact content: {dictated_content!r}")
723
+ calls.append(call)
724
+ return NativeAssistantTurn(turn.text, tuple(calls))
272
725
  except ValueError as error:
273
726
  if cancelled.is_set():
274
727
  return None
@@ -277,7 +730,7 @@ class OrnithBackplane:
277
730
  )
278
731
  if attempt == 0:
279
732
  if isinstance(error, OrnithTokenLimit):
280
- max_new_tokens = max(max_new_tokens, min(512, max_new_tokens * 2))
733
+ max_new_tokens = max(max_new_tokens, min(1024 if file_work else 512, max_new_tokens * 2))
281
734
  rendered = _system_instruction(
282
735
  rendered, f"The preceding generation was rejected before execution: {error}. "
283
736
  "Emit one exact native tool call, or give a short plain-text answer when no tool is needed.",
@@ -301,6 +754,8 @@ class OrnithBackplane:
301
754
  rendered = []
302
755
  for index, original in enumerate(messages):
303
756
  message = dict(original)
757
+ if message["role"] == "tool" and message.get("name") == "shell":
758
+ message["content"] = _shell_context(message["content"])
304
759
  if index in heard:
305
760
  message["content"] = heard[index].user_text
306
761
  if index == audio_index and heard[index].visual_evidence:
@@ -315,9 +770,38 @@ class OrnithBackplane:
315
770
  rendered.append(message)
316
771
  current = current_turn(messages, audio_index)
317
772
  rounds = [entry["tool_calls"] for entry in current if entry.get("tool_calls")]
318
- request = next((message["content"] for message in reversed(rendered) if message["role"] == "user"), None)
319
- named = requested_tool(tools or [], request)
320
- allowed = active_tools(tools or [], messages, audio_index, explicitly_requested=named)
773
+ requests = [message["content"] for message in rendered if message["role"] == "user"]
774
+ request = requests[-1] if requests else None
775
+ spoken_request = request.partition("\n\nBackground sounds:")[0] if request and media and not media.visual_evidence else request
776
+ if (spoken_request and _DIRECT_DATE.fullmatch(spoken_request.strip().replace("’", "'").rstrip(" .?!"))
777
+ and any(tool["function"]["name"] == "get_current_time" for tool in tools or ())):
778
+ return _current_date_turn(current)
779
+ thinking_setting = requested_setting(spoken_request)
780
+ if thinking_setting is not None and any(tool["function"]["name"] == THINKING_TOOL for tool in tools or ()):
781
+ return _thinking_setting_turn(current, thinking_setting)
782
+ named_tools = requested_tools(tools or [], request)
783
+ recall_requested = bool(request and _RECALL_REQUEST.search(request) and not rounds
784
+ and any(tool["function"]["name"] == "episodic_search" for tool in tools or ()))
785
+ if recall_requested:
786
+ named_tools.add("episodic_search")
787
+ named = next(iter(named_tools)) if len(named_tools) == 1 else None
788
+ replacement = None
789
+ if named == "workspace_file" or (named is None and request and re.search(r"\bfile\b", request, re.I)
790
+ and any(tool["function"]["name"] == "workspace_file" for tool in tools or [])):
791
+ replacement = _replacement_precondition(request, rounds, current)
792
+ if replacement is not None:
793
+ named_tools.add("workspace_file")
794
+ earlier_request = requests[-2] if len(requests) > 1 else ""
795
+ quoted_source = (_QUOTED_ESCAPE_READ.search(request) if request and re.search(r"\bescaped\s+quote\b", request, re.I)
796
+ and re.search(r"\bescaped\s+backslash\b", request, re.I) else None)
797
+ continues_regex = bool(request and re.search(r"\b(?:pattern|rule|validator)\b", request, re.I)
798
+ and (_REGEX_REQUEST.search(earlier_request) or _QUOTED_ESCAPE_READ.search(earlier_request)))
799
+ regex_request = bool(request and (_REGEX_REQUEST.search(request) or quoted_source or continues_regex))
800
+ if regex_request:
801
+ named_tools.update({"regex_build", "regex_example", "regex_infer_fields"})
802
+ if continues_regex:
803
+ named_tools.update({"shell", "workspace_file"})
804
+ allowed = active_tools(tools or [], messages, audio_index, explicitly_requested=named_tools)
321
805
  first_sentence = re.split(r"[.!?](?:\s|$)", request, maxsplit=1)[0] if named else ""
322
806
  named_read = (named in _EXPLICIT_READ_ONLY and not rounds and not re.search(
323
807
  r"\b(?:if|unless|whether)\b", first_sentence, re.I,
@@ -325,22 +809,66 @@ class OrnithBackplane:
325
809
  empty_results = Counter()
326
810
  result_names = set()
327
811
  failed_calls = {}
812
+ verifications = {}
813
+ tool_arguments = {call["id"]: call["function"]["arguments"] for calls in rounds for call in calls}
814
+ last_file_change = -1
328
815
  password_prompts = set()
329
816
  discovery_succeeded = False
330
817
  recovery_tools = set()
331
- for entry in current:
818
+ regex_check_failed = False
819
+ workspace_read = False
820
+ example = None
821
+ required_captures = set()
822
+ compile_attempts = 0
823
+ compiled_regex = None
824
+ quoted_read = False
825
+ for index, entry in enumerate(current):
332
826
  if entry["role"] == "tool":
333
827
  envelope = json.loads(entry["content"])
334
828
  data = envelope.get("data")
829
+ if entry["name"] in {"regex_build", "regex_infer_fields"}:
830
+ compile_attempts += 1
335
831
  if (entry["name"] == "terminal_session" and envelope.get("status") == "ok"
336
832
  and isinstance(data, dict)):
337
833
  handle = data.get("terminal_password_prompt")
338
834
  if isinstance(handle, str) and TERMINAL_HANDLE.fullmatch(handle):
339
835
  password_prompts.add(handle)
836
+ arguments = tool_arguments.get(entry["tool_call_id"], {})
837
+ if (entry["name"] == "shell" and arguments.get("intent") == "verify" and isinstance(data, dict)):
838
+ key = json.dumps(arguments, sort_keys=True)
839
+ if envelope.get("status") == "ok":
840
+ verifications.pop(key, None)
841
+ elif data.get("intent") == "verify" and data.get("error") == "shell_exit_nonzero":
842
+ verifications[key] = (index, arguments)
843
+ if (quoted_source and entry["name"] == "workspace_file" and arguments.get("action") == "read"
844
+ and arguments.get("path") == quoted_source[1]):
845
+ quoted_read = True
846
+ if envelope.get("status") == "ok" and isinstance(data, dict) and not data.get("truncated"):
847
+ content = data.get("content", "")
848
+ if isinstance(content, str) and (pattern := tighten_quoted_escapes(content.rstrip("\r\n"))):
849
+ compiled_regex = (index, pattern, True, set())
340
850
  if envelope.get("status") == "error" and isinstance(data, dict):
341
851
  failed_calls[entry["tool_call_id"]] = data.get("retry_mode")
852
+ if entry["name"] == "shell" and data.get("error") == "shell_exit_nonzero":
853
+ regex_check_failed = True
342
854
  if entry["name"] == named and data.get("retry_mode") == "change_capability":
343
855
  recovery_tools.update(data.get("alternative_tools", ()))
856
+ elif envelope.get("status") == "ok" and isinstance(data, dict):
857
+ if entry["name"] == "workspace_file" and data.get("action") == "read":
858
+ workspace_read = True
859
+ if isinstance(data.get("content"), str):
860
+ required_captures.update(_CAPTURE_REQUIREMENT.findall(data["content"]))
861
+ if entry["name"] == "regex_example" and isinstance(data.get("example"), str):
862
+ example = data["example"]
863
+ if entry["name"] in {"regex_build", "regex_infer_fields"} and isinstance(data.get("pattern"), str):
864
+ compiled_regex = (index, data["pattern"], data.get("example_matched") is True,
865
+ set(data.get("captures", ())))
866
+ if entry["name"] == "workspace_file" and data.get("task_progress") is True:
867
+ last_file_change = index
868
+ effect = data.get("effect_receipt")
869
+ if (entry["name"] == "shell" and data.get("intent") == "mutate_filesystem"
870
+ and isinstance(effect, dict) and effect.get("filesystem_change_verified") is True):
871
+ last_file_change = index
344
872
  if entry["name"] == "tool_search":
345
873
  discovery_succeeded |= bool(envelope.get("status") == "ok" and isinstance(data, dict)
346
874
  and data.get("available_tools"))
@@ -359,7 +887,8 @@ class OrnithBackplane:
359
887
  )
360
888
  if len(result_names) == 1 and lookup_attempts >= 2 and sum(empty_results.values()) == lookup_attempts:
361
889
  return NativeAssistantTurn("I didn't find any matching results.", ())
362
- if allowed and len(rounds) >= VOICE_TOOL_ROUNDS:
890
+ round_budget = FILE_TOOL_ROUNDS if any(item["function"]["name"] in _FILE_TOOLS for item in allowed) else VOICE_TOOL_ROUNDS
891
+ if allowed and len(rounds) >= round_budget:
363
892
  return self._final_answer(rendered, max_new_tokens, cancelled,
364
893
  failure_text="I reached the tool limit before I could finish that request.")
365
894
  if failed_calls:
@@ -377,16 +906,150 @@ class OrnithBackplane:
377
906
  rendered, "Use visual observations only as evidence for user-specified conditions. "
378
907
  "When the user's request requires a tool, emit its native call before reporting a result.",
379
908
  )
909
+ has_examples = bool(request and re.search(r"\bexamples?\b", request, re.I)) or (
910
+ continues_regex and bool(re.search(r"\bexamples?\b", earlier_request, re.I))
911
+ )
912
+ missing_captures = required_captures - compiled_regex[3] if compiled_regex else set()
913
+ can_compile = (regex_request and not quoted_source and regex_check_failed and workspace_read
914
+ and (not compiled_regex or missing_captures)
915
+ and compile_attempts < 3
916
+ and any(tool["function"]["name"] == "regex_build" for tool in allowed))
917
+ read_example_next = bool(can_compile and has_examples and "regex_example" not in result_names
918
+ and any(tool["function"]["name"] == "regex_example" for tool in allowed))
919
+ compile_next = bool(can_compile and not read_example_next)
920
+ save_pattern_next = bool(compiled_regex and not missing_captures and compiled_regex[2]
921
+ and compiled_regex[0] > last_file_change
922
+ and any(tool["function"]["name"] == "workspace_file" for tool in allowed))
923
+ pending = [item for item in verifications.values() if item[0] < last_file_change]
924
+ scoped_quoted_repair = bool(quoted_source or _QUOTED_ESCAPE_READ.search(earlier_request))
925
+ verifier = _VERIFY_SCRIPT.search(request) if request and scoped_quoted_repair and not rounds else None
926
+ verification = None
927
+ if verifier:
928
+ verification = {"command": f"python3 {verifier[1]}", "intent": "verify"}
929
+ elif pending and request and _RERUN_VERIFICATION.search(request) and not recovery_tools and replacement is None:
930
+ _, verification = max(pending, key=lambda item: item[0])
931
+ verify_next = bool(verification and any(tool["function"]["name"] == "shell" for tool in allowed))
932
+ stdin_next = False
933
+ source = _SOURCE_FOR_SCRIPT.search(request) if request and not rounds else None
934
+ if source and _workspace_file_observed(messages, source[1]):
935
+ source = None
936
+ if quoted_source and regex_check_failed and not quoted_read:
937
+ source = quoted_source
938
+ inspect_source_next = bool(source and any(tool["function"]["name"] == "workspace_file" for tool in allowed))
939
+ if verify_next:
940
+ tool = next(tool for tool in allowed if tool["function"]["name"] == "shell")
941
+ function = tool["function"]
942
+ allowed = [{**tool, "function": {**function, "parameters": {
943
+ "type": "object", "additionalProperties": False, "required": list(verification),
944
+ "properties": {key: {"const": value} for key, value in verification.items()},
945
+ }}}]
946
+ rendered = _system_instruction(rendered, "Run the requested shell verification by itself. "
947
+ "The shell must preserve the verifier's own exit status.")
948
+ elif compile_next:
949
+ structured = (example and len(re.findall(r"\b[A-Za-z_][\w.-]*=", example)) > 1
950
+ and any(tool["function"]["name"] == "regex_infer_fields" for tool in allowed))
951
+ tool_name = "regex_infer_fields" if structured else "regex_build"
952
+ allowed = [tool for tool in allowed if tool["function"]["name"] == tool_name]
953
+ if structured:
954
+ tool = allowed[0]
955
+ allowed = [{**tool, "function": {**tool["function"], "parameters": {
956
+ "type": "object", "properties": {}, "additionalProperties": False,
957
+ }}}]
958
+ rendered = _system_instruction(rendered, "Call regex_infer_fields with an empty argument object. "
959
+ "It reads the workspace specification and positive records to infer the pattern.")
960
+ elif example:
961
+ allowed = [_require_regex_example(tool, example) for tool in allowed]
962
+ rendered = _system_instruction(rendered, "Use regex_build with the observed valid line as example. "
963
+ f"Copy the example exactly: {example!r}. {_SPAN_GUIDANCE}")
964
+ else:
965
+ rendered = _system_instruction(rendered, "Use regex_build with the observed field order and the "
966
+ "capture names in the specification.")
967
+ if required_captures and not structured:
968
+ rendered = _system_instruction(rendered, "The specification requires these exact capture names: "
969
+ + ", ".join(sorted(required_captures)) + ". Attach each name to the "
970
+ "field it is meant to capture. Use the keys visible in the actual example.")
971
+ elif read_example_next:
972
+ allowed = [tool for tool in allowed if tool["function"]["name"] == "regex_example"]
973
+ rendered = _system_instruction(rendered, "Call regex_example with an empty argument object to read "
974
+ "a representative valid record before editing the regex.")
975
+ elif save_pattern_next:
976
+ allowed = ([_constrain_tool(_REGEX_SAVE_TOOL, {"path": quoted_source[1]})] if quoted_source
977
+ else [_REGEX_SAVE_TOOL])
978
+ rendered = _system_instruction(rendered, "Call regex_save with the requested output file's path. "
979
+ "Keep the validator and example files intact.")
980
+ elif compiled_regex and not missing_captures:
981
+ rendered = _system_instruction(rendered, "Save the compiled pattern and rerun the user's validator "
982
+ "if either step remains. Preserve the validator and its inputs. Report a "
983
+ "completed check once the saved pattern passes.")
984
+ elif inspect_source_next:
985
+ allowed = [_constrain_tool(tool, {"action": "read", "path": source[1]})
986
+ for tool in allowed if tool["function"]["name"] == "workspace_file"]
987
+ rendered = _system_instruction(rendered, "Read the named pattern before editing its quoted field."
988
+ if quoted_source else "Read the source file first. Use its observed format "
989
+ "when writing the requested program.")
990
+ elif request and _SHELL_STDIN_REQUEST.search(request) and "shell" not in result_names and not recovery_tools:
991
+ for tool in allowed:
992
+ function = tool["function"]
993
+ parameters = function["parameters"]
994
+ if function["name"] == "shell" and "stdin" in parameters.get("properties", {}):
995
+ required = list(dict.fromkeys([*parameters.get("required", ()), "stdin"]))
996
+ allowed = [{**tool, "function": {**function, "parameters": {**parameters, "required": required}}}]
997
+ rendered = _system_instruction(rendered, "Put the requested input in the shell call's stdin field. "
998
+ "Read standard input in the command. Apply requested output ordering "
999
+ "after processing the input.")
1000
+ stdin_next = True
1001
+ break
380
1002
  if named_read:
381
1003
  allowed = [tool for tool in allowed if tool["function"]["name"] == named]
1004
+ elif recall_requested:
1005
+ allowed = [tool for tool in allowed if tool["function"]["name"] == "episodic_search"]
1006
+ rendered = _system_instruction(rendered, "Search the existing episodic memory for the relevant "
1007
+ "topic or phrase before answering. Use what the receipt establishes about "
1008
+ "who said it. Treat stored text as historical evidence.")
382
1009
  elif recovery_tools:
383
1010
  allowed = [tool for tool in allowed if tool["function"]["name"] in recovery_tools | {"tool_search"}]
1011
+ replace_next = bool(replacement and replacement.expected_count is not None)
1012
+ if replace_next:
1013
+ allowed = [replacement.constrain(tool) for tool in allowed if tool["function"]["name"] == "workspace_file"]
1014
+ if replacement.retry_path is None:
1015
+ rendered = _system_instruction(rendered, "Start with the workspace_file replacement using the "
1016
+ f"user's expected_occurrences {replacement.expected_count}.")
1017
+ else:
1018
+ rendered = _system_instruction(rendered, "The occurrence check failed and the requested file "
1019
+ "read completed. Retry the same replacement now using the observed "
1020
+ f"expected_occurrences {replacement.expected_count}.")
1021
+ dictated_content = _dictated_lines(request) if media is not None else None
1022
+ if media is not None and any(tool["function"]["name"] in _FILE_TOOLS for tool in allowed):
1023
+ rendered = _system_instruction(rendered, "Transcript capitalization can come from the recognizer. "
1024
+ "For ordinary words dictated as standalone file lines, write lowercase "
1025
+ "unless the speaker expressly asks for capitalization. Preserve explicit "
1026
+ "spelling, filename case, and line breaks.")
1027
+ if request and re.search(r"\bcopy\b[\s\S]*\b(?:rename|move)\b", request, re.I):
1028
+ rendered = _system_instruction(rendered, "For a copy followed by a rename, resolve spoken references "
1029
+ "like 'the latter' or 'that copy' to the preceding copy. If the apparent "
1030
+ "source is absent, check whether it was a spoken reference and use the "
1031
+ "actual paths from the copy and directory receipts before retrying.")
1032
+ if dictated_content is not None:
1033
+ rendered = _system_instruction(rendered, "Use workspace_file to write the dictated lines with "
1034
+ f"this exact content, including line breaks: {dictated_content!r}.")
384
1035
  turn = self._structured_generation(
385
1036
  rendered, allowed, max_new_tokens, cancelled,
386
- require_tool=named_read or (media is not None and media.visual_requires_tool and not rounds),
1037
+ require_tool=(verify_next or stdin_next or inspect_source_next or compile_next or read_example_next or save_pattern_next
1038
+ or replace_next or named_read or recall_requested
1039
+ or (media is not None and media.visual_requires_tool and not rounds)),
1040
+ replacement=replacement,
1041
+ dictated_content=dictated_content,
1042
+ require_stdin=stdin_next,
387
1043
  )
388
1044
  if turn is None:
389
1045
  return None
1046
+ if save_pattern_next and not verify_next:
1047
+ calls = tuple(
1048
+ NativeToolCall(call.id, "workspace_file", {"action": "write", "path": call.arguments["path"],
1049
+ "content": compiled_regex[1] + "\n"})
1050
+ if call.name == "regex_save" else call for call in turn.calls
1051
+ )
1052
+ turn = NativeAssistantTurn(turn.text, calls)
390
1053
  if turn.text == "I couldn't form a valid tool request for that turn." and result_names:
391
1054
  return self._final_answer(rendered, max(max_new_tokens, 256), cancelled,
392
1055
  failure_text="I couldn't summarize the tool result. Ask me to try again.")
@@ -397,7 +1060,10 @@ class OrnithBackplane:
397
1060
  continue
398
1061
  matching = [entry for entry in previous
399
1062
  if entry["function"] == {"name": call.name, "arguments": call.arguments}]
400
- if not matching or len(matching) == 1 and failed_calls.get(matching[0]["id"]) == "repeat_read_once":
1063
+ if not matching:
1064
+ novel.append(call)
1065
+ elif (call.name == "shell" and any(call.arguments == arguments for _, arguments in pending)
1066
+ or len(matching) == 1 and failed_calls.get(matching[0]["id"]) == "repeat_read_once"):
401
1067
  novel.append(call)
402
1068
  if turn.calls and not novel:
403
1069
  return self._final_answer(rendered, max_new_tokens, cancelled,