comitia 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. comitia/__init__.py +3 -0
  2. comitia/__main__.py +3 -0
  3. comitia/api.py +68 -0
  4. comitia/catalog.py +82 -0
  5. comitia/cli.py +950 -0
  6. comitia/control.py +156 -0
  7. comitia/diffs.py +120 -0
  8. comitia/discussion/__init__.py +0 -0
  9. comitia/discussion/api.py +152 -0
  10. comitia/discussion/cli.py +1254 -0
  11. comitia/discussion/config.py +167 -0
  12. comitia/discussion/console.py +366 -0
  13. comitia/discussion/converse.py +1221 -0
  14. comitia/discussion/journal.py +382 -0
  15. comitia/discussion/panel.py +1647 -0
  16. comitia/discussion/panel_view.py +445 -0
  17. comitia/discussion/prompts/converse_asker.md +3 -0
  18. comitia/discussion/prompts/converse_summary.md +27 -0
  19. comitia/discussion/transcript.py +88 -0
  20. comitia/engine.py +1223 -0
  21. comitia/findings.py +270 -0
  22. comitia/host.py +2067 -0
  23. comitia/plan.py +957 -0
  24. comitia/posting.py +328 -0
  25. comitia/prompts.py +750 -0
  26. comitia/recipe.py +430 -0
  27. comitia/report.py +581 -0
  28. comitia/settings.py +66 -0
  29. comitia/skill/SKILL.md +75 -0
  30. comitia/starters/decision-debate.yml +27 -0
  31. comitia/starters/deep-review.yml +12 -0
  32. comitia/starters/message-test.yml +15 -0
  33. comitia/starters/pr-review-light.yml +78 -0
  34. comitia/starters/pr-review.yml +100 -0
  35. comitia/starters/prd-review.yml +10 -0
  36. comitia/store.py +212 -0
  37. comitia/web/__init__.py +13 -0
  38. comitia/web/server.py +244 -0
  39. comitia/web/service.py +679 -0
  40. comitia/web/static/app.js +1521 -0
  41. comitia/web/static/index.html +38 -0
  42. comitia/web/static/styles.css +262 -0
  43. comitia-0.1.0.dist-info/METADATA +589 -0
  44. comitia-0.1.0.dist-info/RECORD +48 -0
  45. comitia-0.1.0.dist-info/WHEEL +4 -0
  46. comitia-0.1.0.dist-info/entry_points.txt +2 -0
  47. comitia-0.1.0.dist-info/licenses/LICENSE +21 -0
  48. comitia-0.1.0.dist-info/licenses/LICENSES/crossby-MIT.txt +21 -0
