|
| 1 | +"""Concrete ``SearchLauncher`` — the self-facing async agentic-search backend. |
| 2 | +
|
| 3 | +Bridges the down-only ``mewbo_graph.scg.search_launcher.SearchLauncher`` seam to |
| 4 | +THIS app's run lifecycle so a task-spawned engine agent's ``agentic_search`` |
| 5 | +tool call drives a real ``scg-search`` run — reusing :class:`SearchRun.start` |
| 6 | +and the run store — WITHOUT the engine importing up into the app. The exact |
| 7 | +counterpart of ``_register_map_phase_sink``: the engine can't reach the run |
| 8 | +store/runtime, so the api injects a writer here at startup. |
| 9 | +
|
| 10 | +Async-by-handle: :meth:`start` hands off to the (orchestrated) runner, which |
| 11 | +returns a ``running`` snapshot promptly; we surface the ``run_id`` immediately |
| 12 | +so the calling agent never blocks on a multi-minute session. A run that settled |
| 13 | +synchronously (the echo runner) — or an idempotent reuse of a recent completed |
| 14 | +run for the same question — is returned fully formed. :meth:`fetch` projects the |
| 15 | +durable snapshot (cited answer + ``computed_at``). |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +from dataclasses import dataclass |
| 21 | +from typing import Any |
| 22 | + |
| 23 | +from mewbo_core.common import get_logger |
| 24 | + |
| 25 | +from . import store as store_mod |
| 26 | +from .runs import SearchRun |
| 27 | +from .schemas import TERMINAL_RUN_STATUSES, RunRecord, Workspace |
| 28 | + |
| 29 | +logging = get_logger(name="api.agentic_search.search_launcher_impl") |
| 30 | + |
| 31 | +# Keep the agent-facing result list compact — a task agent wants the cited |
| 32 | +# answer + an index it can cite, not the full console payload. |
| 33 | +_MAX_RESULTS = 25 |
| 34 | + |
| 35 | + |
| 36 | +@dataclass(frozen=True) |
| 37 | +class RunStoreSearchLauncher: |
| 38 | + """A :class:`SearchLauncher` impl over the api run store + session runtime.""" |
| 39 | + |
| 40 | + runtime: Any = None |
| 41 | + |
| 42 | + # -- launcher protocol -------------------------------------------------- |
| 43 | + |
| 44 | + def start( |
| 45 | + self, query: str, *, workspace: str | None = None, tier: str | None = None |
| 46 | + ) -> dict[str, object]: |
| 47 | + """Resolve the workspace, idempotently reuse or launch a run, return it.""" |
| 48 | + store = store_mod.get_store() |
| 49 | + ws = self._resolve_workspace(store, workspace) |
| 50 | + |
| 51 | + reuse = self._recent_completed(store, ws.id, query) |
| 52 | + if reuse is not None: |
| 53 | + snap = self._shape(reuse) |
| 54 | + snap["reused"] = True |
| 55 | + return snap |
| 56 | + |
| 57 | + payload = SearchRun.start( |
| 58 | + workspace_id=ws.id, |
| 59 | + query=query, |
| 60 | + store=store, |
| 61 | + runtime=self.runtime, |
| 62 | + tier=tier, |
| 63 | + source_platform="agent", |
| 64 | + ) |
| 65 | + if payload is None: # pragma: no cover — ws resolved above |
| 66 | + raise ValueError(f"workspace '{ws.id}' is no longer available") |
| 67 | + |
| 68 | + # A synchronous (echo) or already-terminal run: return the full snapshot |
| 69 | + # so the agent gets its answer in one call. An async run is still |
| 70 | + # ``running`` — hand back the resumable handle. |
| 71 | + if payload.status in TERMINAL_RUN_STATUSES: |
| 72 | + record = store.get_run(payload.run_id) |
| 73 | + if record is not None: |
| 74 | + return self._shape(record) |
| 75 | + return { |
| 76 | + "run_id": payload.run_id, |
| 77 | + "session_id": payload.session_id, |
| 78 | + "workspace_id": ws.id, |
| 79 | + "workspace": ws.name, |
| 80 | + "query": query, |
| 81 | + "tier": payload.tier, |
| 82 | + "status": "processing" if payload.status == "running" else payload.status, |
| 83 | + "note": ( |
| 84 | + "The search is running in its own session. Call agentic_search " |
| 85 | + "again with this run_id to retrieve the cited answer when ready." |
| 86 | + ), |
| 87 | + } |
| 88 | + |
| 89 | + def fetch(self, run_id: str) -> dict[str, object] | None: |
| 90 | + """Return the run's last-known snapshot, or ``None`` if unknown.""" |
| 91 | + record = store_mod.get_store().get_run(run_id) |
| 92 | + if record is None: |
| 93 | + return None |
| 94 | + return self._shape(record) |
| 95 | + |
| 96 | + # -- internals ---------------------------------------------------------- |
| 97 | + |
| 98 | + @staticmethod |
| 99 | + def _resolve_workspace(store: Any, ref: str | None) -> Workspace: |
| 100 | + """Resolve *ref* (id or unique name) → a workspace; raise with guidance. |
| 101 | +
|
| 102 | + Mirrors the MCP ``_resolve_workspace`` ergonomics so the self and |
| 103 | + outside surfaces resolve identically: exact id first, then a unique |
| 104 | + case-insensitive name. With no ref, default to the only workspace; raise |
| 105 | + a list-bearing error when zero or several exist so the agent can pick. |
| 106 | + """ |
| 107 | + workspaces = store.list_workspaces() |
| 108 | + if not workspaces: |
| 109 | + raise ValueError("no search workspaces are configured") |
| 110 | + if not ref: |
| 111 | + if len(workspaces) == 1: |
| 112 | + return workspaces[0] |
| 113 | + names = sorted(w.name for w in workspaces) |
| 114 | + raise ValueError( |
| 115 | + "several workspaces exist — pass 'workspace' (id or name). " |
| 116 | + f"Available: {names}" |
| 117 | + ) |
| 118 | + for ws in workspaces: |
| 119 | + if ws.id == ref: |
| 120 | + return ws |
| 121 | + matches = [w for w in workspaces if w.name.lower() == ref.lower()] |
| 122 | + if len(matches) == 1: |
| 123 | + return matches[0] |
| 124 | + names = sorted(w.name for w in workspaces) |
| 125 | + if not matches: |
| 126 | + raise ValueError(f"no workspace matches '{ref}'. Available: {names}") |
| 127 | + raise ValueError(f"workspace name '{ref}' is ambiguous — use its id. Names: {names}") |
| 128 | + |
| 129 | + @staticmethod |
| 130 | + def _recent_completed( |
| 131 | + store: Any, workspace_id: str, query: str |
| 132 | + ) -> RunRecord | None: |
| 133 | + """The most recent COMPLETED run for the exact same query, or ``None``. |
| 134 | +
|
| 135 | + Gives the "re-invoke the same query → last-known answer" idempotency: |
| 136 | + an identical question returns its prior cited answer (+ ``computed_at``) |
| 137 | + instead of launching a duplicate session. Exact-match on the query text |
| 138 | + only (a different question, or a not-yet-completed run, launches anew). |
| 139 | + """ |
| 140 | + runs = store.list_runs(workspace_id) |
| 141 | + best: RunRecord | None = None |
| 142 | + for run in runs: |
| 143 | + if run.status != "completed" or run.query != query: |
| 144 | + continue |
| 145 | + if best is None or (run.created_at or "") > (best.created_at or ""): |
| 146 | + best = run |
| 147 | + return best |
| 148 | + |
| 149 | + @classmethod |
| 150 | + def _shape(cls, record: RunRecord) -> dict[str, object]: |
| 151 | + """Project a :class:`RunRecord` into the compact agent-facing snapshot. |
| 152 | +
|
| 153 | + The cited synthesis + a compact result index (so citations resolve) + |
| 154 | + ``computed_at`` (when the answer was calculated) — never the per-source |
| 155 | + trace or decorative fields. |
| 156 | + """ |
| 157 | + payload = record.payload |
| 158 | + answer = payload.answer if payload is not None else None |
| 159 | + results = payload.results[:_MAX_RESULTS] if payload is not None else [] |
| 160 | + status = "processing" if record.status == "running" else record.status |
| 161 | + out: dict[str, object] = { |
| 162 | + "run_id": record.run_id, |
| 163 | + "session_id": record.session_id, |
| 164 | + "workspace_id": record.workspace_id, |
| 165 | + "query": record.query, |
| 166 | + "tier": record.tier, |
| 167 | + "status": status, |
| 168 | + "total_ms": record.total_ms, |
| 169 | + # When the answer was calculated — None while still processing. |
| 170 | + "computed_at": record.completed_at, |
| 171 | + "results": [ |
| 172 | + { |
| 173 | + "id": r.id, |
| 174 | + "source": r.source, |
| 175 | + "kind": r.kind, |
| 176 | + "title": r.title, |
| 177 | + "url": r.url, |
| 178 | + "relevance": r.relevance, |
| 179 | + } |
| 180 | + for r in results |
| 181 | + ], |
| 182 | + } |
| 183 | + if answer is not None: |
| 184 | + out["answer"] = { |
| 185 | + "tldr": answer.tldr, |
| 186 | + "bullets": [ |
| 187 | + {"text": b.text, "cites": list(b.cites)} for b in answer.bullets |
| 188 | + ], |
| 189 | + "confidence": answer.confidence, |
| 190 | + "sources_count": answer.sources_count, |
| 191 | + } |
| 192 | + if payload is not None and payload.related_questions: |
| 193 | + out["related_questions"] = list(payload.related_questions) |
| 194 | + if payload is not None and payload.error: |
| 195 | + out["error"] = payload.error |
| 196 | + return out |
| 197 | + |
| 198 | + |
| 199 | +__all__ = ["RunStoreSearchLauncher"] |
0 commit comments