Spaces:
Sleeping

File size: 17,118 Bytes
d176097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab719c7
 
 
 
d176097
 
 
ab719c7
d176097
ab719c7
d176097
 
2a95ee9
 
 
 
 
 
 
 
 
 
d176097
 
 
 
 
2a95ee9
d176097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
pipeline.py
-----------
Multi-agent pipeline orchestrator for CollabCode.

Architecture: Parallel Map with Context Chain
=============================================

                β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  Transcript    β”‚   Agent 0 (1 LLM call, whole transcript)            β”‚
  ─────────────►│   Produces: section map + handoff documents         β”‚
                β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                   β”‚ handoff doc per section
                β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                β”‚  Parallel Agent 1a  (N concurrent LLM calls)        β”‚
  Human confirmsβ”‚  Each section: boundary detection with section ctx  β”‚
  sections  ───►│  Produces: boundary results + episode handoffs       β”‚
                β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                   β”‚ boundary handoff per section
                β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                β”‚  Agent 1b (sequential per section after human review)β”‚
  Human adjusts β”‚  Coding with boundary context from Agent 1a         β”‚
  boundaries ──►│  Produces: coded segments                           β”‚
                β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Key design patterns
-------------------

1. Parallel Map (Agent 1a)
   Sections are causally independent β€” Agent 0 fixes their boundaries
   before 1a runs, so 1a sections can execute concurrently.
   ThreadPoolExecutor with max_workers=3 limits API rate pressure.
   Literature:
     Dean & Ghemawat (2004). MapReduce: Simplified data processing on large
       clusters. OSDI 2004. β€” parallel map over independent partitions.
     Wu et al. (2023). AutoGen: Enabling next-gen LLM applications via
       multi-agent conversation. arXiv:2308.08155.
       β€” concurrent agent execution model.

2. Context Chain (handoff documents)
   Each agent writes a structured memo that the next agent reads.
   This reduces cold-start errors at agent handoffs and gives Agent 1b
   the boundary rationale rather than starting from zero.
   Literature:
     Park et al. (2023). Generative agents: Interactive simulacra of
       human behavior. UIST 2023. β€” agents maintain and pass memory
       summaries to downstream consumers.
     Hong et al. (2023). MetaGPT: Meta programming for multi-agent
       collaborative framework. ICLR 2024.
       β€” structured output documents flowing between agents.
     Shinn et al. (2023). Reflexion: Language agents with verbal
       reinforcement learning. NeurIPS 2023.
       β€” agents build context from prior observations.

3. Progress streaming
   A threading.Queue bridges the parallel worker threads to the
   Gradio generator, emitting one yield per completed section.
   The researcher sees a live table update rather than a frozen UI.
   Literature:
     Nielsen, J. (1994). Usability Engineering, ch.8. Academic Press.
       β€” response feedback within 10s required to maintain user flow.

4. Stats tracking (PipelineStats)
   Every call records wall time, estimated tokens, retries, and timeout.
   Speedup vs. sequential is computed and shown in the UI.
   Literature:
     Sigelman et al. (2010). Dapper: A Large-Scale Distributed Systems
       Tracing Infrastructure. Google Technical Report.
       β€” distributed tracing for latency analysis.

5. Circuit-breaker awareness
   Workers check llm_client._circuit_breaker before dispatching.
   Failed sections are marked ERROR and returned to the researcher
   rather than silently dropped or retried indefinitely.
