| 34 | |
| 35 | @dataclass |
| 36 | class QueryEnginePort: |
| 37 | manifest: PortManifest |
| 38 | config: QueryEngineConfig = field(default_factory=QueryEngineConfig) |
| 39 | session_id: str = field(default_factory=lambda: uuid4().hex) |
| 40 | mutable_messages: list[str] = field(default_factory=list) |
| 41 | permission_denials: list[PermissionDenial] = field(default_factory=list) |
| 42 | total_usage: UsageSummary = field(default_factory=UsageSummary) |
| 43 | transcript_store: TranscriptStore = field(default_factory=TranscriptStore) |
| 44 | |
| 45 | @classmethod |
| 46 | def from_workspace(cls) -> 'QueryEnginePort': |
| 47 | return cls(manifest=build_port_manifest()) |
| 48 | |
| 49 | @classmethod |
| 50 | def from_saved_session(cls, session_id: str) -> 'QueryEnginePort': |
| 51 | stored = load_session(session_id) |
| 52 | transcript = TranscriptStore(entries=list(stored.messages), flushed=True) |
| 53 | return cls( |
| 54 | manifest=build_port_manifest(), |
| 55 | session_id=stored.session_id, |
| 56 | mutable_messages=list(stored.messages), |
| 57 | total_usage=UsageSummary(stored.input_tokens, stored.output_tokens), |
| 58 | transcript_store=transcript, |
| 59 | ) |
| 60 | |
| 61 | def submit_message( |
| 62 | self, |
| 63 | prompt: str, |
| 64 | matched_commands: tuple[str, ...] = (), |
| 65 | matched_tools: tuple[str, ...] = (), |
| 66 | denied_tools: tuple[PermissionDenial, ...] = (), |
| 67 | ) -> TurnResult: |
| 68 | if len(self.mutable_messages) >= self.config.max_turns: |
| 69 | output = f'Max turns reached before processing prompt: {prompt}' |
| 70 | return TurnResult( |
| 71 | prompt=prompt, |
| 72 | output=output, |
| 73 | matched_commands=matched_commands, |
| 74 | matched_tools=matched_tools, |
| 75 | permission_denials=denied_tools, |
| 76 | usage=self.total_usage, |
| 77 | stop_reason='max_turns_reached', |
| 78 | ) |
| 79 | |
| 80 | summary_lines = [ |
| 81 | f'Prompt: {prompt}', |
| 82 | f'Matched commands: {", ".join(matched_commands) if matched_commands else "none"}', |
| 83 | f'Matched tools: {", ".join(matched_tools) if matched_tools else "none"}', |
| 84 | f'Permission denials: {len(denied_tools)}', |
| 85 | ] |
| 86 | output = self._format_output(summary_lines) |
| 87 | projected_usage = self.total_usage.add_turn(prompt, output) |
| 88 | stop_reason = 'completed' |
| 89 | if projected_usage.input_tokens + projected_usage.output_tokens > self.config.max_budget_tokens: |
| 90 | stop_reason = 'max_budget_reached' |
| 91 | self.mutable_messages.append(prompt) |
| 92 | self.transcript_store.append(prompt) |
| 93 | self.permission_denials.extend(denied_tools) |