-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrun_agent.py
More file actions
2296 lines (2179 loc) · 101 KB
/
Copy pathrun_agent.py
File metadata and controls
2296 lines (2179 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Core Moonshine conversation loop and direct terminal runner."""
from __future__ import annotations
import argparse
import difflib
import json
import traceback
from dataclasses import dataclass, field
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
from moonshine.agent_runtime.prompt_builder import build_system_prompt
from moonshine.agent_runtime.research_workflow import ResearchWorkflowManager
from moonshine.json_schema import JsonSchemaValidationError, validate_json_schema
from moonshine.model_tools import collect_tool_schemas, handle_function_calls
from moonshine.providers import OfflineProvider, ProviderResponse, ProviderToolCall
from moonshine.utils import estimate_token_count, estimate_tokens_rough, shorten, tokenize, utc_now
QUERY_MEMORY_VISIBLE_TOKEN_BUDGET = 100000
@dataclass
class AgentEvent:
"""Incremental agent event for terminal and gateway consumers."""
type: str
text: str = ""
payload: Dict[str, object] = field(default_factory=dict)
@dataclass
class ConversationBudget:
"""Hard limits for one user turn."""
max_model_rounds: int
max_tool_rounds: int
max_empty_response_retries: int
max_tool_validation_retries: int
max_consecutive_errors: int
max_tool_calls_per_round: int
@dataclass
class PreparedToolCall:
"""Normalized tool-call record."""
call_id: str
original_name: str
name: str
arguments: Dict[str, object]
status: str
error: str = ""
repaired_from: str = ""
@dataclass
class ConversationState:
"""Mutable per-turn runtime state."""
user_message: str
mode: str
project_slug: str
session_id: str
agent_slug: str
system_prompt: str
provider_messages: List[Dict[str, object]]
tool_schemas: List[Dict[str, object]]
runtime: Dict[str, object]
budget: ConversationBudget
valid_tool_names: Sequence[str]
model_round: int = 0
tool_rounds: int = 0
empty_response_retries: int = 0
tool_validation_retries: int = 0
consecutive_errors: int = 0
post_tool_nudge_used: bool = False
summary_pass_used: bool = False
fallback_response_text: str = ""
fallback_response_streamed: bool = False
fallback_response_reasoning_content: str = ""
final_text: str = ""
final_reason: str = ""
final_reasoning_content: str = ""
turn_transcript: List[Dict[str, object]] = field(default_factory=list)
highest_context_warning_tier: float = 0.0
overflow_recovery_attempts: int = 0
research_workflow_snapshot: Dict[str, object] = field(default_factory=dict)
class AIAgent(object):
"""Moonshine conversation runner."""
OFFLINE_RESPONSE_PREFIX = "Moonshine processed the request in offline mode."
OFFLINE_FINAL_REASONS = {"provider_offline", "verification_provider_offline", "archival_provider_offline"}
def __init__(self, *, config, paths, provider, verification_provider, archival_provider, memory_manager, session_store, agent_manager, skill_manager, tool_manager, context_manager):
self.config = config
self.paths = paths
self.provider = provider
self.verification_provider = verification_provider
self.archival_provider = archival_provider
self.memory_manager = memory_manager
self.session_store = session_store
self.agent_manager = agent_manager
self.skill_manager = skill_manager
self.skill_store = skill_manager.store
self.tool_manager = tool_manager
self.tool_registry = tool_manager
self.context_manager = context_manager
self.research_workflow = ResearchWorkflowManager(
paths=paths,
provider=archival_provider,
memory_manager=memory_manager,
session_store=session_store,
config=config,
)
def _default_agent_slug_for_mode(self, mode: str) -> str:
"""Return the implicit active agent for a given mode."""
return "research-control-loop" if mode == "research" else self.agent_manager.default_slug
def _offline_provider_message(self, response: ProviderResponse) -> str:
"""Return offline fallback text if a provider response entered offline mode."""
content = str(getattr(response, "content", "") or "").strip()
if content.startswith(self.OFFLINE_RESPONSE_PREFIX):
return content
return ""
def _configured_offline_provider_message(self) -> str:
"""Return a concise terminal message for an explicitly offline main provider."""
note = str(getattr(self.provider, "note", "") or "").strip()
suffix = (" Provider note: %s" % note) if note else ""
return (
"Research autopilot stopped because the main provider is offline or unavailable.%s\n"
"Configure a working provider before continuing research mode."
) % suffix
def _verification_offline_error(self, results: Sequence[Dict[str, object]]) -> str:
"""Return the verification-provider offline tool error text if present."""
for result in results:
name = str(result.get("name") or "")
if name not in {
"pessimistic_verify",
"verify_correctness_assumption",
"verify_correctness_computation",
"verify_correctness_logic",
"verify_overall",
}:
continue
error = str(result.get("error") or "")
if "verification provider is offline or unavailable" in error.lower():
return error
return ""
def _archive_provider_failed(self, payload: Dict[str, object]) -> bool:
"""Return whether an archival attempt failed because its provider path is unusable."""
if not payload:
return True
if payload.get("error"):
return True
skipped = str(payload.get("skipped") or "").strip().lower()
return skipped == "structured_provider_unavailable"
def _archive_after_turn_with_provider(
self,
provider,
*,
project_slug: str,
session_id: str,
user_message: str,
assistant_message: str,
turn_context: Sequence[Dict[str, object]],
) -> Dict[str, object]:
"""Run the research archival pass with a specific provider instance."""
previous_provider = self.research_workflow.provider
self.research_workflow.provider = provider
try:
return self.research_workflow.archive_after_turn(
project_slug=project_slug,
session_id=session_id,
user_message=user_message,
assistant_message=assistant_message,
turn_context=list(turn_context),
)
finally:
self.research_workflow.provider = previous_provider
def _build_runtime(self, *, mode: str, project_slug: str, session_id: str, agent_slug: str = "") -> Dict[str, object]:
"""Build the tool runtime mapping."""
resolved_agent_slug = str(agent_slug or self._default_agent_slug_for_mode(mode)).strip()
exposure = getattr(self.config, "exposure", None)
return {
"paths": self.paths,
"config": self.config,
"memory_manager": self.memory_manager,
"session_store": self.session_store,
"agent_manager": self.agent_manager,
"skill_manager": self.skill_manager,
"skill_store": self.skill_store,
"tool_manager": self.tool_manager,
"context_manager": self.context_manager,
"research_workflow": self.research_workflow,
"provider": self.provider,
"verification_provider": self.verification_provider,
"archival_provider": self.archival_provider,
"verification_provider_inherit_from_main": bool(
getattr(self.config.verification_provider, "inherit_from_main", True)
),
"archival_provider_inherit_from_main": bool(
getattr(self.config.archival_provider, "inherit_from_main", True)
),
"mode": mode,
"project_slug": project_slug,
"session_id": session_id,
"agent_slug": resolved_agent_slug,
"exposure": {
"tools_include": list(getattr(exposure, "tools_include", []) or []),
"tools_exclude": list(getattr(exposure, "tools_exclude", []) or []),
"skills_include": list(getattr(exposure, "skills_include", []) or []),
"skills_exclude": list(getattr(exposure, "skills_exclude", []) or []),
},
}
def _build_budget(self) -> ConversationBudget:
"""Resolve loop budgets from config."""
agent_config = self.config.agent
return ConversationBudget(
max_model_rounds=max(1, int(getattr(agent_config, "max_model_rounds", 12))),
max_tool_rounds=max(1, int(getattr(agent_config, "max_tool_rounds", 8))),
max_empty_response_retries=max(0, int(getattr(agent_config, "max_empty_response_retries", 2))),
max_tool_validation_retries=max(0, int(getattr(agent_config, "max_tool_validation_retries", 2))),
max_consecutive_errors=max(1, int(getattr(agent_config, "max_consecutive_errors", 3))),
max_tool_calls_per_round=max(1, int(getattr(agent_config, "max_tool_calls_per_round", 6))),
)
def _record_turn_event(self, session_id: str, event_type: str, text: str = "", **payload: object) -> None:
"""Persist loop decisions for debugging and traceability."""
self.session_store.append_turn_event(
session_id,
{
"type": event_type,
"text": text,
"created_at": utc_now(),
**dict(payload),
},
)
def _snapshot_messages(self, messages: Sequence[Dict[str, object]]) -> List[Dict[str, object]]:
"""Create a JSON-safe snapshot of provider messages before mutation."""
return json.loads(json.dumps(list(messages), ensure_ascii=False))
def _normalized_response_payload(self, response: ProviderResponse) -> Dict[str, object]:
"""Render a normalized provider response for trace persistence."""
return {
"content": response.content,
"reasoning_content": response.reasoning_content,
"tool_calls": [
{
"name": item.name,
"arguments": dict(item.arguments or {}),
"call_id": item.call_id,
}
for item in response.tool_calls
],
}
def _record_provider_round(
self,
*,
state: ConversationState,
phase: str,
title: str,
system_prompt: str,
request_messages: Sequence[Dict[str, object]],
response: ProviderResponse,
tool_schemas: Sequence[Dict[str, object]],
) -> None:
"""Persist one provider request/response round for human inspection."""
self.session_store.append_provider_round(
state.session_id,
{
"created_at": utc_now(),
"phase": phase,
"title": title,
"model_round": state.model_round,
"system_prompt": system_prompt,
"messages": self._snapshot_messages(request_messages),
"tool_schema_names": [str(item.get("name", "")) for item in list(tool_schemas or []) if str(item.get("name", ""))],
"response": self._normalized_response_payload(response),
},
)
def _append_turn_transcript(self, state: ConversationState, event: Dict[str, object]) -> None:
"""Append one JSON-safe event to the current-turn archival transcript."""
if state.mode != "research":
return
state.turn_transcript.append(json.loads(json.dumps(dict(event), ensure_ascii=False)))
def _emit_status(self, state: ConversationState, text: str, **payload: object) -> Optional[AgentEvent]:
"""Create and persist a status event when enabled."""
data = dict(payload)
data.setdefault("model_round", state.model_round)
data.setdefault("tool_rounds", state.tool_rounds)
self._record_turn_event(
state.session_id,
"status",
text,
**data,
)
if not self.config.agent.emit_status_events:
return None
return AgentEvent(type="status", text=text, payload=data)
def _emit_context_pressure_if_needed(self, state: ConversationState, snapshot: Dict[str, float]) -> Optional[AgentEvent]:
"""Emit one of the configured context-pressure warnings."""
warning_tier = float(snapshot.get("warning_tier", 0.0) or 0.0)
if warning_tier <= state.highest_context_warning_tier:
return None
state.highest_context_warning_tier = warning_tier
progress_percent = int(round(float(snapshot.get("progress", 0.0)) * 100.0))
threshold_tokens = int(snapshot.get("threshold_tokens", 0.0) or 0.0)
estimated_tokens = int(snapshot.get("estimated_tokens", 0.0) or 0.0)
tier_percent = int(round(warning_tier * 100.0))
return self._emit_status(
state,
"Context pressure warning: %s%% of the compaction threshold reached (%s/%s tokens, tier %s%%)."
% (progress_percent, estimated_tokens, threshold_tokens, tier_percent),
estimated_tokens=estimated_tokens,
threshold_tokens=threshold_tokens,
progress=snapshot.get("progress", 0.0),
warning_tier=warning_tier,
)
def _maybe_reset_context_warning(self, state: ConversationState, snapshot: Dict[str, float]) -> None:
"""Clear the warning tier once compaction brings pressure back down."""
if float(snapshot.get("warning_tier", 0.0) or 0.0) < float(self.config.context.pressure_warning_ratio):
state.highest_context_warning_tier = 0.0
def _is_context_overflow_error(self, exc: Exception) -> bool:
"""Return True when an exception looks like a context-length failure."""
text = str(exc).lower()
status_code = getattr(exc, "status_code", None) or getattr(getattr(exc, "response", None), "status_code", None)
if status_code in (400, 413):
return True
phrases = (
"context length",
"context length exceeded",
"context size",
"maximum context",
"context window",
"too many tokens",
"token limit",
"prompt is too long",
"request entity too large",
"payload too large",
"reduce the length",
"max tokens too large",
)
return any(phrase in text for phrase in phrases)
def _recover_from_context_overflow(self, state: ConversationState, *, phase: str, error_text: str) -> bool:
"""Apply aggressive compaction and retry when a provider overflows."""
limit = max(0, int(self.config.context.overflow_retry_limit))
if state.overflow_recovery_attempts >= limit:
return False
compacted_messages, compression_meta = self.context_manager.compact_provider_messages(
messages=state.provider_messages,
system_prompt=state.system_prompt,
session_id=state.session_id,
artifact_label="overflow-recovery",
aggressive=True,
tool_schemas=state.tool_schemas,
)
changed = json.dumps(compacted_messages, ensure_ascii=False) != json.dumps(state.provider_messages, ensure_ascii=False)
if not changed:
return False
state.provider_messages = compacted_messages
state.overflow_recovery_attempts += 1
self._record_turn_event(
state.session_id,
"context_overflow_recovery",
"Recovered from a context overflow by aggressively compacting history.",
phase=phase,
error=error_text,
recovery_attempt=state.overflow_recovery_attempts,
estimated_tokens=compression_meta.get("estimated_tokens", 0),
summarized_messages=compression_meta.get("summarized_messages", 0),
kept_recent_messages=compression_meta.get("kept_recent_messages", 0),
pruned_tool_items=compression_meta.get("pruned_tool_items", 0),
)
self._maybe_reset_context_warning(
state,
{
"warning_tier": compression_meta.get("warning_tier", 0.0),
},
)
return True
def _normalize_text(self, value: object) -> str:
"""Normalize provider content into plain text."""
if value is None:
return ""
if isinstance(value, str):
return value
if isinstance(value, dict):
if "text" in value:
return self._normalize_text(value.get("text"))
if "content" in value:
return self._normalize_text(value.get("content"))
return json.dumps(value, ensure_ascii=False)
if isinstance(value, list):
parts = []
for item in value:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict) and item.get("type") == "text":
parts.append(str(item.get("text", "")))
elif isinstance(item, dict) and "text" in item:
parts.append(str(item["text"]))
else:
parts.append(self._normalize_text(item))
return "\n".join(part for part in parts if part)
return str(value)
def _normalize_response(self, response: Optional[ProviderResponse]) -> ProviderResponse:
"""Normalize a provider response before loop handling."""
response = response or ProviderResponse()
normalized_calls = []
for index, tool_call in enumerate(response.tool_calls or []):
arguments = tool_call.arguments
if arguments is None:
arguments = {}
elif not isinstance(arguments, dict):
arguments = {"value": arguments}
normalized_calls.append(
ProviderToolCall(
name=self._normalize_text(tool_call.name).strip(),
arguments=dict(arguments),
call_id=tool_call.call_id or "tool-call-%s" % (index + 1),
)
)
return ProviderResponse(
content=self._normalize_text(response.content),
tool_calls=normalized_calls,
reasoning_content=self._normalize_text(response.reasoning_content),
raw_payload=dict(response.raw_payload or {}),
)
def _repair_tool_name(self, name: str, valid_tool_names: Sequence[str]) -> tuple[str, str]:
"""Repair a tool name with exact-insensitive and fuzzy matching."""
normalized_name = (name or "").strip()
if normalized_name in valid_tool_names:
return normalized_name, ""
lower_map = {item.lower(): item for item in valid_tool_names}
if normalized_name.lower() in lower_map:
return lower_map[normalized_name.lower()], normalized_name
matches = difflib.get_close_matches(normalized_name, list(valid_tool_names), n=1, cutoff=0.72)
if matches:
return matches[0], normalized_name
return normalized_name, ""
def _normalize_tool_arguments(self, arguments: object) -> tuple[Dict[str, object], str]:
"""Normalize tool arguments and detect malformed payloads."""
if arguments is None:
return {}, ""
if isinstance(arguments, dict):
if "_raw_arguments" in arguments and len(arguments) == 1:
return {}, "Tool arguments were malformed JSON and could not be parsed."
return dict(arguments), ""
if isinstance(arguments, str):
cleaned = arguments.strip()
if not cleaned:
return {}, ""
try:
parsed = json.loads(cleaned)
except ValueError:
return {}, "Tool arguments were malformed JSON and could not be parsed."
if isinstance(parsed, dict):
return parsed, ""
return {"value": parsed}, ""
if isinstance(arguments, list):
return {"value": list(arguments)}, ""
return {"value": arguments}, ""
def _prepare_tool_calls(
self,
state: ConversationState,
tool_calls: Sequence[ProviderToolCall],
) -> tuple[List[PreparedToolCall], bool]:
"""Validate, normalize, and guardrail tool calls."""
prepared: List[PreparedToolCall] = []
seen_signatures = set()
executable_count = 0
invalid_batch = False
available_tools = ", ".join(sorted(state.valid_tool_names))
for index, call in enumerate(tool_calls):
repaired_name, repaired_from = self._repair_tool_name(call.name, state.valid_tool_names)
arguments, argument_error = self._normalize_tool_arguments(call.arguments)
call_id = call.call_id or "tool-call-%s" % (index + 1)
status = "execute"
error = ""
if repaired_name not in state.valid_tool_names:
status = "invalid"
error = "Unknown tool '%s'. Available tools: %s." % (call.name, available_tools)
invalid_batch = True
elif argument_error:
status = "invalid"
error = argument_error
invalid_batch = True
else:
tool_definition = self.tool_manager.get_tool(repaired_name)
if tool_definition is not None:
try:
validate_json_schema(arguments, dict(tool_definition.parameters or {}))
except JsonSchemaValidationError as exc:
status = "invalid"
error = "Arguments for tool '%s' do not satisfy its JSON schema: %s." % (repaired_name, exc)
invalid_batch = True
if status == "invalid":
prepared.append(
PreparedToolCall(
call_id=call_id,
original_name=call.name,
name=repaired_name,
arguments=arguments,
status=status,
error=error,
repaired_from=repaired_from,
)
)
continue
signature = "%s|%s" % (
repaired_name,
json.dumps(arguments, sort_keys=True, ensure_ascii=False),
)
if signature in seen_signatures:
status = "duplicate"
error = "Skipped duplicate tool call in the same model response."
elif executable_count >= state.budget.max_tool_calls_per_round:
status = "capped"
error = "Skipped because the per-round tool limit (%s) was reached." % state.budget.max_tool_calls_per_round
else:
seen_signatures.add(signature)
executable_count += 1
prepared.append(
PreparedToolCall(
call_id=call_id,
original_name=call.name,
name=repaired_name,
arguments=arguments,
status=status,
error=error,
repaired_from=repaired_from,
)
)
if invalid_batch:
for item in prepared:
if item.status != "invalid":
item.status = "skipped"
item.error = "Skipped because another tool call in the same model response was invalid. Retry the tool batch."
return prepared, invalid_batch
def _build_assistant_tool_message(
self,
content: str,
reasoning_content: str,
prepared_calls: Sequence[PreparedToolCall],
) -> Dict[str, object]:
"""Build the assistant tool-call message for the next model round."""
message = {
"role": "assistant",
"content": content or "",
"tool_calls": [
{
"id": item.call_id,
"type": "function",
"function": {
"name": item.name or item.original_name,
"arguments": json.dumps(item.arguments, ensure_ascii=False),
},
}
for item in prepared_calls
],
}
if str(reasoning_content or "").strip():
message["reasoning_content"] = reasoning_content
return message
def _assistant_tool_event_content(self, content: str, prepared_calls: Sequence[PreparedToolCall]) -> str:
"""Render an assistant tool-call turn as compact text."""
lines = []
if content.strip():
lines.append("Assistant: %s" % content.strip())
for item in prepared_calls:
lines.append(
"Tool Call: %s(%s)"
% (
item.name or item.original_name,
shorten(json.dumps(item.arguments, ensure_ascii=False), 200),
)
)
return "\n".join(lines)
def _build_synthetic_tool_result(self, item: PreparedToolCall) -> Dict[str, object]:
"""Build a synthetic tool result for invalid or skipped calls."""
output = {
"status": item.status,
"message": item.error,
}
if item.repaired_from:
output["repaired_from"] = item.repaired_from
return {
"name": item.name or item.original_name,
"call_id": item.call_id,
"arguments": dict(item.arguments),
"output": output,
"error": item.error or None,
}
def _dedupe_query_memory_item(self, item: object) -> object:
"""Remove duplicate text copies inside one query_memory hit."""
if not isinstance(item, dict):
return item
cleaned = json.loads(json.dumps(item, ensure_ascii=False))
metadata = dict(cleaned.get("metadata") or {})
content = str(cleaned.get("content") or "")
content_inline = str(cleaned.get("content_inline") or "")
exact_excerpt = str(cleaned.get("exact_excerpt") or "")
summary = str(cleaned.get("summary") or "")
window_excerpt = str(cleaned.get("window_excerpt") or "")
if content and str(metadata.get("raw_text") or "") == content:
metadata.pop("raw_text", None)
if content_inline and str(metadata.get("exact_excerpt") or "") == content_inline:
metadata.pop("exact_excerpt", None)
if exact_excerpt and str(metadata.get("exact_excerpt") or "") == exact_excerpt:
metadata.pop("exact_excerpt", None)
if summary and window_excerpt and summary == window_excerpt:
cleaned.pop("window_excerpt", None)
if metadata:
cleaned["metadata"] = metadata
else:
cleaned.pop("metadata", None)
return cleaned
def _estimate_query_memory_visible_tokens(self, value: object) -> int:
"""Estimate query_memory visible output without relying on exact provider tokenization."""
try:
text = json.dumps(value, ensure_ascii=False, sort_keys=True)
except TypeError:
text = str(value)
if len(text) > 800000:
return estimate_tokens_rough(text)
return estimate_token_count(text, model_name=str(getattr(self.provider, "model", "") or ""))
def _trim_query_memory_text(self, text: str, *, query: str, anchor: str, token_budget: int) -> str:
"""Trim a long retrieved text around the strongest available match anchor."""
source = str(text or "")
if token_budget <= 0 or not source:
return ""
source_tokens = estimate_tokens_rough(source) if len(source) > 800000 else estimate_token_count(
source,
model_name=str(getattr(self.provider, "model", "") or ""),
)
if source_tokens <= token_budget:
return source
char_budget = max(256, int(token_budget) * 4)
if len(source) <= char_budget:
return source
lower_source = source.lower()
anchors = [str(anchor or "").strip(), str(query or "").strip()]
anchors.extend(token for token in tokenize(str(query or "")) if len(token) >= 3)
match_index = -1
for candidate in anchors:
if not candidate:
continue
match_index = lower_source.find(candidate.lower())
if match_index >= 0:
break
if match_index < 0:
match_index = 0
start = max(0, match_index - char_budget // 2)
end = min(len(source), start + char_budget)
start = max(0, end - char_budget)
prefix = "[truncated before local context]\n" if start > 0 else ""
suffix = "\n[truncated after local context]" if end < len(source) else ""
return prefix + source[start:end].strip() + suffix
def _trim_query_memory_item_to_budget(self, item: object, *, query: str, token_budget: int) -> object:
"""Trim one query_memory hit to a local context budget, preserving source metadata."""
if not isinstance(item, dict):
return item
cleaned = json.loads(json.dumps(item, ensure_ascii=False))
if token_budget <= 0:
return {
key: value
for key, value in cleaned.items()
if key in {"id", "key", "source", "source_type", "type", "artifact_type", "title", "content_path", "project_slug", "created_at", "score"}
}
if self._estimate_query_memory_visible_tokens(cleaned) <= token_budget:
return cleaned
anchor = (
str(cleaned.get("content_inline") or "")
or str(cleaned.get("exact_excerpt") or "")
or str(cleaned.get("summary") or "")
or str(cleaned.get("window_excerpt") or "")
or str(cleaned.get("local_context") or "")
or str(cleaned.get("content") or "")
)
for key in ["local_context", "content", "text", "summary", "window_excerpt", "content_inline", "exact_excerpt"]:
if key in cleaned and isinstance(cleaned.get(key), str):
remaining = max(32, token_budget - self._estimate_query_memory_visible_tokens({k: v for k, v in cleaned.items() if k != key}))
cleaned[key] = self._trim_query_memory_text(
str(cleaned.get(key) or ""),
query=query,
anchor=anchor,
token_budget=remaining,
)
if self._estimate_query_memory_visible_tokens(cleaned) <= token_budget:
return cleaned
metadata = dict(cleaned.get("metadata") or {})
for key in ["raw_text", "source_excerpt", "statement", "proof_sketch"]:
if key in metadata and isinstance(metadata.get(key), str):
remaining = max(32, token_budget - self._estimate_query_memory_visible_tokens({k: v for k, v in cleaned.items() if k != "metadata"}))
metadata[key] = self._trim_query_memory_text(
str(metadata.get(key) or ""),
query=query,
anchor=anchor,
token_budget=remaining,
)
if metadata:
cleaned["metadata"] = metadata
if self._estimate_query_memory_visible_tokens(cleaned) <= token_budget:
return cleaned
minimal = {
key: value
for key, value in cleaned.items()
if key in {"id", "key", "source", "source_type", "type", "artifact_type", "title", "content_path", "project_slug", "session_id", "created_at", "score", "source_refs"}
}
text = str(cleaned.get("content") or cleaned.get("local_context") or cleaned.get("text") or cleaned.get("summary") or "")
if text:
minimal["content"] = self._trim_query_memory_text(text, query=query, anchor=anchor, token_budget=max(32, token_budget - 128))
return minimal
def _query_memory_collection_signature(self, items: object) -> Tuple[str, ...]:
"""Build a stable identity signature for a query_memory hit collection."""
if not isinstance(items, list):
return tuple()
signature = []
for item in items:
if not isinstance(item, dict):
signature.append(json.dumps(item, ensure_ascii=False, sort_keys=True))
continue
signature.append(
"|".join(
[
str(item.get("key") or ""),
str(item.get("id") or ""),
str(item.get("source") or item.get("source_type") or ""),
str(item.get("project_slug") or ""),
str(item.get("title") or ""),
]
)
)
return tuple(signature)
def _query_memory_item_score(self, item: object) -> float:
"""Return a retrieval score for ordering visible query_memory hits."""
if not isinstance(item, dict):
return 0.0
for key in ["score", "rrf_score"]:
try:
return float(item.get(key) or 0.0)
except (TypeError, ValueError):
continue
metadata = dict(item.get("metadata") or {})
try:
return float(metadata.get("score") or metadata.get("rrf_score") or 0.0)
except (TypeError, ValueError):
return 0.0
def _append_query_memory_collection_with_budget(
self,
target: Dict[str, object],
key: str,
items: List[object],
*,
query: str,
budget_tokens: int,
) -> int:
"""Append scored query_memory hits until the remaining visible budget is exhausted."""
remaining = max(0, int(budget_tokens))
if remaining <= 0:
return 0
ordered = sorted(
[self._dedupe_query_memory_item(item) for item in items],
key=self._query_memory_item_score,
reverse=True,
)
kept = []
for item in ordered:
if remaining <= 0:
break
item_budget = remaining
trimmed = self._trim_query_memory_item_to_budget(item, query=query, token_budget=item_budget)
cost = self._estimate_query_memory_visible_tokens(trimmed)
if cost > remaining:
continue
kept.append(trimmed)
remaining -= cost
if kept:
target[key] = kept
return max(0, int(budget_tokens) - remaining)
def _visible_query_memory_output(self, output: Dict[str, object]) -> Dict[str, object]:
"""Deduplicate query_memory output before it is sent back to the main model."""
compact: Dict[str, object] = {}
scalar_keys = [
"query",
"scope",
"project_scope",
"all_projects",
"types",
"channels",
"channel_mode",
"limit_per_channel",
"prefer_raw",
"summary",
"raw_record_locations",
]
for key in scalar_keys:
if key in output:
compact[key] = output.get(key)
query = str(output.get("query") or "")
if self._estimate_query_memory_visible_tokens(compact) > QUERY_MEMORY_VISIBLE_TOKEN_BUDGET:
compact["summary"] = self._trim_query_memory_text(
str(compact.get("summary") or ""),
query=query,
anchor=query,
token_budget=max(128, QUERY_MEMORY_VISIBLE_TOKEN_BUDGET // 10),
)
used_budget = self._estimate_query_memory_visible_tokens(compact)
remaining_budget = max(0, QUERY_MEMORY_VISIBLE_TOKEN_BUDGET - used_budget)
if isinstance(output.get("results"), list) and remaining_budget > 0:
used = self._append_query_memory_collection_with_budget(
compact,
"results",
list(output.get("results") or []),
query=query,
budget_tokens=remaining_budget,
)
remaining_budget = max(0, remaining_budget - used)
if isinstance(output.get("compressed_windows"), list) and remaining_budget > 0:
used = self._append_query_memory_collection_with_budget(
compact,
"compressed_windows",
list(output.get("compressed_windows") or []),
query=query,
budget_tokens=remaining_budget,
)
remaining_budget = max(0, remaining_budget - used)
seen_collections = set()
collection_keys = [
"sources",
"research_log_hits",
"research_hits",
"dynamic_hits",
"session_hits",
"event_hits",
"tool_event_hits",
"knowledge_hits",
"graph_hits",
]
for key in collection_keys:
items = output.get(key)
if not isinstance(items, list) or not items:
continue
signature = self._query_memory_collection_signature(items)
if signature and signature in seen_collections:
continue
if signature:
seen_collections.add(signature)
if remaining_budget <= 0:
continue
used = self._append_query_memory_collection_with_budget(
compact,
key,
list(items),
query=query,
budget_tokens=remaining_budget,
)
remaining_budget = max(0, remaining_budget - used)
compact_tokens = self._estimate_query_memory_visible_tokens(compact)
if compact_tokens > QUERY_MEMORY_VISIBLE_TOKEN_BUDGET:
compact["summary"] = self._trim_query_memory_text(
str(compact.get("summary") or ""),
query=query,
anchor=query,
token_budget=512,
)
return compact
def _visible_tool_output(self, result: Dict[str, object]) -> object:
"""Return the compact tool-result payload that should remain visible to the main model."""
name = str(result.get("name") or "").strip()
output = dict(result.get("output") or {})
if name == "query_memory":
return self._visible_query_memory_output(output)
structured_research_recorders = {
"record_solve_attempt",
"record_failed_path",
}
if name in structured_research_recorders:
compact = {
"status": "recorded" if not result.get("error") else "error",
"id": str(output.get("id") or ""),
"artifact_type": str(output.get("artifact_type") or ""),
"channel": str(output.get("channel") or ""),
"path": str(output.get("content_path") or output.get("artifact_path") or ""),
}
return {key: value for key, value in compact.items() if value}
if name in {"store_conclusion", "add_knowledge"}:
compact = {
"status": str(output.get("status") or ""),
"stored_as": str(output.get("stored_as") or ""),
"id": str(output.get("id") or output.get("artifact_id") or ""),
"path": str(output.get("path") or output.get("artifact_path") or ""),
"reason": str(output.get("reason") or ""),
}
return {key: value for key, value in compact.items() if value}
return output
def record_tool_result_message(self, provider_messages: List[Dict[str, object]], result: Dict[str, object]) -> None:
"""Append a tool result message to the provider transcript."""
provider_messages.append(
{
"role": "tool",
"tool_call_id": result["call_id"],
"content": json.dumps(
{
"name": result["name"],
"output": self._visible_tool_output(result),
"error": result.get("error"),
},
ensure_ascii=False,
),
}
)
def _record_tool_results(
self,
state: ConversationState,
results: Sequence[Dict[str, object]],
):
"""Persist tool results, append them to the provider transcript, and emit events."""
for result in results:
event_payload = {
"tool": result["name"],
"call_id": result["call_id"],
"arguments": result["arguments"],
"output": result["output"],
"error": result.get("error"),
"tool_round": state.tool_rounds,
"created_at": utc_now(),
}
self.session_store.append_tool_event(state.session_id, event_payload)
self._append_turn_transcript(
state,
{
"kind": "tool_result",
"tool": result["name"],
"call_id": result["call_id"],
"arguments": result["arguments"],
"output": result["output"],
"error": result.get("error"),
"tool_round": state.tool_rounds,
"created_at": event_payload["created_at"],
},
)
self.record_tool_result_message(state.provider_messages, result)
self._record_turn_event(
state.session_id,
"tool_result" if not result.get("error") else "tool_error",
result["name"],
tool_round=state.tool_rounds,
call_id=result["call_id"],
error=result.get("error"),
)
if state.mode == "research":
try:
self.research_workflow.observe_tool_result(