@@ -0,0 +1,1254 @@
1
+ """comitia converse / comitia panel: quick consultations from the terminal.
2
+
3
+ Copied from crossby v0.71.0 (``crossby/cli/converse.py`` without ``ask``, and
4
+ ``crossby/cli/panel.py``), imports aside. Like crossby's, both commands never
5
+ prompt (unless the project's approval preset is ``strict``), write progress to
6
+ stderr, and keep stdout for the result so they can be piped or scripted.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import contextlib
12
+ import dataclasses
13
+ import json
14
+ import os
15
+ import queue
16
+ import sys
17
+ import tempfile
18
+ import threading
19
+ import time
20
+ import uuid
21
+ from collections.abc import Iterator, Sequence
22
+ from contextlib import contextmanager
23
+ from datetime import UTC, datetime
24
+ from pathlib import Path
25
+ from typing import IO, TYPE_CHECKING, Any
26
+
27
+ import typer
28
+
29
+ from comitia.discussion.console import console
30
+
31
+ if TYPE_CHECKING:
32
+ from crossby.api import AIToolID, EffortLevel
33
+ from rich.console import RenderableType
34
+ from rich.live import Live
35
+
36
+ from comitia.discussion.config import PanelConfig
37
+ from comitia.discussion.converse import ConversationResult, ConverseTurn, Participant
38
+ from comitia.discussion.journal import ConversationEvent, Journal
39
+ from comitia.discussion.panel import PanelResult, PanelSpec
40
+ from comitia.discussion.panel_view import PanelView
41
+
42
+
43
+ def converse(
44
+ asker_tool: str | None = typer.Argument(
45
+ None, metavar="ASKER", help="Agent that holds the goal and asks (e.g. claude)."
46
+ ),
47
+ responder_tool: str | None = typer.Argument(
48
+ None, metavar="RESPONDER", help="Agent that answers (e.g. codex)."
49
+ ),
50
+ continue_dir: Path | None = typer.Option(
51
+ None,
52
+ "--continue",
53
+ help=(
54
+ "Continue the consultation saved in this directory (its events.jsonl): both "
55
+ "sides resume their sessions and --max-rounds more answers are allowed."
56
+ ),
57
+ ),
58
+ goal: str | None = typer.Option(
59
+ None, "--goal", "-g", help="What the asker should find out. Only the asker sees it."
60
+ ),
61
+ goal_file: Path | None = typer.Option(
62
+ None, "--goal-file", help="Read the goal from this file instead."
63
+ ),
64
+ max_rounds: int = typer.Option(
65
+ 5,
66
+ "--max-rounds",
67
+ help="Most questions the asker may send before it must answer (with --continue: more).",
68
+ ),
69
+ timeout: float = typer.Option(
70
+ 1800.0, "--timeout", help="Seconds for the whole consultation (summary excluded)."
71
+ ),
72
+ turn_timeout: float = typer.Option(600.0, "--turn-timeout", help="Seconds per message."),
73
+ asker_model: str | None = typer.Option(None, "--asker-model", help="Model for the asker."),
74
+ responder_model: str | None = typer.Option(
75
+ None, "--responder-model", help="Model for the responder."
76
+ ),
77
+ asker_effort: str | None = typer.Option(
78
+ None, "--asker-effort", help="Reasoning effort for the asker, where its tool supports it."
79
+ ),
80
+ responder_effort: str | None = typer.Option(
81
+ None,
82
+ "--responder-effort",
83
+ help="Reasoning effort for the responder, where its tool supports it.",
84
+ ),
85
+ summary: bool = typer.Option(
86
+ False, "--summary", help="Also write a neutral summary.md of the whole consultation."
87
+ ),
88
+ summarizer_tool: str | None = typer.Option(
89
+ None,
90
+ "--summarizer-tool",
91
+ help="Tool that writes the --summary (defaults to the asker's tool).",
92
+ ),
93
+ summarizer_model: str | None = typer.Option(
94
+ None,
95
+ "--summarizer-model",
96
+ help="Model for the --summary (defaults to the asker's, when on the asker's tool).",
97
+ ),
98
+ summarizer_effort: str | None = typer.Option(
99
+ None,
100
+ "--summarizer-effort",
101
+ help="Reasoning effort for the --summary (defaults to the asker's, on the asker's tool).",
102
+ ),
103
+ output_dir: Path | None = typer.Option(
104
+ None,
105
+ "--output-dir",
106
+ help="Directory for transcript.md (default: .crossby/conversations/<timestamp>/).",
107
+ ),
108
+ as_json: bool = typer.Option(False, "--json", help="Print a JSON result object."),
109
+ quiet: bool = typer.Option(
110
+ False, "--quiet", "-q", help="Do not print messages as they arrive."
111
+ ),
112
+ responder_path: Path | None = typer.Option(
113
+ None,
114
+ "--responder-path",
115
+ help="Folder the responder runs in, with its own files and setup (default: --path).",
116
+ ),
117
+ allow_project_hooks: bool = typer.Option(
118
+ False,
119
+ "--allow-project-hooks",
120
+ help=(
121
+ "Do not warn when a read-only responder or summarizer's folder has hooks the tool "
122
+ "would run, which can change files (it runs and warns by default)."
123
+ ),
124
+ ),
125
+ path: Path = typer.Option(Path("."), "--path", help="Project root directory (the asker's)."),
126
+ ) -> None:
127
+ """Let one AI coding agent consult another, headless, until it has its answer.
128
+
129
+ The ASKER holds the goal. It decides what to ask, judges each answer,
130
+ asks follow-up questions, and ends with its final answer. The RESPONDER
131
+ is never sent the goal; it gets the asker's messages as written and only
132
+ answers, from its own folder (--responder-path), read-only: it can read and
133
+ search but not change files. Each side keeps its own session, resumed every
134
+ turn and sent only the newest message, whole; a CLI build whose resume was
135
+ not verified is refused before anything starts. Messages and progress go to
136
+ stderr and the asker's final answer to stdout (in a terminal, where both
137
+ show, it appears once); transcript.md is saved after every message.
138
+
139
+ Exit codes: 0 answered, 2 stopped by the round or time limit, 1 failed,
140
+ 130 interrupted.
141
+
142
+ Examples::
143
+
144
+ comitia converse claude codex --goal "Check whether this diagnosis is sound: ..."
145
+ comitia converse claude cursor --goal-file goal.md --max-rounds 3 --json
146
+ """
147
+ from comitia.discussion import converse as engine
148
+ from comitia.discussion.journal import (
149
+ JOURNAL_FILE,
150
+ Journal,
151
+ JournalError,
152
+ JournalExistsError,
153
+ )
154
+
155
+ # Everything that can refuse the call is checked before a journal exists,
156
+ # so a refused fresh run leaves no journal behind to block a retry.
157
+ chosen_summarizer = (
158
+ _headless_tool(summarizer_tool, "--summarizer-tool")
159
+ if summary and summarizer_tool is not None
160
+ else None
161
+ )
162
+ efforts = {
163
+ "asker": _effort(asker_effort, "--asker-effort"),
164
+ "responder": _effort(responder_effort, "--responder-effort"),
165
+ "summarizer": _effort(summarizer_effort, "--summarizer-effort"),
166
+ }
167
+ prior: ConversationResult | None = None
168
+ responder_root: Path | None
169
+ journal: Journal | None = None
170
+ if continue_dir is not None:
171
+ prior, out_dir, journal = _load_continuation(
172
+ continue_dir,
173
+ conflicting={
174
+ "ASKER": asker_tool,
175
+ "RESPONDER": responder_tool,
176
+ "--goal": goal,
177
+ "--goal-file": goal_file,
178
+ "--asker-model": asker_model,
179
+ "--responder-model": responder_model,
180
+ "--asker-effort": asker_effort,
181
+ "--responder-effort": responder_effort,
182
+ "--responder-path": responder_path,
183
+ "--output-dir": output_dir,
184
+ },
185
+ )
186
+ asker, responder = prior.asker, prior.responder
187
+ asker_id = asker.tool
188
+ goal_text = prior.goal
189
+ try:
190
+ project_root = _project_root(prior.folders[engine.Role.ASKER], "the asker's folder")
191
+ responder_root = _project_root(
192
+ prior.folders[engine.Role.RESPONDER], "the responder's folder"
193
+ )
194
+ except BaseException:
195
+ journal.close()
196
+ raise
197
+ started_at = prior.started_at
198
+ else:
199
+ if asker_tool is None or responder_tool is None:
200
+ console.error("Name the ASKER and RESPONDER tools, or --continue a consultation.")
201
+ raise typer.Exit(1)
202
+ project_root = _project_root(path)
203
+ responder_root = (
204
+ _project_root(responder_path, "--responder-path")
205
+ if responder_path is not None
206
+ else None
207
+ )
208
+ asker_id = _headless_tool(asker_tool, "ASKER")
209
+ responder_id = _headless_tool(responder_tool, "RESPONDER")
210
+ goal_text = _read_text_input(goal, goal_file, what="goal", hint="--goal or --goal-file")
211
+ asker, responder = engine.make_participants(
212
+ asker_id,
213
+ responder_id,
214
+ asker_model=asker_model,
215
+ responder_model=responder_model,
216
+ asker_effort=efforts["asker"],
217
+ responder_effort=efforts["responder"],
218
+ )
219
+ started_at = datetime.now(tz=UTC)
220
+ out_dir = (
221
+ output_dir.resolve()
222
+ if output_dir is not None
223
+ else engine.conversation_dir(project_root, started_at)
224
+ )
225
+ summarizer_id = (chosen_summarizer or asker_id) if summary else None
226
+ # On the asker's own tool the summary keeps the asker's model and effort.
227
+ same_tool = summarizer_id == asker.tool
228
+ summary_model = summarizer_model or (asker.model if same_tool else None)
229
+ summary_effort = efforts["summarizer"] or (asker.effort if same_tool else None)
230
+ try:
231
+ _approve_if_strict(project_root, "converse", "Start this consultation?", as_json=as_json)
232
+ except BaseException:
233
+ if journal is not None:
234
+ journal.close()
235
+ raise
236
+ if journal is None:
237
+ try:
238
+ # Created exclusively: a fresh run never appends to another journal.
239
+ journal = Journal(uuid.uuid4().hex, path=out_dir / JOURNAL_FILE)
240
+ except JournalExistsError:
241
+ console.error(
242
+ f"{out_dir} already holds a consultation; --continue it or choose another "
243
+ "--output-dir."
244
+ )
245
+ raise typer.Exit(1) from None
246
+ except JournalError as exc:
247
+ console.error(str(exc))
248
+ raise typer.Exit(1) from None
249
+
250
+ transcript_path = out_dir / "transcript.md"
251
+ folders = {
252
+ engine.Role.ASKER: project_root,
253
+ engine.Role.RESPONDER: responder_root or project_root,
254
+ }
255
+ completed: list[ConverseTurn] = list(prior.turns) if prior is not None else []
256
+ allowed = (prior.rounds if prior is not None else 0) + max_rounds
257
+ waiting = _TurnWait()
258
+
259
+ tools_shown = False
260
+
261
+ def on_turn_start(number: int, speaker: Participant) -> None:
262
+ nonlocal tools_shown
263
+ if quiet:
264
+ return
265
+ if not tools_shown:
266
+ # Both sides were checked before the first turn of this run.
267
+ tools_shown = True
268
+ _show_tools(journal.events)
269
+ if console.err.is_terminal:
270
+ # The line updates with the elapsed time and is replaced by the turn.
271
+ waiting.start(f"[{number}] {speaker.label} is writing…")
272
+ else:
273
+ _stderr(f"[step.count]\\[{number}][/] {speaker.label} is writing…")
274
+
275
+ def on_turn(turn: ConverseTurn) -> None:
276
+ waiting.stop()
277
+ # Persist before printing, so a crash or Ctrl-C keeps every completed turn.
278
+ completed.append(turn)
279
+ partial = engine.render_partial_transcript(
280
+ goal=goal_text,
281
+ asker=asker,
282
+ responder=responder,
283
+ max_rounds=allowed,
284
+ started_at=started_at,
285
+ turns=completed,
286
+ folders=folders,
287
+ )
288
+ try:
289
+ _write(transcript_path, partial)
290
+ except OSError as exc:
291
+ # The previous transcript is intact (the write is atomic), and the
292
+ # next turn or the final write tries again; don't end the consultation.
293
+ console.warn(f"Could not save the transcript after turn {turn.number}: {exc}")
294
+ if not quiet:
295
+ _show_turn(turn, heading=console.err.is_terminal)
296
+
297
+ try:
298
+ if not quiet:
299
+ _show_start(asker, responder, folders[engine.Role.RESPONDER], project_root)
300
+ if prior is not None:
301
+ _stderr(f"[dim] {_escape(_continuing(prior))}[/]")
302
+ more = " more" if prior is not None else ""
303
+ questions = "question" if max_rounds == 1 else "questions"
304
+ _stderr(
305
+ f"[dim] limits: up to {max_rounds}{more} {questions}, "
306
+ f"{_duration(timeout)} in all, {_duration(turn_timeout)} per turn[/]"
307
+ )
308
+ _stderr(f"[dim] transcript: {_escape(str(transcript_path))}[/]")
309
+ if journal.path is not None:
310
+ _stderr(f"[dim] events: {_escape(str(journal.path))}[/]")
311
+ result = engine.run_conversation(
312
+ goal_text,
313
+ (asker, responder),
314
+ working_dir=project_root,
315
+ responder_dir=responder_root,
316
+ max_rounds=max_rounds,
317
+ timeout_seconds=timeout,
318
+ turn_timeout_seconds=turn_timeout,
319
+ on_turn_start=on_turn_start,
320
+ on_turn=on_turn,
321
+ allow_project_hooks=allow_project_hooks,
322
+ journal=journal,
323
+ resume=prior,
324
+ )
325
+ except engine.ConverseError as exc:
326
+ console.error(str(exc))
327
+ raise typer.Exit(1) from None
328
+ finally:
329
+ waiting.stop() # a failed or interrupted turn never reaches on_turn
330
+ journal.close()
331
+ if journal.store_error is not None:
332
+ console.warn(f"The event journal is incomplete: {journal.store_error}")
333
+
334
+ _write(transcript_path, engine.render_transcript(result))
335
+
336
+ summary_path: Path | None = None
337
+ summary_body: str | None = None
338
+ summary_error: str | None = None
339
+ exit_code = result.exit_code
340
+ if summarizer_id is not None and result.turns and not _interrupted(result):
341
+ summary_body, summary_error, interrupted = _summarize(
342
+ result,
343
+ transcript_path,
344
+ summarizer_id,
345
+ project_root,
346
+ model=summary_model,
347
+ effort=summary_effort,
348
+ quiet=quiet,
349
+ allow_project_hooks=allow_project_hooks,
350
+ )
351
+ if interrupted:
352
+ exit_code = engine.EXIT_CODES[engine.StopReason.INTERRUPTED]
353
+ if summary_body is not None:
354
+ summary_path = out_dir / "summary.md"
355
+ _write(summary_path, engine.render_summary(result, summary_body))
356
+
357
+ _report(
358
+ result,
359
+ transcript_path=transcript_path,
360
+ events_path=journal.path,
361
+ run_id=journal.run_id,
362
+ summary_path=summary_path,
363
+ summary_body=summary_body,
364
+ summary_error=summary_error,
365
+ as_json=as_json,
366
+ # In a terminal stdout and stderr share the screen, where the final
367
+ # answer was just shown as the last message: print it only once.
368
+ answer_shown=not quiet and sys.stdout.isatty() and console.err.is_terminal,
369
+ # A saved journal of a consultation without its answer can go on. A
370
+ # final answer committed before Ctrl-C reads as answered to --continue.
371
+ continue_dir=(
372
+ out_dir
373
+ if not result.answered
374
+ and not any(turn.is_final_answer for turn in result.turns)
375
+ and journal.store_error is None
376
+ and journal.path is not None
377
+ else None
378
+ ),
379
+ )
380
+ if exit_code:
381
+ raise typer.Exit(exit_code)
382
+
383
+
384
+ # ---------------------------------------------------------------------------
385
+ # Helpers
386
+ # ---------------------------------------------------------------------------
387
+
388
+
389
+ def _approve_if_strict(path: Path, command: str, question: str, *, as_json: bool) -> None:
390
+ """Under ``approval: strict``, the user's own approval before anything starts.
391
+
392
+ Under ``host`` and ``none`` these commands never ask: a person who types one ran it,
393
+ and an agent's host has already applied its own permission flow to it.
394
+ """
395
+ from comitia import cli as commands
396
+ from comitia import store
397
+ from comitia.settings import SettingsError, load_settings
398
+
399
+ root = store.project_root(path)
400
+ try:
401
+ approval = load_settings(root).approval
402
+ except SettingsError as exc:
403
+ console.error(str(exc))
404
+ raise typer.Exit(1) from None
405
+ if approval == "strict":
406
+ commands._approve(root, command, question, as_json=as_json, approval="strict")
407
+
408
+
409
+ def _project_root(path: Path, flag: str = "--path") -> Path:
410
+ root = path.resolve()
411
+ if not root.is_dir():
412
+ console.error(f"{flag} is not a directory: {root}")
413
+ raise typer.Exit(1)
414
+ return root
415
+
416
+
417
+ def _headless_tool(value: str, name: str) -> AIToolID:
418
+ from crossby.ai_tools import AbstractAITool
419
+ from crossby.api import AIToolID
420
+
421
+ usable = sorted(
422
+ tid.value
423
+ for tid in AbstractAITool.available_tools()
424
+ if AbstractAITool.get(tid).capabilities().headless.managed_supported
425
+ )
426
+ choices = f"Choose one of: {', '.join(usable)}."
427
+ try:
428
+ tool_id = AIToolID(value)
429
+ except ValueError:
430
+ where = "" if name == "TOOL" else f" for {name}"
431
+ console.error(f"Unknown tool {value!r}{where}. {choices}")
432
+ raise typer.Exit(1) from None
433
+ if tool_id.value not in usable:
434
+ role = "" if name == "TOOL" else f", so it can't be the {name}"
435
+ console.error(f"{tool_id.value} can't run headless sessions{role}. {choices}")
436
+ raise typer.Exit(1)
437
+ return tool_id
438
+
439
+
440
+ def _read_text_input(
441
+ value: str | None,
442
+ file: Path | None,
443
+ *,
444
+ what: str,
445
+ hint: str,
446
+ ) -> str:
447
+ if value is not None and file is not None:
448
+ console.error(f"Pass the {what} once, as {hint}; not both.")
449
+ raise typer.Exit(1)
450
+ if file is not None:
451
+ try:
452
+ text = file.read_text(encoding="utf-8")
453
+ except OSError as exc:
454
+ console.error(f"Cannot read {what} file {file}: {exc}")
455
+ raise typer.Exit(1) from None
456
+ elif value == "-":
457
+ text = sys.stdin.read()
458
+ elif value is not None:
459
+ text = value
460
+ else:
461
+ console.error(f"A {what} is required: pass it as {hint}.")
462
+ raise typer.Exit(1)
463
+ if not text.strip():
464
+ console.error(f"The {what} is empty.")
465
+ raise typer.Exit(1)
466
+ return text.strip()
467
+
468
+
469
+ def _effort(value: str | None, flag: str = "--effort") -> EffortLevel | None:
470
+ from crossby.api import EffortLevel
471
+
472
+ if value is None:
473
+ return None
474
+ try:
475
+ return EffortLevel(value)
476
+ except ValueError:
477
+ choices = ", ".join(level.value for level in EffortLevel)
478
+ console.error(f"Unknown {flag} {value!r}. Choose one of: {choices}.")
479
+ raise typer.Exit(1) from None
480
+
481
+
482
+ def _write(path: Path, text: str) -> None:
483
+ """Replace ``path`` atomically, so a failed write keeps the previous content.
484
+
485
+ The transcript is rewritten after every turn; a truncating write that
486
+ failed part-way would erase every turn saved so far.
487
+ """
488
+ # On POSIX, invalid bytes in argv (e.g. --goal) arrive as lone surrogates,
489
+ # which strict UTF-8 cannot encode; replace them rather than fail.
490
+ _atomic_write_text(path, text.encode("utf-8", "replace").decode("utf-8"))
491
+
492
+
493
+ def _atomic_write_text(path: Path, text: str) -> None:
494
+ """Write ``text`` through a unique temporary file in ``path``'s folder, then rename it.
495
+
496
+ The rename is atomic, so a write that fails part-way leaves the old file whole.
497
+ """
498
+ path.parent.mkdir(parents=True, exist_ok=True)
499
+ handle, name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
500
+ temporary = Path(name)
501
+ try:
502
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
503
+ stream.write(text)
504
+ os.replace(temporary, path)
505
+ except BaseException:
506
+ temporary.unlink(missing_ok=True)
507
+ raise
508
+
509
+
510
+ def _show_start(asker: Participant, responder: Participant, folder: Path, root: Path) -> None:
511
+ """One line on who consults whom, and where the read-only responder runs."""
512
+
513
+ def name(participant: Participant) -> str:
514
+ settings = participant.settings
515
+ return participant.tool.value + (f" ({settings})" if settings else "")
516
+
517
+ where = "the asker's folder" if folder == root else str(folder)
518
+ _stderr(
519
+ f" [step]▸[/] {_escape(name(asker))} asks {_escape(name(responder))}"
520
+ f" [dim](read-only, in {_escape(where)})[/]"
521
+ )
522
+
523
+
524
+ def _show_turn(turn: ConverseTurn, *, heading: bool = False) -> None:
525
+ """Print a finished turn; ``heading`` replaces the live "is writing" line."""
526
+ from comitia.discussion.converse import turn_footer
527
+
528
+ who = "final answer" if turn.is_final_answer else turn.role.value
529
+ title = f"{who} ({turn.tool.value})"
530
+ if heading:
531
+ _stderr(f"[step.count]\\[{turn.number}][/] {_escape(title)}")
532
+ sys.stderr.write(f"\n{turn.text or '(empty message)'}\n\n")
533
+ footer = turn_footer(turn) if heading else f"{title} · {turn_footer(turn)}"
534
+ _stderr(f"[dim] {_escape(footer)}[/]")
535
+ sys.stderr.flush()
536
+
537
+
538
+ def _continuing(prior: ConversationResult) -> str:
539
+ """``continuing after 3 messages; it had stopped on the time limit``."""
540
+ from comitia.discussion.converse import StopReason
541
+
542
+ count = len(prior.turns)
543
+ why = {
544
+ StopReason.ROUND_LIMIT: "it had reached its question limit",
545
+ StopReason.TIMEOUT: "it had stopped on the time limit",
546
+ StopReason.INTERRUPTED: "it had been interrupted",
547
+ StopReason.FAILED: "a session had failed",
548
+ }.get(prior.stop_reason, f"it had stopped ({prior.stop_reason.value})")
549
+ return f"continuing after {count} message{'' if count == 1 else 's'}; {why}"
550
+
551
+
552
+ def _show_tools(events: Sequence[ConversationEvent]) -> None:
553
+ """``tools: claude 2.1.317 · codex 0.166.0``, from this run's checks."""
554
+ from comitia.discussion.journal import EventType
555
+ from comitia.discussion.panel_view import version_number
556
+
557
+ versions: dict[str, str | None] = {}
558
+ warnings: dict[str, None] = {}
559
+ for event in events:
560
+ if event.type is EventType.PARTICIPANT_READY:
561
+ tool = str(event.data.get("tool"))
562
+ versions.setdefault(tool, version_number(event.data.get("version")))
563
+ warnings.update(dict.fromkeys(event.data.get("warnings") or ()))
564
+ if versions:
565
+ tools = " · ".join(name + (f" {v}" if v else "") for name, v in versions.items())
566
+ _stderr(f"[dim] tools: {_escape(tools)}[/]")
567
+ for warning in warnings:
568
+ console.warn(_escape(str(warning)))
569
+
570
+
571
+ def _duration(seconds: float) -> str:
572
+ """``42s``, ``3m 05s``, ``30m``, ``1h 02m``."""
573
+ whole = int(seconds)
574
+ hours, rest = divmod(whole, 3600)
575
+ minutes, secs = divmod(rest, 60)
576
+ if hours:
577
+ return f"{hours}h {minutes:02d}m"
578
+ if minutes:
579
+ return f"{minutes}m" if not secs else f"{minutes}m {secs:02d}s"
580
+ return f"{secs}s"
581
+
582
+
583
+ class _Elapsed:
584
+ """A spinner with a label and the time since it started."""
585
+
586
+ def __init__(self, label: str) -> None:
587
+ from rich.spinner import Spinner
588
+
589
+ self._label = label
590
+ self._started = time.monotonic()
591
+ self._spinner = Spinner("dots", style="step")
592
+
593
+ def __rich__(self) -> RenderableType:
594
+ from rich.text import Text
595
+
596
+ elapsed = _duration(time.monotonic() - self._started)
597
+ self._spinner.update(text=Text(f" {self._label} {elapsed}", style="dim"))
598
+ return self._spinner
599
+
600
+
601
+ class _TurnWait:
602
+ """The live line under a running turn, on a terminal only; safe to stop twice."""
603
+
604
+ def __init__(self) -> None:
605
+ self._live: Live | None = None
606
+
607
+ def start(self, label: str) -> None:
608
+ from rich.live import Live
609
+
610
+ self.stop()
611
+ self._live = Live(
612
+ _Elapsed(label), console=console.err, transient=True, refresh_per_second=4
613
+ )
614
+ self._live.start()
615
+
616
+ def stop(self) -> None:
617
+ if self._live is not None:
618
+ self._live.stop()
619
+ self._live = None
620
+
621
+
622
+ @contextmanager
623
+ def _waiting(label: str) -> Iterator[None]:
624
+ """Show ``label`` with the elapsed time while waiting, on a terminal only."""
625
+ if not console.err.is_terminal:
626
+ yield
627
+ return
628
+ wait = _TurnWait()
629
+ wait.start(label)
630
+ try:
631
+ yield
632
+ finally:
633
+ wait.stop()
634
+
635
+
636
+ def _load_continuation(
637
+ directory: Path, *, conflicting: dict[str, object]
638
+ ) -> tuple[ConversationResult, Path, Journal]:
639
+ """The saved consultation in ``directory``, ready to continue."""
640
+ from comitia.discussion.converse import ConverseError, result_from_journal
641
+ from comitia.discussion.journal import JOURNAL_FILE, Journal, JournalError
642
+
643
+ given = [name for name, value in conflicting.items() if value is not None]
644
+ if given:
645
+ console.error(
646
+ f"--continue takes its tools, goal and folders from the journal; drop {given[0]}."
647
+ )
648
+ raise typer.Exit(1)
649
+ folder = directory.resolve()
650
+ path = folder / JOURNAL_FILE
651
+ if not path.is_file():
652
+ console.error(f"{folder} has no {JOURNAL_FILE} to continue from.")
653
+ raise typer.Exit(1)
654
+ try:
655
+ # Locked before it is read, and held until the run ends: a second
656
+ # process continuing the same consultation is refused.
657
+ journal, events = Journal.reopen(path)
658
+ except JournalError as exc:
659
+ console.error(str(exc))
660
+ raise typer.Exit(1) from None
661
+ try:
662
+ prior = result_from_journal(events)
663
+ except ConverseError as exc:
664
+ journal.close()
665
+ console.error(str(exc))
666
+ raise typer.Exit(1) from None
667
+ if prior.answered:
668
+ journal.close()
669
+ console.error("That consultation already has its final answer.")
670
+ raise typer.Exit(1)
671
+ return prior, folder, journal
672
+
673
+
674
+ def _side_json(result: ConversationResult, participant: Participant) -> dict[str, Any]:
675
+ """One side's tool, model and session facts for ``--json``."""
676
+ own = [turn for turn in result.turns if turn.role is participant.role]
677
+ return {
678
+ "tool": participant.tool.value,
679
+ "model": participant.model,
680
+ "effort": participant.effort.value if participant.effort is not None else None,
681
+ # The native session every turn after the first resumed.
682
+ "session_id": result.sessions.get(participant.role),
683
+ "denials": [denial for turn in own for denial in turn.denials],
684
+ }
685
+
686
+
687
+ def _interrupted(result: ConversationResult) -> bool:
688
+ from comitia.discussion.converse import StopReason
689
+
690
+ return result.stop_reason is StopReason.INTERRUPTED
691
+
692
+
693
+ def _summarize(
694
+ result: ConversationResult,
695
+ transcript_path: Path,
696
+ tool: AIToolID,
697
+ project_root: Path,
698
+ *,
699
+ quiet: bool,
700
+ model: str | None = None,
701
+ effort: EffortLevel | None = None,
702
+ allow_project_hooks: bool = False,
703
+ ) -> tuple[str | None, str | None, bool]:
704
+ """Return ``(summary, error, interrupted)``; the transcript is already written."""
705
+ from comitia.discussion.converse import ConverseSummaryError, summarize_conversation
706
+
707
+ label = f"Summarizing with {tool.value}…"
708
+ if not quiet and not console.err.is_terminal:
709
+ _stderr(f" [step]▸[/] {label}")
710
+ try:
711
+ with _waiting(label) if not quiet else _nothing():
712
+ body = summarize_conversation(
713
+ result,
714
+ transcript_path=transcript_path,
715
+ tool=tool,
716
+ working_dir=project_root,
717
+ model=model,
718
+ effort=effort,
719
+ allow_project_hooks=allow_project_hooks,
720
+ )
721
+ except ConverseSummaryError as exc:
722
+ console.warn(f"Summary failed: {exc}")
723
+ return None, str(exc), False
724
+ except KeyboardInterrupt:
725
+ console.warn("Summary interrupted; the transcript is saved.")
726
+ return None, "interrupted", True
727
+ return body, None, False
728
+
729
+
730
+ @contextmanager
731
+ def _nothing() -> Iterator[None]:
732
+ yield
733
+
734
+
735
+ def _report(
736
+ result: ConversationResult,
737
+ *,
738
+ transcript_path: Path,
739
+ events_path: Path | None = None,
740
+ run_id: str | None = None,
741
+ summary_path: Path | None,
742
+ summary_body: str | None,
743
+ summary_error: str | None,
744
+ as_json: bool,
745
+ answer_shown: bool = False,
746
+ continue_dir: Path | None = None,
747
+ ) -> None:
748
+ from comitia.discussion.converse import describe_stop
749
+
750
+ if as_json:
751
+ _print_json(
752
+ {
753
+ "status": result.stop_reason.value,
754
+ "answered": result.answered,
755
+ "final_answer": result.final_answer,
756
+ "outcome": describe_stop(result),
757
+ "error": result.error,
758
+ "rounds": result.rounds,
759
+ "max_rounds": result.max_rounds,
760
+ "turns": len(result.turns),
761
+ "asker": _side_json(result, result.asker),
762
+ "responder": _side_json(result, result.responder),
763
+ "transcript_path": str(transcript_path),
764
+ "events_path": str(events_path) if events_path is not None else None,
765
+ "run_id": run_id,
766
+ "summary_path": str(summary_path) if summary_path else None,
767
+ "summary": summary_body,
768
+ "summary_error": summary_error,
769
+ "continuable": continue_dir is not None,
770
+ }
771
+ )
772
+ return
773
+
774
+ # stdout carries the result: the asker's final answer, and the summary when asked.
775
+ answer = None if answer_shown else result.final_answer
776
+ if answer is not None:
777
+ print(answer)
778
+ if summary_body is not None:
779
+ if answer is not None:
780
+ print()
781
+ print(summary_body.strip())
782
+
783
+ outcome = describe_stop(result)
784
+ if result.answered:
785
+ _stderr(f" [success]✓[/] {_escape(outcome)}")
786
+ elif result.exit_code == 1:
787
+ _stderr(f" [error]✗ Error:[/] {_escape(outcome)}")
788
+ else:
789
+ _stderr(f" [warning]![/] {_escape(outcome)}")
790
+ _stderr(f"[dim] transcript: {_escape(str(transcript_path))}[/]")
791
+ if summary_path is not None:
792
+ _stderr(f"[dim] summary: {_escape(str(summary_path))}[/]")
793
+ if continue_dir is not None:
794
+ import shlex
795
+
796
+ _hint(f"continue it with: comitia converse --continue {shlex.quote(str(continue_dir))}")
797
+
798
+
799
+ def _stderr(markup: str) -> None:
800
+ # soft_wrap keeps long paths on one line so they can be copied.
801
+ console.err.print(markup, soft_wrap=True)
802
+
803
+
804
+ def _hint(message: str) -> None:
805
+ """A hint on stderr: stdout carries only the answer, so it can be piped."""
806
+ # soft_wrap keeps a command or path on one line, so it can be copied.
807
+ console.err.print(f"[hint] {console.ARROW} {_escape(message)}[/]", soft_wrap=True)
808
+
809
+
810
+ def _escape(text: str) -> str:
811
+ from rich.markup import escape
812
+
813
+ return escape(text)
814
+
815
+
816
+ def _print_json(payload: dict[str, Any]) -> None:
817
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
818
+
819
+
820
+ def panel(
821
+ name: str = typer.Argument(
822
+ ..., help="Panel recipe name under `panels:` in .comitia.yml (or .crossby.yml)."
823
+ ),
824
+ goal: str | None = typer.Option(
825
+ None, "--goal", "-g", help="What the lead should find out. Only the lead sees it."
826
+ ),
827
+ goal_file: Path | None = typer.Option(
828
+ None, "--goal-file", help="Read the goal from this file instead."
829
+ ),
830
+ max_rounds: int | None = typer.Option(
831
+ None, "--max-rounds", help="Most messages the lead may send (default: the recipe's)."
832
+ ),
833
+ output_dir: Path | None = typer.Option(
834
+ None,
835
+ "--output-dir",
836
+ help="Directory for transcript.md and events.jsonl (default: .crossby/panels/<time>/).",
837
+ ),
838
+ as_json: bool = typer.Option(False, "--json", help="Print a JSON result object."),
839
+ quiet: bool = typer.Option(False, "--quiet", "-q", help="Do not print messages."),
840
+ allow_project_hooks: bool = typer.Option(
841
+ False,
842
+ "--allow-project-hooks",
843
+ help="Do not warn when a read-only member's folder has hooks, which can change files.",
844
+ ),
845
+ path: Path = typer.Option(Path("."), "--path", help="Project root (where .comitia.yml is)."),
846
+ ) -> None:
847
+ """Let a lead agent consult a panel of read-only agents, by id, until it answers.
848
+
849
+ The recipe in .comitia.yml (or .crossby.yml) names the lead and the members, each with its
850
+ tool and folder. The lead ends each message with `NEXT: ASK @id …` (or
851
+ `@all`), or `NEXT: DONE` for its final answer; addressed members answer
852
+ in parallel, read-only, each resuming its own session, and their replies
853
+ reach the lead together under their @ids. A member with a persona_folder
854
+ gets it provisioned with its instructions and skills in its tool's own
855
+ layout. Exit codes are those of `converse`.
856
+ """
857
+ from comitia.discussion.config import PanelsError, load_panels
858
+ from comitia.discussion.journal import (
859
+ JOURNAL_FILE,
860
+ Journal,
861
+ JournalError,
862
+ JournalExistsError,
863
+ )
864
+ from comitia.discussion.panel import HumanInput, render_panel_transcript, run_panel
865
+
866
+ root = _project_root(path)
867
+ try:
868
+ panels = load_panels(root)
869
+ except PanelsError as exc:
870
+ console.error(str(exc))
871
+ raise typer.Exit(1) from None
872
+ recipe = panels.recipes.get(name)
873
+ if recipe is None:
874
+ known = ", ".join(sorted(panels.recipes)) or "none defined"
875
+ where = panels.source or ".comitia.yml (or .crossby.yml)"
876
+ console.error(f"No panel named {name!r} in {where} ({known}).")
877
+ raise typer.Exit(1)
878
+ goal_text = _read_text_input(goal, goal_file, what="goal", hint="--goal or --goal-file")
879
+ # Before a persona folder is provisioned: nothing happens unless it is approved.
880
+ _approve_if_strict(root, "panel", f"Run the panel `{name}`?", as_json=as_json)
881
+ spec = _spec(
882
+ recipe,
883
+ panels.root,
884
+ goal_text,
885
+ max_rounds=max_rounds,
886
+ allow_project_hooks=allow_project_hooks,
887
+ )
888
+
889
+ started = datetime.now(tz=UTC)
890
+ out_dir = (
891
+ output_dir.resolve()
892
+ if output_dir is not None
893
+ else root / ".crossby" / "panels" / started.strftime("%Y%m%dT%H%M%S%f")
894
+ )
895
+ from comitia.discussion.panel_view import PanelView, show_opening
896
+
897
+ view = (
898
+ None
899
+ if quiet
900
+ else PanelView(spec, live=console.err.is_terminal, typed_here=_isatty(sys.stdin))
901
+ )
902
+ try:
903
+ # Created exclusively: a second run never mixes into this journal.
904
+ journal = Journal(
905
+ uuid.uuid4().hex, path=out_dir / JOURNAL_FILE, sinks=[] if view is None else [view]
906
+ )
907
+ except JournalExistsError:
908
+ console.error(f"{out_dir} already holds a panel; choose another --output-dir.")
909
+ raise typer.Exit(1) from None
910
+ except JournalError as exc:
911
+ console.error(str(exc))
912
+ raise typer.Exit(1) from None
913
+ human = spec.lead.human or any(member.human for member in spec.members)
914
+ member_ids = tuple(member.id for member in spec.members)
915
+ transcript = out_dir / "transcript.md"
916
+
917
+ def reply(request: Any) -> Any:
918
+ return _terminal_reply(request, view, member_ids)
919
+
920
+ try:
921
+ if view is not None:
922
+ events = str(journal.path) if journal.path is not None else None
923
+ source = str(panels.source) if panels.source is not None else None
924
+ show_opening(spec, transcript=str(transcript), events=events, recipe=source)
925
+ view.start()
926
+ result = run_panel(spec, journal=journal, inputs=HumanInput(reply) if human else None)
927
+ finally:
928
+ journal.close() # delivers every queued event to the view first
929
+ if view is not None:
930
+ view.close()
931
+ if journal.store_error is not None:
932
+ console.warn(f"The event journal is incomplete: {journal.store_error}")
933
+ result = dataclasses.replace(result, journal_error=journal.store_error)
934
+ _write(transcript, render_panel_transcript(result))
935
+ _report_panel(
936
+ result,
937
+ transcript,
938
+ journal.path,
939
+ journal.run_id,
940
+ as_json=as_json,
941
+ # In a terminal stdout and stderr share the screen, where the final
942
+ # answer was just shown as the last message: print it only once.
943
+ answer_shown=not quiet and sys.stdout.isatty() and console.err.is_terminal,
944
+ )
945
+ if result.exit_code:
946
+ raise typer.Exit(result.exit_code)
947
+
948
+
949
+ def _spec(
950
+ recipe: PanelConfig,
951
+ root: Path,
952
+ goal: str,
953
+ *,
954
+ max_rounds: int | None,
955
+ allow_project_hooks: bool,
956
+ ) -> PanelSpec:
957
+ """Turn a recipe into a panel, provisioning persona folders it names."""
958
+ from crossby.api import (
959
+ CliBackend,
960
+ EffortLevel,
961
+ OwnedWorkspaceSpec,
962
+ ProjectWorkspace,
963
+ RestrictionChannel,
964
+ WorkspaceError,
965
+ provision,
966
+ )
967
+ from pydantic import ValidationError
968
+
969
+ from comitia.discussion.panel import HumanBackend, Lead, Member, PanelSpec
970
+
971
+ def backend(tool: str, model: str | None, effort: str | None, role: str) -> CliBackend:
972
+ return CliBackend(
973
+ tool=_headless_tool(tool, role),
974
+ model=model,
975
+ effort=EffortLevel(effort) if effort else None,
976
+ )
977
+
978
+ def text(relative: str, what: str) -> str:
979
+ source = root / relative
980
+ try:
981
+ return source.read_text(encoding="utf-8")
982
+ except OSError as exc:
983
+ console.error(f"Cannot read {what} {source}: {exc}")
984
+ raise typer.Exit(1) from None
985
+
986
+ try:
987
+ members = []
988
+ for item in recipe.members:
989
+ if item.human:
990
+ members.append(Member(id=item.id, name=item.name, backend=HumanBackend()))
991
+ continue
992
+ assert item.tool is not None
993
+ instructions = text(item.instructions, "instructions") if item.instructions else None
994
+ member_backend = backend(item.tool, item.model, item.effort, f"member {item.id}")
995
+ if item.persona_folder is not None:
996
+ workspace: Any = provision(
997
+ OwnedWorkspaceSpec(
998
+ path=root / item.persona_folder,
999
+ tool=member_backend.tool,
1000
+ instructions=instructions,
1001
+ skills=tuple(root / skill for skill in item.skills),
1002
+ files={key: text(value, "file") for key, value in item.files.items()},
1003
+ )
1004
+ )
1005
+ else:
1006
+ if item.skills or item.files:
1007
+ console.error(f"Member {item.id}: skills and files need a persona_folder.")
1008
+ raise typer.Exit(1)
1009
+ workspace = ProjectWorkspace(
1010
+ path=_project_root(root / item.folder, f"member {item.id}'s folder"),
1011
+ instructions=instructions,
1012
+ )
1013
+ members.append(
1014
+ Member(id=item.id, name=item.name, backend=member_backend, workspace=workspace)
1015
+ )
1016
+ if recipe.lead.human:
1017
+ lead = Lead(backend=HumanBackend())
1018
+ else:
1019
+ assert recipe.lead.tool is not None
1020
+ lead = Lead(
1021
+ backend=backend(
1022
+ recipe.lead.tool, recipe.lead.model, recipe.lead.effort, "the lead"
1023
+ ),
1024
+ folder=_project_root(root / recipe.lead.folder, "the lead's folder"),
1025
+ )
1026
+ return PanelSpec(
1027
+ goal=goal,
1028
+ lead=lead,
1029
+ members=tuple(members),
1030
+ visibility=recipe.visibility,
1031
+ max_rounds=max_rounds or recipe.max_rounds,
1032
+ concurrency=recipe.concurrency,
1033
+ timeout_seconds=recipe.timeout,
1034
+ turn_timeout_seconds=recipe.turn_timeout,
1035
+ require_blocked=frozenset(RestrictionChannel(c) for c in recipe.require_blocked),
1036
+ allow_project_hooks=allow_project_hooks,
1037
+ protocol_notice=text(recipe.notice, "notice") if recipe.notice else None,
1038
+ human_timeout_seconds=recipe.human_timeout,
1039
+ )
1040
+ except (ValidationError, ValueError, WorkspaceError) as exc:
1041
+ console.error(f"The panel recipe is invalid: {exc}")
1042
+ raise typer.Exit(1) from None
1043
+
1044
+
1045
+ _TERMINAL = threading.Lock()
1046
+
1047
+
1048
+ def _terminal_reply(
1049
+ request: Any, view: PanelView | None = None, members: tuple[str, ...] = ()
1050
+ ) -> Any:
1051
+ """One human seat's prompt and reply on the terminal, one seat at a time.
1052
+
1053
+ A request that expires while waiting for the terminal is never prompted,
1054
+ and one that expires mid-reply stops reading and frees the terminal.
1055
+ While the person types, the panel's live line and other output wait.
1056
+ """
1057
+ while not _TERMINAL.acquire(timeout=0.2):
1058
+ if request.expired.is_set():
1059
+ return None
1060
+ try:
1061
+ if request.expired.is_set():
1062
+ return None
1063
+ # The messages this seat answers are printed above the prompt, unless
1064
+ # the view is slow to catch up; then the prompt shows them itself.
1065
+ shown = view is not None and view.wait_announced(request.request_id, timeout=2.0)
1066
+ with view.hold() if view is not None else contextlib.nullcontext():
1067
+ return _read_terminal_reply(request, message_shown=shown, members=members)
1068
+ finally:
1069
+ _TERMINAL.release()
1070
+
1071
+
1072
+ class _StdinLines:
1073
+ """stdin, read a whole line at a time by one thread of its own.
1074
+
1075
+ A seat waits on the queue, not on the stream, so it can stop the moment
1076
+ its request expires. Nothing is ever hidden from it: every line the
1077
+ stream buffered is already in the queue, unlike text left in
1078
+ ``sys.stdin``'s buffer behind a readiness check of its descriptor. A
1079
+ blocking read on a thread works the same on every platform. Lines go to
1080
+ seats in order, so piped replies are taken as given; at a terminal, lines
1081
+ typed before a prompt appeared are dropped when it does, since no one
1082
+ could have meant them for it. The reader is a daemon and never holds up exit.
1083
+ """
1084
+
1085
+ def __init__(self, stream: IO[str]) -> None:
1086
+ self.stream = stream
1087
+ self.interactive = _isatty(stream)
1088
+ self._lines: queue.Queue[str | None] = queue.Queue()
1089
+ self._closed = threading.Event()
1090
+ threading.Thread(target=self._pump, daemon=True, name="crossby-stdin").start()
1091
+
1092
+ def _pump(self) -> None:
1093
+ try:
1094
+ while True:
1095
+ line = self.stream.readline()
1096
+ if line:
1097
+ self._lines.put(line)
1098
+ continue
1099
+ # End of input. At a terminal it ends one reply (Ctrl-D) and
1100
+ # the next prompt can read again; anywhere else it is final.
1101
+ self._lines.put(None)
1102
+ if not self.interactive:
1103
+ break
1104
+ except (OSError, ValueError):
1105
+ pass
1106
+ self._closed.set()
1107
+
1108
+ def drop_typed_ahead(self) -> None:
1109
+ if not self.interactive:
1110
+ return
1111
+ while True:
1112
+ try:
1113
+ self._lines.get_nowait()
1114
+ except queue.Empty:
1115
+ return
1116
+
1117
+ def next(self, expired: threading.Event) -> str | None:
1118
+ """The next line, or ``None`` at end of input or once ``expired`` is set."""
1119
+ while not expired.is_set():
1120
+ try:
1121
+ return self._lines.get(timeout=0.1)
1122
+ except queue.Empty:
1123
+ if self._closed.is_set() and self._lines.empty():
1124
+ return None
1125
+ return None
1126
+
1127
+
1128
+ def _isatty(stream: IO[str]) -> bool:
1129
+ try:
1130
+ return stream.isatty()
1131
+ except (AttributeError, OSError, ValueError):
1132
+ return False
1133
+
1134
+
1135
+ _STDIN: dict[str, _StdinLines] = {}
1136
+ _STDIN_LOCK = threading.Lock()
1137
+
1138
+
1139
+ def _stdin_lines() -> _StdinLines:
1140
+ """The reader of the current ``sys.stdin``, started on first use."""
1141
+ with _STDIN_LOCK:
1142
+ reader = _STDIN.get("current")
1143
+ if reader is None or reader.stream is not sys.stdin:
1144
+ reader = _STDIN["current"] = _StdinLines(sys.stdin)
1145
+ return reader
1146
+
1147
+
1148
+ def _readline(request: Any) -> str | None:
1149
+ """One line of stdin, or ``None`` at end of input or once the request expired."""
1150
+ return _stdin_lines().next(request.expired)
1151
+
1152
+
1153
+ def _read_terminal_reply(
1154
+ request: Any, *, message_shown: bool = False, members: tuple[str, ...] = ()
1155
+ ) -> Any:
1156
+ """A human seat's reply, read from stdin: lines up to a lone "." or end of input.
1157
+
1158
+ A human lead then names the members (`@cto @founder`, `@all`) or types
1159
+ `done` for a final answer. ``message_shown`` means the messages this seat
1160
+ answers are already on screen, so the prompt points at them instead.
1161
+ """
1162
+ from comitia.discussion.panel import HumanReply
1163
+
1164
+ who = "lead" if request.kind == "lead" else f"@{request.participant}"
1165
+ _stdin_lines().drop_typed_ahead()
1166
+ if request.kind == "lead" and request.message is None:
1167
+ head = "your turn: write your first message to the panel"
1168
+ elif request.kind == "lead":
1169
+ head = "your turn: the replies are above" if message_shown else "your turn. The replies:"
1170
+ else:
1171
+ head = (
1172
+ "your turn: reply to the lead's message above"
1173
+ if message_shown
1174
+ else "your turn. The lead's message:"
1175
+ )
1176
+ _stderr(f" [step]▸[/] [bold]{_escape(who)}[/], {head}")
1177
+ if request.message and not message_shown:
1178
+ sys.stderr.write(f"\n{request.message}\n\n")
1179
+ _stderr("[dim] End your reply with a line holding only a period (or Ctrl-D).[/]")
1180
+ lines: list[str] = []
1181
+ while (line := _readline(request)) is not None:
1182
+ if line.rstrip("\n") == ".":
1183
+ break
1184
+ lines.append(line.rstrip("\n"))
1185
+ if request.expired.is_set():
1186
+ return None
1187
+ text = "\n".join(lines).strip()
1188
+ if not text:
1189
+ return None
1190
+ if request.kind != "lead":
1191
+ return HumanReply(text)
1192
+ names = " ".join(f"@{member}" for member in members) or "@ids"
1193
+ _stderr(
1194
+ f"[dim] Send it to whom? {_escape(names)}, @all, or done for your final answer:[/]"
1195
+ )
1196
+ target = (_readline(request) or "").strip()
1197
+ if target.lower() == "done":
1198
+ return HumanReply(text, done=True)
1199
+ return HumanReply(text, recipients=tuple(target.replace(",", " ").split()))
1200
+
1201
+
1202
+ def _report_panel(
1203
+ result: PanelResult,
1204
+ transcript: Path,
1205
+ events: Path | None,
1206
+ run_id: str,
1207
+ *,
1208
+ as_json: bool,
1209
+ answer_shown: bool,
1210
+ ) -> None:
1211
+ from comitia.discussion.panel import describe_panel_stop
1212
+
1213
+ outcome = describe_panel_stop(result)
1214
+ if as_json:
1215
+ _print_json(
1216
+ {
1217
+ "status": result.stop_reason.value,
1218
+ "answered": result.answered,
1219
+ "final_answer": result.final_answer,
1220
+ "outcome": outcome,
1221
+ "error": result.error,
1222
+ "dispatches": result.dispatches,
1223
+ "members": [
1224
+ {
1225
+ "id": member.id,
1226
+ "tool": member.tool_name,
1227
+ "session_id": result.sessions.get(member.id),
1228
+ "replies": sum(1 for t in result.turns if t.sender == member.id),
1229
+ }
1230
+ for member in result.spec.members
1231
+ ],
1232
+ "member_failures": [
1233
+ {"message": dispatch, "member": member, "reason": reason}
1234
+ for dispatch, member, reason in result.member_failures
1235
+ ],
1236
+ "transcript_path": str(transcript),
1237
+ "events_path": str(events) if events is not None else None,
1238
+ "journal_error": result.journal_error,
1239
+ "run_id": run_id,
1240
+ }
1241
+ )
1242
+ return
1243
+ # stdout carries only the lead's final answer, so it can be piped.
1244
+ if result.final_answer is not None and not answer_shown:
1245
+ print(result.final_answer)
1246
+ if result.answered:
1247
+ _stderr(f" [success]✓[/] {_escape(outcome)}")
1248
+ elif result.exit_code == 1:
1249
+ _stderr(f" [error]✗ Error:[/] {_escape(outcome)}")
1250
+ else:
1251
+ _stderr(f" [warning]![/] {_escape(outcome)}")
1252
+ for dispatch, member, reason in result.member_failures:
1253
+ _stderr(f"[dim] no answer from @{member} to message {dispatch}: {_escape(reason)}[/]")
1254
+ _stderr(f"[dim] transcript: {_escape(str(transcript))}[/]")