phosphor-harness 0.4.4 → 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.
- package/README.md +27 -4
- package/package.json +33 -10
- package/quickstart.sh +3 -3
- package/scripts/context_size.py +28 -0
- package/scripts/run_service.sh +8 -0
- package/scripts/run_transcription_worker.py +91 -0
- package/sophon_harness/cli.py +4 -0
- package/sophon_harness/duplex_voice.py +392 -0
- package/sophon_harness/episode_recording.py +59 -0
- package/sophon_harness/ornith.py +596 -20
- package/sophon_harness/portal_server.py +87 -3
- package/sophon_harness/pulse_audio.py +77 -0
- package/sophon_harness/regex_tools.py +337 -0
- package/sophon_harness/tools.py +52 -12
- package/sophon_harness/voice.py +46 -16
package/sophon_harness/ornith.py
CHANGED
|
@@ -3,14 +3,19 @@
|
|
|
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
|
|
12
16
|
from urllib.parse import urlsplit
|
|
13
17
|
import wave
|
|
18
|
+
from uuid import uuid4
|
|
14
19
|
|
|
15
20
|
import httpx
|
|
16
21
|
from jsonschema import Draft202012Validator
|
|
@@ -20,17 +25,89 @@ from training_suite.models.native_turn import NativeAssistantTurn, NativeToolCal
|
|
|
20
25
|
from training_suite.sophon_speech import validate_speech_text
|
|
21
26
|
from training_suite.training.audio_bridge_training import MEDIA_INSTRUCTION, MEDIA_SYSTEM_PROMPT
|
|
22
27
|
|
|
23
|
-
from .
|
|
28
|
+
from .regex_tools import tighten_quoted_escapes
|
|
29
|
+
from .tools import FILE_TOOL_ROUNDS, VOICE_TOOL_ROUNDS, active_tools, current_turn, requested_tools
|
|
24
30
|
from .terminal_input import PASSWORD_REQUEST, TERMINAL_HANDLE
|
|
25
31
|
|
|
26
32
|
FAILURE_INSTRUCTIONS = (
|
|
27
33
|
"Use the tool receipt to diagnose failure. For correct_arguments, fix the evidenced problem. "
|
|
28
34
|
"For change_capability, consider the offered tools. For repeat_read_once, the same read may be retried once. "
|
|
35
|
+
"After a verified file change, rerun a failed shell verification to check the correction. "
|
|
29
36
|
"For needs_location, ask for an updated location. For report_failure, state what failed or use an "
|
|
30
37
|
"independent permitted tool when appropriate. Respect access controls. "
|
|
31
38
|
"Speak plain text and omit URLs, markup, and command syntax."
|
|
32
39
|
)
|
|
33
40
|
_EXPLICIT_READ_ONLY = {"safe_math_eval", "scan_wifi_networks", "get_current_time", "get_system_snapshot", "capture_view"}
|
|
41
|
+
_FILE_TOOLS = {"shell", "workspace_file", "regex_build", "regex_example", "regex_infer_fields", "regex_save"}
|
|
42
|
+
_REGEX_SAVE_TOOL = {"type": "function", "function": {
|
|
43
|
+
"name": "regex_save",
|
|
44
|
+
"description": "Write the compiled pattern from this turn to the requested workspace file.",
|
|
45
|
+
"parameters": {"type": "object", "required": ["path"], "additionalProperties": False,
|
|
46
|
+
"properties": {"path": {"type": "string", "minLength": 1}}},
|
|
47
|
+
}}
|
|
48
|
+
_LITERAL_REPLACEMENT = re.compile(r"\breplace\s+([\w-]+)\s+with\s+([\w-]+)\b", re.I)
|
|
49
|
+
_COUNT_WORDS = dict(zip("one two three four five six seven eight nine ten".split(), range(1, 11)))
|
|
50
|
+
_ORDINALS = dict(zip("first second third fourth fifth sixth seventh eighth ninth tenth".split(), range(1, 11)))
|
|
51
|
+
_DICTATED_LINES = re.compile(
|
|
52
|
+
r"\b(\d{1,2}|" + "|".join(_COUNT_WORDS) + r")\s+(?:(?:newline[- ]|newly )terminated\s+)?lines\s*[:.]\s*"
|
|
53
|
+
r"([A-Za-z-]+(?:\s*,\s*[A-Za-z-]+)+)\s*[.!?]", re.I,
|
|
54
|
+
)
|
|
55
|
+
_DICTATED_REPEAT = re.compile(
|
|
56
|
+
r"\bthe first\s+(\d{1,2}|" + "|".join(_COUNT_WORDS) + r")\s+say\s+([A-Za-z-]+)[.?!]", re.I,
|
|
57
|
+
)
|
|
58
|
+
_DICTATED_ORDINAL = re.compile(
|
|
59
|
+
r"\bthe\s+(" + "|".join(_ORDINALS) + r")\s+says?\s+([A-Za-z-]+)[.?!]", re.I,
|
|
60
|
+
)
|
|
61
|
+
_REQUESTED_OCCURRENCES = re.compile(
|
|
62
|
+
r"\b(?:expected\s+count(?:\s+of)?|requiring(?:\s+a\s+count\s+of)?|with\s+exactly|count\s+of)"
|
|
63
|
+
r"\s+(?:exactly\s+)?(\d{1,4}|" + "|".join(_COUNT_WORDS) + r")\b", re.I,
|
|
64
|
+
)
|
|
65
|
+
_OCCURRENCE_ERROR = re.compile(r"old_text occurrence mismatch: expected \d+, found (\d+)\Z")
|
|
66
|
+
_REGEX_REQUEST = re.compile(r"\b(?:regex|regular expression)\b", re.I)
|
|
67
|
+
_RERUN_VERIFICATION = re.compile(r"\b(?:re[- ]?run|repeat)\b[^.!?\n]{0,160}"
|
|
68
|
+
r"\b(?:validat\w*|verif\w*|check\w*|test\w*)\b", re.I)
|
|
69
|
+
_SHELL_STDIN_REQUEST = re.compile(r"\bstdin\s+(?:argument|field|parameter)\b", re.I)
|
|
70
|
+
_DIRECT_DATE = re.compile(
|
|
71
|
+
r"(?:what(?:'s| is)|tell me|can you tell me) (?:the )?(?:current |today's )?date(?: today| right now)?"
|
|
72
|
+
r"|(?:can you tell me )?what (?:day|date) is (?:it(?: today)?|today)"
|
|
73
|
+
r"|(?:can you tell me )?what (?:the date is today|today's date is)", re.I,
|
|
74
|
+
)
|
|
75
|
+
_RECALL_REQUEST = re.compile(
|
|
76
|
+
r"\b(?:do you remember|can you recall|what did (?:i|we) (?:say|discuss|talk about|tell you)|"
|
|
77
|
+
r"(?:find|search|recall) (?:our |my )?(?:past|earlier|previous) (?:conversation|discussion))\b", re.I,
|
|
78
|
+
)
|
|
79
|
+
_LITERAL_STDIN_PIPE = re.compile(r"\A\s*printf\s+'([^']+)'\s*\|\s*(?![|&])")
|
|
80
|
+
_SOURCE_FOR_SCRIPT = re.compile(r"\b(?:create|write)\s+[\w./-]+\.py\s+(?:to|that)\s+reads?\s+"
|
|
81
|
+
r"([\w./-]+\.[A-Za-z0-9]{1,12})\b", re.I)
|
|
82
|
+
_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)
|
|
83
|
+
_VERIFY_SCRIPT = re.compile(r"\brun\s+(?:python3\s+|the\s+unchanged\s+)([\w./-]+\.py)\b", re.I)
|
|
84
|
+
_CAPTURE_REQUIREMENT = re.compile(
|
|
85
|
+
r"\b(?:named\s+group|capture\b[^.?!\n]{0,90}?\bgroup)\s+[`'\"]?([A-Za-z_][A-Za-z0-9_]{0,39})", re.I,
|
|
86
|
+
)
|
|
87
|
+
_SPAN_GUIDANCE = (
|
|
88
|
+
"In example mode, omit all literal separators, spaces, and fixed fields. Each part covers an entire varying value. "
|
|
89
|
+
"Example line: SKU=DX-914 QTY=37 AREA=west TAG='ready'. To allow different SKUs, quantities, east or west, "
|
|
90
|
+
"and single-quoted tags, send these parts: "
|
|
91
|
+
'[{"kind":"shape","span":"DX-914","value":"AA-000","capture":"sku"},'
|
|
92
|
+
'{"kind":"unsigned_integer","span":"37","capture":"qty"},'
|
|
93
|
+
'{"kind":"choice","span":"west","choices":["east","west"]},'
|
|
94
|
+
'{"kind":"quoted_text","span":"\'ready\'","value":"\'"}]. '
|
|
95
|
+
"A shape is a mask, not regex syntax. The compiler inserts fixed text from the example. For a date use "
|
|
96
|
+
"date_format and give the corresponding strftime layout. A quoted span includes its opening and closing quotes."
|
|
97
|
+
)
|
|
98
|
+
_FILE_TOOL_INSTRUCTIONS = (
|
|
99
|
+
"For file and shell tasks, use relative workspace paths unless the user supplied an absolute path. "
|
|
100
|
+
"The receipt's artifact paths are logs, not the shell working directory. Keep tool calls concise. "
|
|
101
|
+
"Interpret dictated slash, dot, and letter names as filename punctuation and spelling when clear. "
|
|
102
|
+
"When a check fails, use the specification and the reported failing case to make a correction, "
|
|
103
|
+
"then rerun the exact check. Once you have the relevant evidence, make the requested edit without further reads. "
|
|
104
|
+
"For a regex, construct it in the order of the input fields. Use the requested capture names only on the "
|
|
105
|
+
"corresponding fields and check a valid and invalid example before reporting success. "
|
|
106
|
+
"When available, use regex_build for typed components and quoted-text escaping, then save the returned pattern. "
|
|
107
|
+
"Use the verify intent for a shell check. A standard checksum manifest includes both the digest and filename. "
|
|
108
|
+
"When checking a saved SHA-256 manifest, pass that file to sha256sum -c in a separate call. "
|
|
109
|
+
"Keep source files intact unless the user asks to modify them. Report what the final receipt actually shows."
|
|
110
|
+
)
|
|
34
111
|
|
|
35
112
|
|
|
36
113
|
@dataclass
|
|
@@ -68,12 +145,49 @@ class OrnithTokenLimit(ValueError):
|
|
|
68
145
|
"""The response ran out of generation tokens before it could finish."""
|
|
69
146
|
|
|
70
147
|
|
|
71
|
-
|
|
148
|
+
class OrnithTurnInterrupted(RuntimeError):
|
|
149
|
+
"""The acoustic session superseded an in-flight request."""
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _wave_bytes(pcm: bytes) -> bytes:
|
|
72
153
|
output = BytesIO()
|
|
73
154
|
with wave.open(output, "wb") as wav:
|
|
74
155
|
wav.setparams((1, 2, 16_000, 0, "NONE", "not compressed"))
|
|
75
156
|
wav.writeframes(pcm)
|
|
76
|
-
return
|
|
157
|
+
return output.getvalue()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _audio_part(pcm: bytes) -> dict:
|
|
161
|
+
return {"type": "input_audio", "input_audio": {"data": base64.b64encode(_wave_bytes(pcm)).decode("ascii")}}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _spoken_extensions(text):
|
|
165
|
+
if re.search(r"\b(?:upper\s*case|case[- ]sensitive|including the hyphen|verbatim)\b", text, re.I):
|
|
166
|
+
return text
|
|
167
|
+
return re.sub(r"(\bdot\s+|\.)sha-256\b", r"\g<1>sha256", text, flags=re.I)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _dictated_lines(text):
|
|
171
|
+
if (not text or not re.search(r"\b(?:write|create|text file)\b", text, re.I)
|
|
172
|
+
or not re.search(r"\b(?:newline|new line|terminate|terminated)\b", text, re.I)
|
|
173
|
+
or re.search(r"\b(?:upper\s*case|capitalize|case[- ]sensitive|verbatim)\b", text, re.I)):
|
|
174
|
+
return None
|
|
175
|
+
if listed := _DICTATED_LINES.search(text):
|
|
176
|
+
count = int(listed[1]) if listed[1].isdecimal() else _COUNT_WORDS[listed[1].lower()]
|
|
177
|
+
items = [item.strip().lower() for item in listed[2].split(",")]
|
|
178
|
+
if len(items) == count:
|
|
179
|
+
return "\n".join(items) + "\n"
|
|
180
|
+
if repeated := _DICTATED_REPEAT.search(text):
|
|
181
|
+
count = int(repeated[1]) if repeated[1].isdecimal() else _COUNT_WORDS[repeated[1].lower()]
|
|
182
|
+
positions = {index: repeated[2].lower() for index in range(1, count + 1)}
|
|
183
|
+
for ordinal, word in _DICTATED_ORDINAL.findall(text):
|
|
184
|
+
index = _ORDINALS[ordinal.lower()]
|
|
185
|
+
if index in positions:
|
|
186
|
+
return None
|
|
187
|
+
positions[index] = word.lower()
|
|
188
|
+
if len(positions) > count and set(positions) == set(range(1, len(positions) + 1)):
|
|
189
|
+
return "\n".join(positions[index] for index in range(1, len(positions) + 1)) + "\n"
|
|
190
|
+
return None
|
|
77
191
|
|
|
78
192
|
|
|
79
193
|
def _arguments(raw: str) -> dict:
|
|
@@ -104,16 +218,187 @@ def _system_instruction(messages, text):
|
|
|
104
218
|
return [{"role": "system", "content": text}, *messages]
|
|
105
219
|
|
|
106
220
|
|
|
221
|
+
def _compact_completed_turns(messages):
|
|
222
|
+
last_user = max((i for i, message in enumerate(messages) if message["role"] == "user"), default=0)
|
|
223
|
+
earlier = messages[:last_user]
|
|
224
|
+
compact = [message for message in earlier
|
|
225
|
+
if message["role"] != "tool" and not message.get("tool_calls")]
|
|
226
|
+
if len(compact) != len(earlier):
|
|
227
|
+
return [*compact, *messages[last_user:]]
|
|
228
|
+
user_turns = [i for i, message in enumerate(earlier) if message["role"] == "user"]
|
|
229
|
+
if not user_turns:
|
|
230
|
+
return messages
|
|
231
|
+
first_user = user_turns[0]
|
|
232
|
+
next_user = user_turns[1] if len(user_turns) > 1 else last_user
|
|
233
|
+
return [*messages[:first_user], *messages[next_user:]]
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _context_rejected(response):
|
|
237
|
+
if response.status_code != 400:
|
|
238
|
+
return False
|
|
239
|
+
try:
|
|
240
|
+
message = response.json()["error"]["message"]
|
|
241
|
+
except (ValueError, KeyError, TypeError):
|
|
242
|
+
return False
|
|
243
|
+
return isinstance(message, str) and "exceeds the available context size" in message
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _shell_context(content):
|
|
247
|
+
envelope = json.loads(content)
|
|
248
|
+
data = envelope.get("data")
|
|
249
|
+
if isinstance(data, dict) and "output_artifacts" in data and not any(
|
|
250
|
+
data.get(key) for key in ("stdout_truncated", "stderr_truncated", "truncated")
|
|
251
|
+
):
|
|
252
|
+
data.pop("output_artifacts")
|
|
253
|
+
return json.dumps(envelope)
|
|
254
|
+
return content
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _shell_stdin_arguments(arguments):
|
|
258
|
+
data = arguments.get("stdin")
|
|
259
|
+
if not isinstance(data, str) or not data.strip():
|
|
260
|
+
raise ValueError("put the requested input in stdin and read from standard input")
|
|
261
|
+
command = arguments["command"]
|
|
262
|
+
literal = data.rstrip("\n")
|
|
263
|
+
if "\n" not in literal or (literal not in command and literal.replace("\n", r"\n") not in command):
|
|
264
|
+
return arguments
|
|
265
|
+
prefix = _LITERAL_STDIN_PIPE.match(command)
|
|
266
|
+
if prefix and command[prefix.end():].strip() and not any(symbol in data for symbol in ("%", "\\")):
|
|
267
|
+
printed = prefix[1].replace(r"\n", "\n")
|
|
268
|
+
if printed in {data, data + "\n"}:
|
|
269
|
+
return {**arguments, "command": command[prefix.end():], "stdin": printed}
|
|
270
|
+
raise ValueError("put the input only in stdin and have the command read from standard input")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _current_date_turn(receipts):
|
|
274
|
+
for entry in reversed(receipts):
|
|
275
|
+
if entry["role"] == "tool" and entry.get("name") == "get_current_time":
|
|
276
|
+
envelope = json.loads(entry["content"])
|
|
277
|
+
try:
|
|
278
|
+
if envelope.get("status") == "ok":
|
|
279
|
+
current = date.fromisoformat(envelope["data"]["date"])
|
|
280
|
+
return NativeAssistantTurn(f"Today is {current:%A, %B} {current.day}, {current.year}.", ())
|
|
281
|
+
except (TypeError, ValueError, KeyError):
|
|
282
|
+
pass
|
|
283
|
+
return NativeAssistantTurn("I couldn't read the current date from the device clock.", ())
|
|
284
|
+
return NativeAssistantTurn("", (NativeToolCall(uuid4().hex, "get_current_time", {}),))
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
@dataclass(frozen=True)
|
|
288
|
+
class _ReplacementPrecondition:
|
|
289
|
+
old: str
|
|
290
|
+
new: str
|
|
291
|
+
expected_count: int | None
|
|
292
|
+
retry_path: str | None = None
|
|
293
|
+
|
|
294
|
+
def validate(self, call):
|
|
295
|
+
args = call.arguments
|
|
296
|
+
if call.name != "workspace_file" or args.get("action") != "replace":
|
|
297
|
+
return
|
|
298
|
+
if (args.get("old_text"), args.get("new_text")) != (self.old, self.new):
|
|
299
|
+
raise ValueError(f"use the requested literal old_text {self.old!r} and new_text {self.new!r}")
|
|
300
|
+
if self.expected_count is not None and args.get("expected_occurrences") != self.expected_count:
|
|
301
|
+
raise ValueError(f"set expected_occurrences to {self.expected_count}")
|
|
302
|
+
|
|
303
|
+
def constrain(self, definition):
|
|
304
|
+
values = {"action": "replace", "old_text": self.old, "new_text": self.new,
|
|
305
|
+
"expected_occurrences": self.expected_count}
|
|
306
|
+
if self.retry_path is not None:
|
|
307
|
+
values["path"] = self.retry_path
|
|
308
|
+
return _constrain_tool(definition, values)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _constrain_tool(definition, values):
|
|
312
|
+
function = definition["function"]
|
|
313
|
+
parameters = function["parameters"]
|
|
314
|
+
properties = {**parameters.get("properties", {}),
|
|
315
|
+
**{key: {"const": value} for key, value in values.items()}}
|
|
316
|
+
required = list(dict.fromkeys([*parameters.get("required", ()), *values]))
|
|
317
|
+
return {**definition, "function": {**function, "parameters": {
|
|
318
|
+
**parameters, "properties": properties, "required": required,
|
|
319
|
+
}}}
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _require_regex_example(definition, example):
|
|
323
|
+
function = definition["function"]
|
|
324
|
+
parameters = function["parameters"]
|
|
325
|
+
parts = parameters["properties"]["parts"]
|
|
326
|
+
item = parts["items"]
|
|
327
|
+
return {**definition, "function": {**function, "parameters": {
|
|
328
|
+
**parameters, "required": [*parameters["required"], "example"],
|
|
329
|
+
"properties": {**parameters["properties"], "example": {"const": example}, "parts": {**parts, "items": {
|
|
330
|
+
**item, "required": [*item["required"], "span"],
|
|
331
|
+
}}},
|
|
332
|
+
}}}
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _workspace_file_observed(messages, path):
|
|
336
|
+
reads_or_writes = {call["id"] for message in messages for call in (message.get("tool_calls") or ())
|
|
337
|
+
if call["function"]["name"] == "workspace_file"
|
|
338
|
+
and call["function"]["arguments"].get("path") == path
|
|
339
|
+
and call["function"]["arguments"].get("action") in {"read", "write"}}
|
|
340
|
+
return any(message.get("role") == "tool" and message.get("tool_call_id") in reads_or_writes
|
|
341
|
+
and json.loads(message["content"]).get("status") == "ok" for message in messages)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _replacement_precondition(request, rounds, current):
|
|
345
|
+
if not request or not (literal := _LITERAL_REPLACEMENT.search(request)):
|
|
346
|
+
return None
|
|
347
|
+
count = _REQUESTED_OCCURRENCES.search(request[literal.end():literal.end() + 240])
|
|
348
|
+
if not count:
|
|
349
|
+
return None
|
|
350
|
+
value = count[1].lower()
|
|
351
|
+
expected = int(value) if value.isdecimal() else _COUNT_WORDS[value]
|
|
352
|
+
if not 1 <= expected <= 1000:
|
|
353
|
+
return None
|
|
354
|
+
calls_by_id = {call["id"]: call["function"]["arguments"] for calls in rounds for call in calls
|
|
355
|
+
if call["function"]["name"] == "workspace_file"}
|
|
356
|
+
if not any(args.get("action") == "replace" for args in calls_by_id.values()):
|
|
357
|
+
return _ReplacementPrecondition(*literal.groups(), expected)
|
|
358
|
+
pending = None
|
|
359
|
+
retry = None
|
|
360
|
+
if re.search(r"\b(?:retry|repeat|try again)\b", request, re.I):
|
|
361
|
+
for item in current:
|
|
362
|
+
if item["role"] != "tool" or item.get("name") != "workspace_file":
|
|
363
|
+
continue
|
|
364
|
+
args = calls_by_id.get(item["tool_call_id"], {})
|
|
365
|
+
result = json.loads(item["content"])
|
|
366
|
+
data = result.get("data") or {}
|
|
367
|
+
if args.get("action") == "replace":
|
|
368
|
+
pending = None
|
|
369
|
+
retry = None
|
|
370
|
+
if result.get("status") == "error" and data.get("error") == "ToolInputError":
|
|
371
|
+
actual = _OCCURRENCE_ERROR.fullmatch(data.get("message", ""))
|
|
372
|
+
if actual and 1 <= int(actual[1]) <= 1000:
|
|
373
|
+
pending = (args.get("path"), int(actual[1]))
|
|
374
|
+
elif (pending and args.get("action") == "read" and args.get("path") == pending[0]
|
|
375
|
+
and result.get("status") == "ok"):
|
|
376
|
+
retry = pending
|
|
377
|
+
return _ReplacementPrecondition(*literal.groups(), retry[1], retry[0]) if retry else (
|
|
378
|
+
_ReplacementPrecondition(*literal.groups(), None)
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
|
|
107
382
|
class OrnithBackplane:
|
|
108
383
|
prior_audio = ()
|
|
384
|
+
tool_rounds = FILE_TOOL_ROUNDS
|
|
109
385
|
|
|
110
|
-
def __init__(self, url: str, model: str, *, transport=None):
|
|
386
|
+
def __init__(self, url: str, model: str, *, transcription_url=None, transport=None):
|
|
111
387
|
address = urlsplit(url)
|
|
112
388
|
if (address.scheme != "http" or address.hostname not in {"127.0.0.1", "::1"}
|
|
113
389
|
or address.username is not None or address.path not in {"", "/"} or address.query or address.fragment):
|
|
114
390
|
raise ValueError("Ornith requires an HTTP loopback server address")
|
|
391
|
+
if transcription_url is not None:
|
|
392
|
+
endpoint = urlsplit(transcription_url)
|
|
393
|
+
if (endpoint.scheme != "http" or endpoint.hostname not in {"127.0.0.1", "::1"}
|
|
394
|
+
or endpoint.username is not None or endpoint.path != "/v1/audio/transcriptions"
|
|
395
|
+
or endpoint.query or endpoint.fragment):
|
|
396
|
+
raise ValueError("transcription_url must point to a loopback audio transcription endpoint")
|
|
397
|
+
self.transcription_url = transcription_url
|
|
115
398
|
self.model = model
|
|
116
399
|
self.client = httpx.Client(base_url=url, timeout=90, trust_env=False, transport=transport)
|
|
400
|
+
self.transport = transport
|
|
401
|
+
self._cancel = ContextVar("ornith_cancel", default=None)
|
|
117
402
|
|
|
118
403
|
def __enter__(self):
|
|
119
404
|
return self
|
|
@@ -121,13 +406,50 @@ class OrnithBackplane:
|
|
|
121
406
|
def __exit__(self, *exc):
|
|
122
407
|
self.client.close()
|
|
123
408
|
|
|
409
|
+
@contextmanager
|
|
410
|
+
def interruptible(self, cancelled):
|
|
411
|
+
token = self._cancel.set(cancelled)
|
|
412
|
+
try:
|
|
413
|
+
yield
|
|
414
|
+
finally:
|
|
415
|
+
self._cancel.reset(token)
|
|
416
|
+
|
|
417
|
+
def _post(self, path, **options):
|
|
418
|
+
cancelled = self._cancel.get()
|
|
419
|
+
if cancelled is None:
|
|
420
|
+
return self.client.post(path, **options)
|
|
421
|
+
|
|
422
|
+
async def post():
|
|
423
|
+
async with httpx.AsyncClient(base_url=self.client.base_url, timeout=self.client.timeout,
|
|
424
|
+
trust_env=False, transport=self.transport) as client:
|
|
425
|
+
if cancelled.is_set():
|
|
426
|
+
raise OrnithTurnInterrupted()
|
|
427
|
+
request = asyncio.create_task(client.post(path, **options))
|
|
428
|
+
while not request.done() and not cancelled.is_set():
|
|
429
|
+
await asyncio.wait((request,), timeout=0.025)
|
|
430
|
+
if cancelled.is_set():
|
|
431
|
+
request.cancel()
|
|
432
|
+
with suppress(asyncio.CancelledError, httpx.HTTPError):
|
|
433
|
+
await request
|
|
434
|
+
raise OrnithTurnInterrupted()
|
|
435
|
+
return request.result()
|
|
436
|
+
|
|
437
|
+
return asyncio.run(post())
|
|
438
|
+
|
|
124
439
|
def _chat(self, messages, *, max_tokens, **options):
|
|
125
440
|
try:
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
441
|
+
while True:
|
|
442
|
+
response = self._post("/v1/chat/completions", json={
|
|
443
|
+
"model": self.model, "messages": messages, "max_tokens": max_tokens,
|
|
444
|
+
"chat_template_kwargs": {"enable_thinking": False}, "temperature": 0, **options,
|
|
445
|
+
})
|
|
446
|
+
if not _context_rejected(response):
|
|
447
|
+
response.raise_for_status()
|
|
448
|
+
break
|
|
449
|
+
compact = _compact_completed_turns(messages)
|
|
450
|
+
if len(compact) == len(messages):
|
|
451
|
+
response.raise_for_status()
|
|
452
|
+
messages = compact
|
|
131
453
|
choice = response.json()["choices"][0]
|
|
132
454
|
if choice["finish_reason"] == "length":
|
|
133
455
|
raise OrnithTokenLimit("the response reached its token limit")
|
|
@@ -186,8 +508,24 @@ class OrnithBackplane:
|
|
|
186
508
|
return self._recognize(pcm)["speech_transcript"]
|
|
187
509
|
|
|
188
510
|
def _perceive(self, turn):
|
|
511
|
+
if self.transcription_url:
|
|
512
|
+
try:
|
|
513
|
+
response = self._post(self.transcription_url, files={
|
|
514
|
+
"file": ("utterance.wav", _wave_bytes(turn.pcm), "audio/wav"),
|
|
515
|
+
}, timeout=25)
|
|
516
|
+
response.raise_for_status()
|
|
517
|
+
text = response.json()["text"]
|
|
518
|
+
except (httpx.HTTPError, ValueError, KeyError, TypeError) as error:
|
|
519
|
+
raise InvalidAcousticEvidence("configured transcription endpoint failed") from error
|
|
520
|
+
if not isinstance(text, str) or len(text) > 8192:
|
|
521
|
+
raise InvalidAcousticEvidence("invalid transcript from configured endpoint")
|
|
522
|
+
if not text.strip():
|
|
523
|
+
raise NoIntelligibleSpeech("no intelligible speech from configured endpoint")
|
|
524
|
+
turn.user_text = _spoken_extensions(text.strip())
|
|
525
|
+
turn.pcm = b""
|
|
526
|
+
return
|
|
189
527
|
evidence = self._recognize(turn.pcm)
|
|
190
|
-
turn.user_text = evidence["speech_transcript"]
|
|
528
|
+
turn.user_text = _spoken_extensions(evidence["speech_transcript"])
|
|
191
529
|
if observation := evidence["audio_observation"]:
|
|
192
530
|
turn.user_text += f"\n\nBackground sounds: {observation}"
|
|
193
531
|
turn.pcm = b""
|
|
@@ -249,9 +587,24 @@ class OrnithBackplane:
|
|
|
249
587
|
return None
|
|
250
588
|
return NativeAssistantTurn(failure_text, ())
|
|
251
589
|
|
|
252
|
-
def _structured_generation(self, rendered, tools, max_new_tokens, cancelled, *, require_tool=False
|
|
590
|
+
def _structured_generation(self, rendered, tools, max_new_tokens, cancelled, *, require_tool=False,
|
|
591
|
+
replacement=None, dictated_content=None, require_stdin=False):
|
|
253
592
|
options = {"tools": tools, "tool_choice": "required" if require_tool else "auto"} if tools else {}
|
|
254
593
|
schemas = {tool["function"]["name"]: tool["function"]["parameters"] for tool in tools}
|
|
594
|
+
file_work = bool(_FILE_TOOLS.intersection(schemas))
|
|
595
|
+
if file_work:
|
|
596
|
+
rendered = _system_instruction(rendered, _FILE_TOOL_INSTRUCTIONS)
|
|
597
|
+
if schemas.keys() == {"regex_build"}:
|
|
598
|
+
options["reasoning_budget_tokens"] = 384
|
|
599
|
+
options["chat_template_kwargs"] = {"enable_thinking": True}
|
|
600
|
+
max_new_tokens = max(max_new_tokens, 1536)
|
|
601
|
+
elif schemas.keys() == {"regex_infer_fields"}:
|
|
602
|
+
options["reasoning_budget_tokens"] = 128
|
|
603
|
+
options["chat_template_kwargs"] = {"enable_thinking": True}
|
|
604
|
+
max_new_tokens = max(max_new_tokens, 640)
|
|
605
|
+
else:
|
|
606
|
+
options["reasoning_budget_tokens"] = 96
|
|
607
|
+
max_new_tokens = max(max_new_tokens, 640)
|
|
255
608
|
for attempt in range(2):
|
|
256
609
|
if cancelled.is_set():
|
|
257
610
|
return None
|
|
@@ -262,13 +615,26 @@ class OrnithBackplane:
|
|
|
262
615
|
turn = validate_visible_turn(self._decode(message, tools))
|
|
263
616
|
if require_tool and not turn.calls:
|
|
264
617
|
raise ValueError("the requested tool call was omitted")
|
|
618
|
+
calls = []
|
|
265
619
|
for call in turn.calls:
|
|
266
620
|
validate_visible_turn(NativeAssistantTurn(json.dumps(call.arguments), ()))
|
|
267
621
|
validator = Draft202012Validator(schemas[call.name], registry=Registry())
|
|
268
622
|
error = next(validator.iter_errors(call.arguments), None)
|
|
269
623
|
if error is not None:
|
|
624
|
+
if error.validator == "const" and error.absolute_path:
|
|
625
|
+
field = error.absolute_path[-1]
|
|
626
|
+
raise ValueError(f"set {call.name}.{field} to {error.validator_value!r}")
|
|
270
627
|
raise ValueError(f"{call.name} failed its {error.validator} schema rule")
|
|
271
|
-
|
|
628
|
+
if replacement is not None:
|
|
629
|
+
replacement.validate(call)
|
|
630
|
+
if require_stdin and call.name == "shell":
|
|
631
|
+
call = NativeToolCall(call.id, call.name, _shell_stdin_arguments(call.arguments))
|
|
632
|
+
if (dictated_content is not None and call.name == "workspace_file"
|
|
633
|
+
and call.arguments.get("action") == "write"
|
|
634
|
+
and call.arguments.get("content") != dictated_content):
|
|
635
|
+
raise ValueError(f"write the dictated lines with this exact content: {dictated_content!r}")
|
|
636
|
+
calls.append(call)
|
|
637
|
+
return NativeAssistantTurn(turn.text, tuple(calls))
|
|
272
638
|
except ValueError as error:
|
|
273
639
|
if cancelled.is_set():
|
|
274
640
|
return None
|
|
@@ -277,7 +643,7 @@ class OrnithBackplane:
|
|
|
277
643
|
)
|
|
278
644
|
if attempt == 0:
|
|
279
645
|
if isinstance(error, OrnithTokenLimit):
|
|
280
|
-
max_new_tokens = max(max_new_tokens, min(512, max_new_tokens * 2))
|
|
646
|
+
max_new_tokens = max(max_new_tokens, min(1024 if file_work else 512, max_new_tokens * 2))
|
|
281
647
|
rendered = _system_instruction(
|
|
282
648
|
rendered, f"The preceding generation was rejected before execution: {error}. "
|
|
283
649
|
"Emit one exact native tool call, or give a short plain-text answer when no tool is needed.",
|
|
@@ -301,6 +667,8 @@ class OrnithBackplane:
|
|
|
301
667
|
rendered = []
|
|
302
668
|
for index, original in enumerate(messages):
|
|
303
669
|
message = dict(original)
|
|
670
|
+
if message["role"] == "tool" and message.get("name") == "shell":
|
|
671
|
+
message["content"] = _shell_context(message["content"])
|
|
304
672
|
if index in heard:
|
|
305
673
|
message["content"] = heard[index].user_text
|
|
306
674
|
if index == audio_index and heard[index].visual_evidence:
|
|
@@ -315,9 +683,35 @@ class OrnithBackplane:
|
|
|
315
683
|
rendered.append(message)
|
|
316
684
|
current = current_turn(messages, audio_index)
|
|
317
685
|
rounds = [entry["tool_calls"] for entry in current if entry.get("tool_calls")]
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
686
|
+
requests = [message["content"] for message in rendered if message["role"] == "user"]
|
|
687
|
+
request = requests[-1] if requests else None
|
|
688
|
+
date_query = request.partition("\n\nBackground sounds:")[0] if request and media and not media.visual_evidence else request
|
|
689
|
+
if (date_query and _DIRECT_DATE.fullmatch(date_query.strip().replace("’", "'").rstrip(" .?!"))
|
|
690
|
+
and any(tool["function"]["name"] == "get_current_time" for tool in tools or ())):
|
|
691
|
+
return _current_date_turn(current)
|
|
692
|
+
named_tools = requested_tools(tools or [], request)
|
|
693
|
+
recall_requested = bool(request and _RECALL_REQUEST.search(request) and not rounds
|
|
694
|
+
and any(tool["function"]["name"] == "episodic_search" for tool in tools or ()))
|
|
695
|
+
if recall_requested:
|
|
696
|
+
named_tools.add("episodic_search")
|
|
697
|
+
named = next(iter(named_tools)) if len(named_tools) == 1 else None
|
|
698
|
+
replacement = None
|
|
699
|
+
if named == "workspace_file" or (named is None and request and re.search(r"\bfile\b", request, re.I)
|
|
700
|
+
and any(tool["function"]["name"] == "workspace_file" for tool in tools or [])):
|
|
701
|
+
replacement = _replacement_precondition(request, rounds, current)
|
|
702
|
+
if replacement is not None:
|
|
703
|
+
named_tools.add("workspace_file")
|
|
704
|
+
earlier_request = requests[-2] if len(requests) > 1 else ""
|
|
705
|
+
quoted_source = (_QUOTED_ESCAPE_READ.search(request) if request and re.search(r"\bescaped\s+quote\b", request, re.I)
|
|
706
|
+
and re.search(r"\bescaped\s+backslash\b", request, re.I) else None)
|
|
707
|
+
continues_regex = bool(request and re.search(r"\b(?:pattern|rule|validator)\b", request, re.I)
|
|
708
|
+
and (_REGEX_REQUEST.search(earlier_request) or _QUOTED_ESCAPE_READ.search(earlier_request)))
|
|
709
|
+
regex_request = bool(request and (_REGEX_REQUEST.search(request) or quoted_source or continues_regex))
|
|
710
|
+
if regex_request:
|
|
711
|
+
named_tools.update({"regex_build", "regex_example", "regex_infer_fields"})
|
|
712
|
+
if continues_regex:
|
|
713
|
+
named_tools.update({"shell", "workspace_file"})
|
|
714
|
+
allowed = active_tools(tools or [], messages, audio_index, explicitly_requested=named_tools)
|
|
321
715
|
first_sentence = re.split(r"[.!?](?:\s|$)", request, maxsplit=1)[0] if named else ""
|
|
322
716
|
named_read = (named in _EXPLICIT_READ_ONLY and not rounds and not re.search(
|
|
323
717
|
r"\b(?:if|unless|whether)\b", first_sentence, re.I,
|
|
@@ -325,22 +719,66 @@ class OrnithBackplane:
|
|
|
325
719
|
empty_results = Counter()
|
|
326
720
|
result_names = set()
|
|
327
721
|
failed_calls = {}
|
|
722
|
+
verifications = {}
|
|
723
|
+
tool_arguments = {call["id"]: call["function"]["arguments"] for calls in rounds for call in calls}
|
|
724
|
+
last_file_change = -1
|
|
328
725
|
password_prompts = set()
|
|
329
726
|
discovery_succeeded = False
|
|
330
727
|
recovery_tools = set()
|
|
331
|
-
|
|
728
|
+
regex_check_failed = False
|
|
729
|
+
workspace_read = False
|
|
730
|
+
example = None
|
|
731
|
+
required_captures = set()
|
|
732
|
+
compile_attempts = 0
|
|
733
|
+
compiled_regex = None
|
|
734
|
+
quoted_read = False
|
|
735
|
+
for index, entry in enumerate(current):
|
|
332
736
|
if entry["role"] == "tool":
|
|
333
737
|
envelope = json.loads(entry["content"])
|
|
334
738
|
data = envelope.get("data")
|
|
739
|
+
if entry["name"] in {"regex_build", "regex_infer_fields"}:
|
|
740
|
+
compile_attempts += 1
|
|
335
741
|
if (entry["name"] == "terminal_session" and envelope.get("status") == "ok"
|
|
336
742
|
and isinstance(data, dict)):
|
|
337
743
|
handle = data.get("terminal_password_prompt")
|
|
338
744
|
if isinstance(handle, str) and TERMINAL_HANDLE.fullmatch(handle):
|
|
339
745
|
password_prompts.add(handle)
|
|
746
|
+
arguments = tool_arguments.get(entry["tool_call_id"], {})
|
|
747
|
+
if (entry["name"] == "shell" and arguments.get("intent") == "verify" and isinstance(data, dict)):
|
|
748
|
+
key = json.dumps(arguments, sort_keys=True)
|
|
749
|
+
if envelope.get("status") == "ok":
|
|
750
|
+
verifications.pop(key, None)
|
|
751
|
+
elif data.get("intent") == "verify" and data.get("error") == "shell_exit_nonzero":
|
|
752
|
+
verifications[key] = (index, arguments)
|
|
753
|
+
if (quoted_source and entry["name"] == "workspace_file" and arguments.get("action") == "read"
|
|
754
|
+
and arguments.get("path") == quoted_source[1]):
|
|
755
|
+
quoted_read = True
|
|
756
|
+
if envelope.get("status") == "ok" and isinstance(data, dict) and not data.get("truncated"):
|
|
757
|
+
content = data.get("content", "")
|
|
758
|
+
if isinstance(content, str) and (pattern := tighten_quoted_escapes(content.rstrip("\r\n"))):
|
|
759
|
+
compiled_regex = (index, pattern, True, set())
|
|
340
760
|
if envelope.get("status") == "error" and isinstance(data, dict):
|
|
341
761
|
failed_calls[entry["tool_call_id"]] = data.get("retry_mode")
|
|
762
|
+
if entry["name"] == "shell" and data.get("error") == "shell_exit_nonzero":
|
|
763
|
+
regex_check_failed = True
|
|
342
764
|
if entry["name"] == named and data.get("retry_mode") == "change_capability":
|
|
343
765
|
recovery_tools.update(data.get("alternative_tools", ()))
|
|
766
|
+
elif envelope.get("status") == "ok" and isinstance(data, dict):
|
|
767
|
+
if entry["name"] == "workspace_file" and data.get("action") == "read":
|
|
768
|
+
workspace_read = True
|
|
769
|
+
if isinstance(data.get("content"), str):
|
|
770
|
+
required_captures.update(_CAPTURE_REQUIREMENT.findall(data["content"]))
|
|
771
|
+
if entry["name"] == "regex_example" and isinstance(data.get("example"), str):
|
|
772
|
+
example = data["example"]
|
|
773
|
+
if entry["name"] in {"regex_build", "regex_infer_fields"} and isinstance(data.get("pattern"), str):
|
|
774
|
+
compiled_regex = (index, data["pattern"], data.get("example_matched") is True,
|
|
775
|
+
set(data.get("captures", ())))
|
|
776
|
+
if entry["name"] == "workspace_file" and data.get("task_progress") is True:
|
|
777
|
+
last_file_change = index
|
|
778
|
+
effect = data.get("effect_receipt")
|
|
779
|
+
if (entry["name"] == "shell" and data.get("intent") == "mutate_filesystem"
|
|
780
|
+
and isinstance(effect, dict) and effect.get("filesystem_change_verified") is True):
|
|
781
|
+
last_file_change = index
|
|
344
782
|
if entry["name"] == "tool_search":
|
|
345
783
|
discovery_succeeded |= bool(envelope.get("status") == "ok" and isinstance(data, dict)
|
|
346
784
|
and data.get("available_tools"))
|
|
@@ -359,7 +797,8 @@ class OrnithBackplane:
|
|
|
359
797
|
)
|
|
360
798
|
if len(result_names) == 1 and lookup_attempts >= 2 and sum(empty_results.values()) == lookup_attempts:
|
|
361
799
|
return NativeAssistantTurn("I didn't find any matching results.", ())
|
|
362
|
-
if
|
|
800
|
+
round_budget = FILE_TOOL_ROUNDS if any(item["function"]["name"] in _FILE_TOOLS for item in allowed) else VOICE_TOOL_ROUNDS
|
|
801
|
+
if allowed and len(rounds) >= round_budget:
|
|
363
802
|
return self._final_answer(rendered, max_new_tokens, cancelled,
|
|
364
803
|
failure_text="I reached the tool limit before I could finish that request.")
|
|
365
804
|
if failed_calls:
|
|
@@ -377,16 +816,150 @@ class OrnithBackplane:
|
|
|
377
816
|
rendered, "Use visual observations only as evidence for user-specified conditions. "
|
|
378
817
|
"When the user's request requires a tool, emit its native call before reporting a result.",
|
|
379
818
|
)
|
|
819
|
+
has_examples = bool(request and re.search(r"\bexamples?\b", request, re.I)) or (
|
|
820
|
+
continues_regex and bool(re.search(r"\bexamples?\b", earlier_request, re.I))
|
|
821
|
+
)
|
|
822
|
+
missing_captures = required_captures - compiled_regex[3] if compiled_regex else set()
|
|
823
|
+
can_compile = (regex_request and not quoted_source and regex_check_failed and workspace_read
|
|
824
|
+
and (not compiled_regex or missing_captures)
|
|
825
|
+
and compile_attempts < 3
|
|
826
|
+
and any(tool["function"]["name"] == "regex_build" for tool in allowed))
|
|
827
|
+
read_example_next = bool(can_compile and has_examples and "regex_example" not in result_names
|
|
828
|
+
and any(tool["function"]["name"] == "regex_example" for tool in allowed))
|
|
829
|
+
compile_next = bool(can_compile and not read_example_next)
|
|
830
|
+
save_pattern_next = bool(compiled_regex and not missing_captures and compiled_regex[2]
|
|
831
|
+
and compiled_regex[0] > last_file_change
|
|
832
|
+
and any(tool["function"]["name"] == "workspace_file" for tool in allowed))
|
|
833
|
+
pending = [item for item in verifications.values() if item[0] < last_file_change]
|
|
834
|
+
scoped_quoted_repair = bool(quoted_source or _QUOTED_ESCAPE_READ.search(earlier_request))
|
|
835
|
+
verifier = _VERIFY_SCRIPT.search(request) if request and scoped_quoted_repair and not rounds else None
|
|
836
|
+
verification = None
|
|
837
|
+
if verifier:
|
|
838
|
+
verification = {"command": f"python3 {verifier[1]}", "intent": "verify"}
|
|
839
|
+
elif pending and request and _RERUN_VERIFICATION.search(request) and not recovery_tools and replacement is None:
|
|
840
|
+
_, verification = max(pending, key=lambda item: item[0])
|
|
841
|
+
verify_next = bool(verification and any(tool["function"]["name"] == "shell" for tool in allowed))
|
|
842
|
+
stdin_next = False
|
|
843
|
+
source = _SOURCE_FOR_SCRIPT.search(request) if request and not rounds else None
|
|
844
|
+
if source and _workspace_file_observed(messages, source[1]):
|
|
845
|
+
source = None
|
|
846
|
+
if quoted_source and regex_check_failed and not quoted_read:
|
|
847
|
+
source = quoted_source
|
|
848
|
+
inspect_source_next = bool(source and any(tool["function"]["name"] == "workspace_file" for tool in allowed))
|
|
849
|
+
if verify_next:
|
|
850
|
+
tool = next(tool for tool in allowed if tool["function"]["name"] == "shell")
|
|
851
|
+
function = tool["function"]
|
|
852
|
+
allowed = [{**tool, "function": {**function, "parameters": {
|
|
853
|
+
"type": "object", "additionalProperties": False, "required": list(verification),
|
|
854
|
+
"properties": {key: {"const": value} for key, value in verification.items()},
|
|
855
|
+
}}}]
|
|
856
|
+
rendered = _system_instruction(rendered, "Run the requested shell verification by itself. "
|
|
857
|
+
"The shell must preserve the verifier's own exit status.")
|
|
858
|
+
elif compile_next:
|
|
859
|
+
structured = (example and len(re.findall(r"\b[A-Za-z_][\w.-]*=", example)) > 1
|
|
860
|
+
and any(tool["function"]["name"] == "regex_infer_fields" for tool in allowed))
|
|
861
|
+
tool_name = "regex_infer_fields" if structured else "regex_build"
|
|
862
|
+
allowed = [tool for tool in allowed if tool["function"]["name"] == tool_name]
|
|
863
|
+
if structured:
|
|
864
|
+
tool = allowed[0]
|
|
865
|
+
allowed = [{**tool, "function": {**tool["function"], "parameters": {
|
|
866
|
+
"type": "object", "properties": {}, "additionalProperties": False,
|
|
867
|
+
}}}]
|
|
868
|
+
rendered = _system_instruction(rendered, "Call regex_infer_fields with an empty argument object. "
|
|
869
|
+
"It reads the workspace specification and positive records to infer the pattern.")
|
|
870
|
+
elif example:
|
|
871
|
+
allowed = [_require_regex_example(tool, example) for tool in allowed]
|
|
872
|
+
rendered = _system_instruction(rendered, "Use regex_build with the observed valid line as example. "
|
|
873
|
+
f"Copy the example exactly: {example!r}. {_SPAN_GUIDANCE}")
|
|
874
|
+
else:
|
|
875
|
+
rendered = _system_instruction(rendered, "Use regex_build with the observed field order and the "
|
|
876
|
+
"capture names in the specification.")
|
|
877
|
+
if required_captures and not structured:
|
|
878
|
+
rendered = _system_instruction(rendered, "The specification requires these exact capture names: "
|
|
879
|
+
+ ", ".join(sorted(required_captures)) + ". Attach each name to the "
|
|
880
|
+
"field it is meant to capture. Use the keys visible in the actual example.")
|
|
881
|
+
elif read_example_next:
|
|
882
|
+
allowed = [tool for tool in allowed if tool["function"]["name"] == "regex_example"]
|
|
883
|
+
rendered = _system_instruction(rendered, "Call regex_example with an empty argument object to read "
|
|
884
|
+
"a representative valid record before editing the regex.")
|
|
885
|
+
elif save_pattern_next:
|
|
886
|
+
allowed = ([_constrain_tool(_REGEX_SAVE_TOOL, {"path": quoted_source[1]})] if quoted_source
|
|
887
|
+
else [_REGEX_SAVE_TOOL])
|
|
888
|
+
rendered = _system_instruction(rendered, "Call regex_save with the requested output file's path. "
|
|
889
|
+
"Keep the validator and example files intact.")
|
|
890
|
+
elif compiled_regex and not missing_captures:
|
|
891
|
+
rendered = _system_instruction(rendered, "Save the compiled pattern and rerun the user's validator "
|
|
892
|
+
"if either step remains. Preserve the validator and its inputs. Report a "
|
|
893
|
+
"completed check once the saved pattern passes.")
|
|
894
|
+
elif inspect_source_next:
|
|
895
|
+
allowed = [_constrain_tool(tool, {"action": "read", "path": source[1]})
|
|
896
|
+
for tool in allowed if tool["function"]["name"] == "workspace_file"]
|
|
897
|
+
rendered = _system_instruction(rendered, "Read the named pattern before editing its quoted field."
|
|
898
|
+
if quoted_source else "Read the source file first. Use its observed format "
|
|
899
|
+
"when writing the requested program.")
|
|
900
|
+
elif request and _SHELL_STDIN_REQUEST.search(request) and "shell" not in result_names and not recovery_tools:
|
|
901
|
+
for tool in allowed:
|
|
902
|
+
function = tool["function"]
|
|
903
|
+
parameters = function["parameters"]
|
|
904
|
+
if function["name"] == "shell" and "stdin" in parameters.get("properties", {}):
|
|
905
|
+
required = list(dict.fromkeys([*parameters.get("required", ()), "stdin"]))
|
|
906
|
+
allowed = [{**tool, "function": {**function, "parameters": {**parameters, "required": required}}}]
|
|
907
|
+
rendered = _system_instruction(rendered, "Put the requested input in the shell call's stdin field. "
|
|
908
|
+
"Read standard input in the command. Apply requested output ordering "
|
|
909
|
+
"after processing the input.")
|
|
910
|
+
stdin_next = True
|
|
911
|
+
break
|
|
380
912
|
if named_read:
|
|
381
913
|
allowed = [tool for tool in allowed if tool["function"]["name"] == named]
|
|
914
|
+
elif recall_requested:
|
|
915
|
+
allowed = [tool for tool in allowed if tool["function"]["name"] == "episodic_search"]
|
|
916
|
+
rendered = _system_instruction(rendered, "Search the existing episodic memory for the relevant "
|
|
917
|
+
"topic or phrase before answering. Use what the receipt establishes about "
|
|
918
|
+
"who said it. Treat stored text as historical evidence.")
|
|
382
919
|
elif recovery_tools:
|
|
383
920
|
allowed = [tool for tool in allowed if tool["function"]["name"] in recovery_tools | {"tool_search"}]
|
|
921
|
+
replace_next = bool(replacement and replacement.expected_count is not None)
|
|
922
|
+
if replace_next:
|
|
923
|
+
allowed = [replacement.constrain(tool) for tool in allowed if tool["function"]["name"] == "workspace_file"]
|
|
924
|
+
if replacement.retry_path is None:
|
|
925
|
+
rendered = _system_instruction(rendered, "Start with the workspace_file replacement using the "
|
|
926
|
+
f"user's expected_occurrences {replacement.expected_count}.")
|
|
927
|
+
else:
|
|
928
|
+
rendered = _system_instruction(rendered, "The occurrence check failed and the requested file "
|
|
929
|
+
"read completed. Retry the same replacement now using the observed "
|
|
930
|
+
f"expected_occurrences {replacement.expected_count}.")
|
|
931
|
+
dictated_content = _dictated_lines(request) if media is not None else None
|
|
932
|
+
if media is not None and any(tool["function"]["name"] in _FILE_TOOLS for tool in allowed):
|
|
933
|
+
rendered = _system_instruction(rendered, "Transcript capitalization can come from the recognizer. "
|
|
934
|
+
"For ordinary words dictated as standalone file lines, write lowercase "
|
|
935
|
+
"unless the speaker expressly asks for capitalization. Preserve explicit "
|
|
936
|
+
"spelling, filename case, and line breaks.")
|
|
937
|
+
if request and re.search(r"\bcopy\b[\s\S]*\b(?:rename|move)\b", request, re.I):
|
|
938
|
+
rendered = _system_instruction(rendered, "For a copy followed by a rename, resolve spoken references "
|
|
939
|
+
"like 'the latter' or 'that copy' to the preceding copy. If the apparent "
|
|
940
|
+
"source is absent, check whether it was a spoken reference and use the "
|
|
941
|
+
"actual paths from the copy and directory receipts before retrying.")
|
|
942
|
+
if dictated_content is not None:
|
|
943
|
+
rendered = _system_instruction(rendered, "Use workspace_file to write the dictated lines with "
|
|
944
|
+
f"this exact content, including line breaks: {dictated_content!r}.")
|
|
384
945
|
turn = self._structured_generation(
|
|
385
946
|
rendered, allowed, max_new_tokens, cancelled,
|
|
386
|
-
require_tool=
|
|
947
|
+
require_tool=(verify_next or stdin_next or inspect_source_next or compile_next or read_example_next or save_pattern_next
|
|
948
|
+
or replace_next or named_read or recall_requested
|
|
949
|
+
or (media is not None and media.visual_requires_tool and not rounds)),
|
|
950
|
+
replacement=replacement,
|
|
951
|
+
dictated_content=dictated_content,
|
|
952
|
+
require_stdin=stdin_next,
|
|
387
953
|
)
|
|
388
954
|
if turn is None:
|
|
389
955
|
return None
|
|
956
|
+
if save_pattern_next and not verify_next:
|
|
957
|
+
calls = tuple(
|
|
958
|
+
NativeToolCall(call.id, "workspace_file", {"action": "write", "path": call.arguments["path"],
|
|
959
|
+
"content": compiled_regex[1] + "\n"})
|
|
960
|
+
if call.name == "regex_save" else call for call in turn.calls
|
|
961
|
+
)
|
|
962
|
+
turn = NativeAssistantTurn(turn.text, calls)
|
|
390
963
|
if turn.text == "I couldn't form a valid tool request for that turn." and result_names:
|
|
391
964
|
return self._final_answer(rendered, max(max_new_tokens, 256), cancelled,
|
|
392
965
|
failure_text="I couldn't summarize the tool result. Ask me to try again.")
|
|
@@ -397,7 +970,10 @@ class OrnithBackplane:
|
|
|
397
970
|
continue
|
|
398
971
|
matching = [entry for entry in previous
|
|
399
972
|
if entry["function"] == {"name": call.name, "arguments": call.arguments}]
|
|
400
|
-
if not matching
|
|
973
|
+
if not matching:
|
|
974
|
+
novel.append(call)
|
|
975
|
+
elif (call.name == "shell" and any(call.arguments == arguments for _, arguments in pending)
|
|
976
|
+
or len(matching) == 1 and failed_calls.get(matching[0]["id"]) == "repeat_read_once"):
|
|
401
977
|
novel.append(call)
|
|
402
978
|
if turn.calls and not novel:
|
|
403
979
|
return self._final_answer(rendered, max_new_tokens, cancelled,
|