"""

from __future__ import annotations

import queue
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from typing import Callable, Iterator, Optional

from llm_client import call_llm_timed, LLMCallStats, circuit_state

# Maximum parallel workers for Agent 1a.
# 3 balances latency vs. HF Inference API rate limits (typically ~5 req/min
# for free tier; 3 leaves headroom for retries).
MAX_PARALLEL_WORKERS = 3


# ---------------------------------------------------------------------------
# Data structures
# ---------------------------------------------------------------------------

@dataclass
class SectionResult:
    """Outcome of one Agent 1a or Agent 1b call for a single section."""
    section_id:   str
    section_label: str
    success:      bool
    result:       Optional[dict]       # the agent's output dict
    stats:        Optional[LLMCallStats]
    wall_time_s:  float
    error:        Optional[str] = None

    @property
    def status_icon(self) -> str:
        if self.success:
            return "βœ“"
        return "βœ—"


@dataclass
class PipelineStats:
    """Aggregate statistics for the full pipeline run."""
    agent_name:        str
    n_sections:        int
    results:           list[SectionResult] = field(default_factory=list)
    parallel_wall_s:   float = 0.0
    sequential_est_s:  float = 0.0   # what it would have taken serially

    @property
    def n_success(self) -> int:
        return sum(1 for r in self.results if r.success)

    @property
    def n_error(self) -> int:
        return sum(1 for r in self.results if not r.success)

    @property
    def speedup(self) -> float:
        if self.parallel_wall_s <= 0:
            return 1.0
        return round(self.sequential_est_s / self.parallel_wall_s, 1)

    @property
    def total_estimated_tokens(self) -> int:
        return sum(
            r.stats.estimated_total_tok
            for r in self.results
            if r.stats and r.success
        )

    def summary_line(self) -> str:
        spd = f"{self.speedup:.1f}Γ—" if self.speedup > 1.1 else "β€”"
        return (
            f"{self.n_success}/{self.n_sections} OK Β· "
            f"{self.parallel_wall_s:.0f}s wall Β· "
            f"~{self.speedup:.1f}Γ— faster than serial Β· "
            f"~{self.total_estimated_tokens:,} tokens"
        )


# ---------------------------------------------------------------------------
# Handoff document builders
# ---------------------------------------------------------------------------

def build_agent0_section_handoff(section: dict, session_overview: str) -> dict:
    """
    Package the context that Agent 0 produces for one section
    into the format Agent 1a will consume.
    """
    return {
        "session_overview": session_overview,
        "section_id":       section.get("section_id", ""),
        "section_label":    section.get("label", ""),
        "section_summary":  section.get("summary", ""),
        "start_time":       section.get("start_time", ""),
        "end_time":         section.get("end_time", ""),
    }


def build_agent1a_boundary_handoff(section: dict, agent1a_result: dict) -> dict:
    """
    Package Agent 1a's boundary analysis for Agent 1b to consume.

    Agent 1b receives the boundary rationale and episode distribution so it
    can calibrate its coding to the local conversational structure rather
    than starting cold (Park et al. 2023 β€” agent memory passing).
    """
    boundaries   = agent1a_result.get("boundaries", [])
    segments     = agent1a_result.get("segments", [])
    n_boundaries = len(boundaries)

    # Summarise the boundary signals found
    signal_counts: dict[str, int] = {}
    for b in boundaries:
        sig = b.get("boundary_signal", "unknown")
        signal_counts[sig] = signal_counts.get(sig, 0) + 1

    signal_summary = "; ".join(
        f"{n} {sig.replace('_', ' ')}" for sig, n in signal_counts.items()
    ) or "no boundaries β€” single episode"

    # Build short episode previews for Agent 1b context
    episode_previews = []
    for seg in segments[:6]:  # cap at 6 to avoid prompt bloat
        turns = seg.get("turns", [])
        if turns:
            episode_previews.append({
                "segment_id": seg["segment_id"],
                "first_turn": turns[0].get("text", "")[:80],
            })

    return {
        "section_id":       section.get("section_id", ""),
        "section_label":    section.get("label", ""),
        "section_summary":  section.get("summary", ""),
        "n_boundaries":     n_boundaries,
        "n_episodes":       len(segments),
        "boundary_signals": signal_summary,
        "episode_previews": episode_previews,
    }


# ---------------------------------------------------------------------------
# Parallel Agent 1a runner
# ---------------------------------------------------------------------------

def run_boundaries_parallel(
    sections:          list[dict],
    all_turns:         list[dict],
    session_id:        str,
    session_overview:  str = "",
    max_workers:       int = MAX_PARALLEL_WORKERS,
) -> Iterator[tuple[SectionResult, PipelineStats]]:
    """
    Run Agent 1a on all sections concurrently.

    Yields (SectionResult, PipelineStats_so_far) after each section completes
    so callers can stream progress. The final yield contains the complete stats.

    Design
    ------
    Uses a threading.Queue to bridge worker threads and the caller's
    generator loop (Nielsen 1994 β€” live feedback prevents perceived freeze).
    Workers share a ThreadPoolExecutor; results arrive in completion order,
    not submission order (as_completed pattern).

    Args
    ----
    sections         : confirmed section list from Agent 0 + human review.
    all_turns        : full parsed turn list for the session.
    session_id       : used for segment ID namespacing.
    session_overview : Agent 0's session-level summary (context chain).
    max_workers      : parallel worker cap (default 3 to respect API limits).
    """
    from agent1a_boundary import propose_boundaries_with_context

    result_q: queue.Queue[SectionResult | None] = queue.Queue()
    t_wall_start = time.perf_counter()
    stats        = PipelineStats(
        agent_name="Agent 1a β€” Boundary Detector",
        n_sections=len(sections),
    )

    def _worker(sec: dict) -> None:
        turns     = [t for t in all_turns
                     if sec["start_turn_id"] <= t["turn_id"] <= sec["end_turn_id"]]
        t0        = time.perf_counter()
        handoff_in = build_agent0_section_handoff(sec, session_overview)

        try:
            result, llm_stats = propose_boundaries_with_context(
                section=sec,
                turns=turns,
                session_id=session_id,
                agent0_handoff=handoff_in,
            )
            sr = SectionResult(
                section_id=sec["section_id"],
                section_label=sec.get("label", ""),
                success=True,
                result=result,
                stats=llm_stats,
                wall_time_s=round(time.perf_counter() - t0, 1),
            )
        except Exception as exc:
            sr = SectionResult(
                section_id=sec["section_id"],
                section_label=sec.get("label", ""),
                success=False,
                result=None,
                stats=None,
                wall_time_s=round(time.perf_counter() - t0, 1),
                error=str(exc),
            )
        result_q.put(sr)

    # Dispatch all workers without blocking β€” results stream into the queue
    # as each section completes, so the caller receives live updates.
    # (Calling shutdown(wait=True) here would block until ALL workers finish,
    # defeating the streaming purpose and freezing the UI for the full batch.)
    executor = ThreadPoolExecutor(max_workers=max_workers)
    for sec in sections:
        executor.submit(_worker, sec)
    executor.shutdown(wait=False)   # non-blocking: workers run in background

    # Yield results in completion order as they arrive in the queue
    n_received = 0
    while n_received < len(sections):
        try:
            sr = result_q.get(timeout=_TIMEOUT_MAX_WAIT)
        except queue.Empty:
            remaining = len(sections) - n_received
            raise RuntimeError(
                f"Timed out waiting for {remaining} section result(s) after "
                f"{_TIMEOUT_MAX_WAIT}s. The HF Inference API may be overloaded "
                "or unreachable. Check your HF_TOKEN and retry."
            )

        stats.results.append(sr)
        n_received += 1

        if n_received == len(sections):
            stats.parallel_wall_s  = round(time.perf_counter() - t_wall_start, 1)
            stats.sequential_est_s = sum(r.wall_time_s for r in stats.results)

        yield sr, stats


_TIMEOUT_MAX_WAIT = 360   # max seconds to wait for any single section result


# ---------------------------------------------------------------------------
# Sequential Agent 1b runner (per-section, after human boundary review)
# ---------------------------------------------------------------------------

def run_coding_with_context(
    section:           dict,
    segments:          list[dict],
    agent1a_result:    Optional[dict] = None,
    library_root=None,
) -> tuple[list[dict], LLMCallStats]:
    """
    Run Agent 1b on one section, enriched with Agent 1a's boundary handoff.

    Returns (coded_segments, stats).
    """
    from agent1b_coder import code_section_with_context

    boundary_handoff = (
        build_agent1a_boundary_handoff(section, agent1a_result)
        if agent1a_result
        else None
    )
    return code_section_with_context(
        section=section,
        segments=segments,
        boundary_handoff=boundary_handoff,
        library_root=library_root,
    )


# ---------------------------------------------------------------------------
# Stats rendering (for UI transparency panel)
# ---------------------------------------------------------------------------

def render_pipeline_stats_html(stats: PipelineStats) -> str:
    """Render PipelineStats as an HTML block for the UI agent log."""
    rows = ""
    for r in stats.results:
        tok_str  = f"~{r.stats.estimated_total_tok:,}" if r.stats else "β€”"
        time_str = f"{r.wall_time_s:.1f}s"
        icon     = r.status_icon
        icon_col = "#065f46" if r.success else "#be123c"
        rows += (
            f'<tr>'
            f'<td style="padding:4px 8px;font-weight:600">{r.section_id}</td>'
            f'<td style="padding:4px 8px;color:#475569">{r.section_label[:22]}</td>'
            f'<td style="padding:4px 8px;font-family:monospace">{time_str}</td>'
            f'<td style="padding:4px 8px;font-family:monospace;color:#64748b">{tok_str}</td>'
            f'<td style="padding:4px 8px;font-weight:700;color:{icon_col}">{icon}</td>'
            f'</tr>'
        )

    if not rows:
        return ""

    speedup_line = ""
    if stats.speedup > 1.1:
        speedup_line = (
            f'<div style="background:#ecfdf5;border:1px solid #86efac;border-radius:6px;'
            f'padding:8px 12px;margin-bottom:8px;font-size:0.82em;color:#065f46">'
            f'<strong>⚑ {stats.speedup:.1f}Γ— faster</strong> than sequential processing β€” '
            f'{stats.parallel_wall_s:.0f}s wall vs ~{stats.sequential_est_s:.0f}s serial Β· '
            f'~{stats.total_estimated_tokens:,} tokens total'
            f'</div>'
        )

    cb_state = circuit_state()
    cb_line  = ""
    if cb_state != "CLOSED":
        cb_line = (
            f'<div style="background:#fef2f2;border:1px solid #fca5a5;border-radius:6px;'
            f'padding:6px 12px;margin-bottom:6px;font-size:0.8em;color:#991b1b">'
            f'⚠ Circuit breaker: <strong>{cb_state}</strong>'
            f'</div>'
        )

    return (
        f'{cb_line}{speedup_line}'
        f'<div style="font-size:0.75em;font-weight:700;text-transform:uppercase;'
        f'letter-spacing:0.08em;color:#94a3b8;margin-bottom:6px">'
        f'{stats.agent_name}</div>'
        f'<table style="border-collapse:collapse;width:100%;font-size:0.8em">'
        f'<tr style="background:#f1f5f9;font-size:0.75em;font-weight:600;color:#64748b">'
        f'<th style="padding:4px 8px;text-align:left">Section</th>'
        f'<th style="padding:4px 8px;text-align:left">Label</th>'
        f'<th style="padding:4px 8px;text-align:left">Time</th>'
        f'<th style="padding:4px 8px;text-align:left">~Tokens</th>'
        f'<th style="padding:4px 8px;text-align:left">OK</th>'
        f'</tr>'
        f'{rows}</table>'
    )