yf176 commited on
Commit
331ce90
Β·
1 Parent(s): f06c440

feat: non-blocking Scout 429 + human takeover via @scout results: <paste>

Browse files
src/polyhedra/agents/coordinator.py CHANGED
@@ -326,6 +326,8 @@ class CoordinatorService:
326
  def _apply_state_update(self, response: AgentResponse) -> None:
327
  """Patch the Research State from agent response metadata."""
328
  manager = ResearchStateManager(self.session.session_dir)
 
 
329
  papers_raw = response.metadata.get("papers", [])
330
  if papers_raw:
331
  papers = [
@@ -339,7 +341,11 @@ class CoordinatorService:
339
  )
340
  for p in papers_raw
341
  ]
342
- current = manager.load()
343
  current.key_papers = papers
344
- current.compress()
345
- manager.save(current)
 
 
 
 
 
 
326
  def _apply_state_update(self, response: AgentResponse) -> None:
327
  """Patch the Research State from agent response metadata."""
328
  manager = ResearchStateManager(self.session.session_dir)
329
+ current = manager.load()
330
+
331
  papers_raw = response.metadata.get("papers", [])
332
  if papers_raw:
333
  papers = [
 
341
  )
342
  for p in papers_raw
343
  ]
 
344
  current.key_papers = papers
345
+
346
+ pending_task = response.metadata.get("pending_task")
347
+ if pending_task and pending_task not in current.pending_tasks:
348
+ current.pending_tasks.append(pending_task)
349
+
350
+ current.compress()
351
+ manager.save(current)
src/polyhedra/agents/scout.py CHANGED
@@ -47,6 +47,34 @@ class ScoutAgent(Agent):
47
  thread_context: list[dict[str, Any]],
48
  research_state: dict[str, Any],
49
  ) -> AgentResponse:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  query = self._extract_query(mention, research_state)
51
  if not query:
52
  return AgentResponse(
@@ -59,6 +87,36 @@ class ScoutAgent(Agent):
59
  self.logger.info("Scout searching for: %s", query)
60
  papers = await self._search(query)
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  if not papers:
63
  return AgentResponse(
64
  agent_role=self.role,
@@ -110,12 +168,15 @@ class ScoutAgent(Agent):
110
  # Fall back to session goal
111
  return research_state.get("goal", "")
112
 
113
- async def _search(self, query: str) -> list[dict[str, Any]]:
114
- """Execute search and return deduplicated paper list (max 50)."""
115
  try:
116
  results = await self._scholar.search(query=query, limit=_MAX_PAPERS)
117
  except Exception as exc:
118
  logger.error("Semantic Scholar search failed: %s", exc)
 
 
 
119
  return []
120
 
121
  if not results:
 
47
  thread_context: list[dict[str, Any]],
48
  research_state: dict[str, Any],
49
  ) -> AgentResponse:
50
+ import re as _re
51
+
52
+ raw_text = mention.content
53
+
54
+ # ── Human takeover: paste results back ──────────────────────────
55
+ # Triggered when human replies with:
56
+ # @scout results: <pasted titles/text>
57
+ # @scout here are the results: ...
58
+ handoff_match = _re.match(
59
+ r"(?:here\s+are\s+the\s+results|results)\s*:\s*(.*)",
60
+ _re.sub(r"@scout\b", "", raw_text, flags=_re.IGNORECASE).strip(),
61
+ _re.IGNORECASE | _re.DOTALL,
62
+ )
63
+ if handoff_match:
64
+ pasted = handoff_match.group(1).strip()
65
+ content = (
66
+ "πŸ” **Scout** β€” Thanks for the manual results! "
67
+ "Formatting and handing off to Strategist.\n\n"
68
+ f"{pasted}"
69
+ )
70
+ return AgentResponse(
71
+ agent_role=self.role,
72
+ content=content,
73
+ mentions=["strategist"],
74
+ updates_state=False,
75
+ )
76
+ # ────────────────────────────────────────────────────────────────
77
+
78
  query = self._extract_query(mention, research_state)
79
  if not query:
80
  return AgentResponse(
 
87
  self.logger.info("Scout searching for: %s", query)
88
  papers = await self._search(query)
89
 
90
+ if isinstance(papers, Exception):
91
+ exc = papers
92
+ msg = str(exc)
93
+ encoded_query = query.replace(" ", "+")
94
+ search_url = (
95
+ f"https://www.semanticscholar.org/search?q={encoded_query}&sort=Relevance"
96
+ )
97
+ if "429" in msg or "rate limit" in msg.lower():
98
+ reason = "rate-limited by Semantic Scholar (HTTP 429)"
99
+ else:
100
+ reason = f"search error: {msg}"
101
+
102
+ task = f"Scout: search '{query}' β€” {reason}. Manual link: {search_url}"
103
+
104
+ content = (
105
+ f"πŸ” **Scout** β€” I got {reason} and couldn't complete the search.\n\n"
106
+ f"I've logged it as a pending task and am handing off to Strategist so the team can keep moving.\n\n"
107
+ f"**Manual search URL:** {search_url}\n\n"
108
+ f"πŸ’‘ *You can take over: search manually, then reply with:*\n"
109
+ f"`@PolyTest @scout results: <paste paper titles/summaries here>`"
110
+ )
111
+ return AgentResponse(
112
+ agent_role=self.role,
113
+ content=content,
114
+ error=msg,
115
+ mentions=["strategist"],
116
+ updates_state=True,
117
+ metadata={"pending_task": task},
118
+ )
119
+
120
  if not papers:
121
  return AgentResponse(
122
  agent_role=self.role,
 
168
  # Fall back to session goal
169
  return research_state.get("goal", "")
170
 
171
+ async def _search(self, query: str) -> list[dict[str, Any]] | Exception:
172
+ """Execute search and return deduplicated paper list (max 50), or an Exception on failure."""
173
  try:
174
  results = await self._scholar.search(query=query, limit=_MAX_PAPERS)
175
  except Exception as exc:
176
  logger.error("Semantic Scholar search failed: %s", exc)
177
+ return exc
178
+
179
+ if not results:
180
  return []
181
 
182
  if not results:
src/polyhedra/core/research_state.py CHANGED
@@ -82,6 +82,7 @@ class ResearchState:
82
  key_papers: list[Paper] = dc_field(default_factory=list)
83
  decisions: list[Decision] = dc_field(default_factory=list)
84
  open_questions: list[str] = dc_field(default_factory=list)
 
85
  last_updated: datetime = dc_field(default_factory=lambda: datetime.now(tz=timezone.utc))
86
  version: int = 1
87
 
@@ -109,6 +110,7 @@ class ResearchState:
109
  state.goal = data.get("goal", "")
110
  state.field = data.get("field", "")
111
  state.open_questions = data.get("open_questions", [])
 
112
  state.version = data.get("version", 1)
113
  last_updated = data.get("last_updated")
114
  if last_updated:
@@ -166,6 +168,7 @@ class ResearchState:
166
  lines += self._markdown_hypothesis()
167
  lines += self._markdown_papers()
168
  lines += self._markdown_questions()
 
169
  lines += self._markdown_decisions()
170
  return "\n".join(lines)
171
 
@@ -215,6 +218,14 @@ class ResearchState:
215
  lines.append("")
216
  return lines
217
 
 
 
 
 
 
 
 
 
218
  def _markdown_decisions(self) -> list[str]:
219
  if not self.decisions:
220
  return []
 
82
  key_papers: list[Paper] = dc_field(default_factory=list)
83
  decisions: list[Decision] = dc_field(default_factory=list)
84
  open_questions: list[str] = dc_field(default_factory=list)
85
+ pending_tasks: list[str] = dc_field(default_factory=list) # blocked/deferred tasks for the team
86
  last_updated: datetime = dc_field(default_factory=lambda: datetime.now(tz=timezone.utc))
87
  version: int = 1
88
 
 
110
  state.goal = data.get("goal", "")
111
  state.field = data.get("field", "")
112
  state.open_questions = data.get("open_questions", [])
113
+ state.pending_tasks = data.get("pending_tasks", [])
114
  state.version = data.get("version", 1)
115
  last_updated = data.get("last_updated")
116
  if last_updated:
 
168
  lines += self._markdown_hypothesis()
169
  lines += self._markdown_papers()
170
  lines += self._markdown_questions()
171
+ lines += self._markdown_pending()
172
  lines += self._markdown_decisions()
173
  return "\n".join(lines)
174
 
 
218
  lines.append("")
219
  return lines
220
 
221
+ def _markdown_pending(self) -> list[str]:
222
+ if not self.pending_tasks:
223
+ return []
224
+ lines = ["", "### πŸ“‹ Pending / Blocked Tasks", ""]
225
+ for task in self.pending_tasks:
226
+ lines.append(f"- [ ] {task}")
227
+ return lines
228
+
229
  def _markdown_decisions(self) -> list[str]:
230
  if not self.decisions:
231
  return []