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,1647 @@
1
+ # Copied from crossby v0.71.0 (src/crossby/services/panel.py), imports aside.
2
+ """Panels: one lead consults several read-only members.
3
+
4
+ A panel generalizes a two-party consultation. The lead holds the goal and
5
+ addresses members by id on the last line of each message::
6
+
7
+ NEXT: ASK @cto @founder (those members)
8
+ NEXT: ASK @all (every member)
9
+ NEXT: DONE (the reply is the final answer)
10
+
11
+ Addressed members answer in parallel (at most ``concurrency`` at once), each
12
+ from its own folder and resumed session, read-only; their replies reach the
13
+ lead in roster order, each under its ``@id`` label. A member that fails is a
14
+ factual note in that message; a dispatch in which every member fails stops
15
+ the panel. ``max_rounds`` counts the lead's dispatches, plus one final turn.
16
+
17
+ In a ``private`` panel a member receives only what the lead addresses to it.
18
+ In a ``shared`` panel a member also receives, on its next turn, the other
19
+ members' replies it has not seen, under their labels: no extra turns run.
20
+
21
+ crossby adds only protocol text: the lead's opening notice (the goal, the
22
+ roster and the limit; replaceable through ``protocol_notice``, whose grammar
23
+ never changes), the ``@id`` labels, failure notes, the final-turn nudge, and
24
+ one request for the last line when an agent lead's reply lacks a valid one.
25
+ Everything is journaled (see :mod:`crossby.services.journal`).
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import re
31
+ import threading
32
+ from collections.abc import Callable, Collection, Mapping, Sequence
33
+ from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
34
+ from dataclasses import dataclass, field
35
+ from datetime import UTC, datetime
36
+ from pathlib import Path
37
+ from time import monotonic
38
+ from typing import TYPE_CHECKING, Annotated, Any, Literal
39
+
40
+ from crossby.ai_tools import (
41
+ HeadlessEvent,
42
+ HeadlessInteractionMode,
43
+ HeadlessSessionRequest,
44
+ HeadlessSessionResult,
45
+ HeadlessTerminalStatus,
46
+ TokenUsage,
47
+ )
48
+ from crossby.api import (
49
+ CliBackend,
50
+ OwnedWorkspace,
51
+ ProjectWorkspace,
52
+ RestrictionChannel,
53
+ Workspace,
54
+ render_envelope,
55
+ )
56
+ from pydantic import (
57
+ BaseModel,
58
+ ConfigDict,
59
+ Discriminator,
60
+ Field,
61
+ Tag,
62
+ field_validator,
63
+ model_validator,
64
+ )
65
+
66
+ from comitia.discussion.converse import (
67
+ EXIT_CODES,
68
+ MIN_TURN_SECONDS,
69
+ PREFLIGHT_RESUME_ID,
70
+ ConverseError,
71
+ HeadlessTurnRunner,
72
+ StopReason,
73
+ TurnRunner,
74
+ _usage_data,
75
+ check_depth,
76
+ child_environment,
77
+ )
78
+
79
+ if TYPE_CHECKING:
80
+ from comitia.discussion.journal import ConversationEvent, Journal
81
+
82
+ PANEL_NOTICE_VERSION = 1
83
+ MAX_MEMBERS = 16
84
+ _MEMBER_ID = re.compile(r"[a-z0-9][a-z0-9-]{0,31}")
85
+ # "all" addresses every member and "lead" names the lead in labels, events
86
+ # and sessions, so neither can be a member's id.
87
+ _RESERVED_IDS = frozenset({"all", "lead"})
88
+ _NEXT_LINE = re.compile(
89
+ r"^[\s*_`>#-]*next\s*:\s*[*_`]*\s*(ask|done)\b(?P<args>[^\n]*?)[\s*_`.!]*$",
90
+ re.IGNORECASE,
91
+ )
92
+
93
+ PANEL_NOTICE = (
94
+ "Goal: {goal}\n\n"
95
+ "You lead a panel of {count}: {roster}. Each reply you write goes to the members you "
96
+ "name on its last line, and their answers come back to you together, each under its "
97
+ "@id. End every reply with `NEXT: ASK @id` (one or more ids, or `@all`) to send it, or "
98
+ "with `NEXT: DONE` when the reply is your final answer. You can send at most "
99
+ "{max_rounds} messages."
100
+ )
101
+ # Sent at the start of an agent member's first message, so it knows which
102
+ # @id is its own when one message addresses several members.
103
+ MEMBER_NOTICE_VERSION = 1
104
+ MEMBER_NOTICE = (
105
+ "You are @{id}{name} on a panel whose members are {roster}. The lead's messages may "
106
+ "address several members by @id: answer what is asked of @{id}, or of everyone, and "
107
+ "leave other members' questions to them. Your reply goes back to the lead as written."
108
+ )
109
+ FINAL_NUDGE = (
110
+ "You have used all {max_rounds} messages. Write your final answer now and end with the "
111
+ "line `NEXT: DONE`."
112
+ )
113
+ # Sent once to an agent lead whose reply's last line was missing or wrong; the
114
+ # reply is then sent as written, by the line it answers with.
115
+ LINE_REPAIR = (
116
+ "Your last reply was not sent: {problem}. Answer with only the line that ends it: "
117
+ "`NEXT: ASK @id` (one or more ids, or `@all`) to send it as written, or `NEXT: DONE` "
118
+ "if it is your final answer."
119
+ )
120
+
121
+
122
+ class PanelError(ConverseError):
123
+ """A panel request is invalid before any agent starts."""
124
+
125
+
126
+ class _Frozen(BaseModel):
127
+ model_config = ConfigDict(extra="forbid", frozen=True)
128
+
129
+
130
+ class HumanBackend(_Frozen):
131
+ """A seat a person takes: their turns come from a :class:`HumanInput`."""
132
+
133
+ kind: Literal["human"] = "human"
134
+
135
+
136
+ def _backend_kind(value: Any) -> str:
137
+ if isinstance(value, dict):
138
+ return str(value.get("kind", "cli"))
139
+ return "human" if isinstance(value, HumanBackend) else "cli"
140
+
141
+
142
+ Backend = Annotated[
143
+ Annotated[CliBackend, Tag("cli")] | Annotated[HumanBackend, Tag("human")],
144
+ Discriminator(_backend_kind),
145
+ ]
146
+
147
+
148
+ class Member(_Frozen):
149
+ """One member: an id the lead addresses, and an agent with its folder, or a person.
150
+
151
+ An agent member is always read-only; a human member has no folder.
152
+ ``readable_dirs`` are folders an agent member may also read, as in an ask:
153
+ a persona folder's member can then read the project it discusses.
154
+ """
155
+
156
+ id: str
157
+ name: str | None = None
158
+ backend: Backend
159
+ workspace: Workspace | None = None
160
+ readable_dirs: tuple[Path, ...] = ()
161
+
162
+ @field_validator("id")
163
+ @classmethod
164
+ def _id_is_addressable(cls, value: str) -> str:
165
+ if not _MEMBER_ID.fullmatch(value) or value in _RESERVED_IDS:
166
+ raise ValueError(
167
+ f"member id {value!r} must be lowercase letters, digits and hyphens "
168
+ "(not 'all' or 'lead')"
169
+ )
170
+ return value
171
+
172
+ @model_validator(mode="after")
173
+ def _seat_is_coherent(self) -> Member:
174
+ if isinstance(self.backend, HumanBackend):
175
+ if self.workspace is not None or self.readable_dirs:
176
+ raise ValueError(f"human member {self.id} has no folder")
177
+ return self
178
+ if self.workspace is None:
179
+ raise ValueError(f"member {self.id} needs a folder")
180
+ if isinstance(self.workspace, OwnedWorkspace) and self.workspace.tool is not (
181
+ self.backend.tool
182
+ ):
183
+ raise ValueError(f"member {self.id}'s persona folder is for {self.workspace.tool}")
184
+ return self
185
+
186
+ @property
187
+ def human(self) -> bool:
188
+ return isinstance(self.backend, HumanBackend)
189
+
190
+ @property
191
+ def tool_name(self) -> str:
192
+ return "human" if isinstance(self.backend, HumanBackend) else self.backend.tool.value
193
+
194
+ @property
195
+ def label(self) -> str:
196
+ return f"@{self.id}"
197
+
198
+
199
+ class Lead(_Frozen):
200
+ """Who holds the goal: an agent running in ``folder``, or a person.
201
+
202
+ An agent lead keeps its folder's normal unattended policy, unless
203
+ ``read_only`` is set: it then runs under its tool's verified read-only
204
+ profile and must have the panel's ``require_blocked`` channels blocked,
205
+ like a member, and a tool without such a profile is refused at preflight.
206
+ """
207
+
208
+ backend: Backend
209
+ folder: Path | None = None
210
+ read_only: bool = False
211
+
212
+ @model_validator(mode="after")
213
+ def _seat_is_coherent(self) -> Lead:
214
+ if isinstance(self.backend, HumanBackend):
215
+ if self.read_only:
216
+ raise ValueError("a person leading a panel runs no session to make read-only")
217
+ return self
218
+ if self.folder is None:
219
+ raise ValueError("an agent lead needs a folder")
220
+ return self
221
+
222
+ @property
223
+ def human(self) -> bool:
224
+ return isinstance(self.backend, HumanBackend)
225
+
226
+ @property
227
+ def tool_name(self) -> str:
228
+ return "human" if isinstance(self.backend, HumanBackend) else self.backend.tool.value
229
+
230
+
231
+ class PanelSpec(_Frozen):
232
+ goal: str
233
+ lead: Lead
234
+ members: tuple[Member, ...]
235
+ visibility: Literal["private", "shared"] = "private"
236
+ max_rounds: int = Field(default=5, ge=1)
237
+ concurrency: int = Field(default=4, ge=1, le=MAX_MEMBERS)
238
+ timeout_seconds: float = Field(default=1800.0, gt=0)
239
+ turn_timeout_seconds: float = Field(default=600.0, gt=0)
240
+ # Channels every member must have verified blocked (see crossby.api).
241
+ require_blocked: frozenset[RestrictionChannel] = frozenset()
242
+ allow_project_hooks: bool = False
243
+ # Replaces the wording of the lead's opening notice; it is formatted with
244
+ # {goal}, {roster}, {count} and {max_rounds}. The grammar never changes.
245
+ protocol_notice: str | None = None
246
+ # How long a human seat may take to reply before its turn times out.
247
+ human_timeout_seconds: float = Field(default=1800.0, gt=0)
248
+
249
+ @field_validator("goal")
250
+ @classmethod
251
+ def _goal_is_not_blank(cls, value: str) -> str:
252
+ if not value.strip():
253
+ raise ValueError("the goal is empty")
254
+ return value
255
+
256
+ @model_validator(mode="after")
257
+ def _roster_is_valid(self) -> PanelSpec:
258
+ if not 1 <= len(self.members) <= MAX_MEMBERS:
259
+ raise ValueError(f"a panel needs 1 to {MAX_MEMBERS} members")
260
+ ids = [member.id for member in self.members]
261
+ if len(set(ids)) != len(ids):
262
+ raise ValueError("member ids must be unique")
263
+ return self
264
+
265
+
266
+ # ---------------------------------------------------------------------------
267
+ # Grammar
268
+ # ---------------------------------------------------------------------------
269
+
270
+
271
+ class ProtocolError(ValueError):
272
+ """The lead's last line does not address the panel validly."""
273
+
274
+
275
+ @dataclass(frozen=True)
276
+ class Dispatch:
277
+ done: bool
278
+ recipients: tuple[str, ...] = ()
279
+
280
+
281
+ def parse_dispatch(text: str, member_ids: Sequence[str]) -> tuple[str, Dispatch]:
282
+ """Split a lead reply into ``(body, dispatch)``, or raise :class:`ProtocolError`.
283
+
284
+ Only the last non-blank line is read. ``NEXT: ASK`` with no ids addresses
285
+ the only member of a one-member panel; ``@all`` cannot be combined with
286
+ ids; ``NEXT: DONE`` takes none.
287
+ """
288
+ lines = text.rstrip().splitlines()
289
+ index = next((i for i in range(len(lines) - 1, -1, -1) if lines[i].strip()), None)
290
+ if index is None:
291
+ raise ProtocolError("the message is empty")
292
+ match = _NEXT_LINE.match(lines[index])
293
+ body = "\n".join(lines[:index]).strip()
294
+ if match is None:
295
+ if len(member_ids) == 1:
296
+ # A reply without the marker is sent on, as in a consultation.
297
+ return text.strip(), Dispatch(done=False, recipients=(member_ids[0],))
298
+ raise ProtocolError("the last line is not `NEXT: ASK @id …` or `NEXT: DONE`")
299
+ action = match.group(1).lower()
300
+ names = [token for token in re.split(r"[\s,]+", match.group("args").strip()) if token]
301
+ if action == "done":
302
+ if names:
303
+ raise ProtocolError("`NEXT: DONE` takes no members")
304
+ return body, Dispatch(done=True)
305
+ if not names:
306
+ if len(member_ids) == 1:
307
+ return body, Dispatch(done=False, recipients=(member_ids[0],))
308
+ raise ProtocolError("`NEXT: ASK` must name members (`@id` or `@all`)")
309
+ if any(not name.startswith("@") for name in names):
310
+ raise ProtocolError("members are named as `@id`")
311
+ ids = [name[1:].lower() for name in names]
312
+ if "all" in ids:
313
+ if len(ids) > 1:
314
+ raise ProtocolError("`@all` cannot be combined with member ids")
315
+ return body, Dispatch(done=False, recipients=tuple(member_ids))
316
+ unknown = [name for name in ids if name not in member_ids]
317
+ if unknown:
318
+ raise ProtocolError(f"no member is named @{unknown[0]}")
319
+ if len(set(ids)) != len(ids):
320
+ raise ProtocolError("a member is named twice")
321
+ # Roster order, whatever order the lead named them in.
322
+ return body, Dispatch(done=False, recipients=tuple(m for m in member_ids if m in ids))
323
+
324
+
325
+ def _last_line(text: str) -> str:
326
+ return next((line for line in reversed(text.splitlines()) if line.strip()), "")
327
+
328
+
329
+ def _body_without_line(text: str) -> str:
330
+ """A lead reply without its last line, when that line is a (wrong) ``NEXT:`` line."""
331
+ lines = text.rstrip().splitlines()
332
+ if lines and _NEXT_LINE.match(lines[-1]):
333
+ return "\n".join(lines[:-1]).strip()
334
+ return text.strip()
335
+
336
+
337
+ # ---------------------------------------------------------------------------
338
+ # Human seats
339
+ # ---------------------------------------------------------------------------
340
+
341
+
342
+ @dataclass(frozen=True)
343
+ class InputRequest:
344
+ """A human seat's turn: what they are asked to reply to."""
345
+
346
+ request_id: str
347
+ participant: str # "lead" or a member id
348
+ kind: Literal["lead", "member"]
349
+ turn: int
350
+ # For a member: the lead's message (with missed replies, if shared). For
351
+ # the lead: the members' replies, or None for its first message.
352
+ message: str | None
353
+ # Set once the request has timed out or been cancelled: a responder still
354
+ # working on it should stop, and must not prompt anyone.
355
+ expired: threading.Event = field(default_factory=threading.Event, compare=False, repr=False)
356
+
357
+
358
+ @dataclass(frozen=True)
359
+ class HumanReply:
360
+ """A human's reply. A human lead names its ``recipients`` or sets ``done``."""
361
+
362
+ text: str
363
+ recipients: tuple[str, ...] = ()
364
+ done: bool = False
365
+
366
+
367
+ HumanResponder = Callable[[InputRequest], "HumanReply | None"]
368
+
369
+
370
+ class HumanInput:
371
+ """Where a panel gets its human seats' replies.
372
+
373
+ A UI watches for ``input.requested`` events (or calls :meth:`pending`) and
374
+ calls :meth:`submit` with the request's id. A ``responder`` instead
375
+ answers each request synchronously (the CLI reads the terminal). Safe from
376
+ any thread.
377
+ """
378
+
379
+ def __init__(self, responder: HumanResponder | None = None) -> None:
380
+ self._responder = responder
381
+ self._lock = threading.Lock()
382
+ self._open: dict[str, InputRequest] = {}
383
+ self._replies: dict[str, HumanReply] = {}
384
+ self._ready = threading.Condition(self._lock)
385
+
386
+ def pending(self) -> tuple[InputRequest, ...]:
387
+ with self._lock:
388
+ return tuple(self._open.values())
389
+
390
+ def submit(
391
+ self,
392
+ request_id: str,
393
+ text: str,
394
+ *,
395
+ recipients: Sequence[str] = (),
396
+ done: bool = False,
397
+ ) -> None:
398
+ """Reply to an open request; raises ``KeyError`` for an unknown or closed one."""
399
+ with self._ready:
400
+ if request_id not in self._open:
401
+ raise KeyError(f"no open input request {request_id!r}")
402
+ self._replies[request_id] = HumanReply(text, tuple(recipients), done)
403
+ self._ready.notify_all()
404
+
405
+ def _open_request(self, request: InputRequest) -> None:
406
+ """Register a request; it is open before anyone can learn of it."""
407
+ with self._ready:
408
+ self._open[request.request_id] = request
409
+
410
+ def _await(
411
+ self, request: InputRequest, timeout: float, cancel: threading.Event
412
+ ) -> tuple[HumanReply | None, str]:
413
+ """The reply to an open request and how it resolved: answered, timed_out or cancelled.
414
+
415
+ A synchronous responder runs in a worker bound by the same deadline and
416
+ cancellation; a reply it gives too late is discarded. However the wait
417
+ ends without an answer, even by an exception such as Ctrl-C, the
418
+ request is expired, so a responder still working on it stops.
419
+ """
420
+ answered = False
421
+ try:
422
+ reply, how = self._wait(request, timeout, cancel)
423
+ answered = how == "answered"
424
+ return reply, how
425
+ finally:
426
+ if not answered:
427
+ request.expired.set()
428
+
429
+ def _wait(
430
+ self, request: InputRequest, timeout: float, cancel: threading.Event
431
+ ) -> tuple[HumanReply | None, str]:
432
+ deadline = monotonic() + timeout
433
+ if self._responder is not None:
434
+ responder = self._responder
435
+ box: list[HumanReply | None] = []
436
+ finished = threading.Event()
437
+
438
+ def answer() -> None:
439
+ try:
440
+ box.append(responder(request))
441
+ except Exception:
442
+ box.append(None)
443
+ finally:
444
+ finished.set()
445
+
446
+ threading.Thread(target=answer, daemon=True, name="crossby-human-seat").start()
447
+ try:
448
+ while not finished.wait(0.1):
449
+ if cancel.is_set():
450
+ return None, "cancelled"
451
+ if monotonic() >= deadline:
452
+ return None, "timed_out"
453
+ reply = box[0] if box else None
454
+ return (reply, "answered") if reply is not None else (None, "cancelled")
455
+ finally:
456
+ with self._ready:
457
+ self._open.pop(request.request_id, None)
458
+ with self._ready:
459
+ self._open.setdefault(request.request_id, request)
460
+ try:
461
+ while request.request_id not in self._replies:
462
+ if cancel.is_set():
463
+ return None, "cancelled"
464
+ left = deadline - monotonic()
465
+ if left <= 0:
466
+ return None, "timed_out"
467
+ self._ready.wait(min(left, 0.1))
468
+ return self._replies.pop(request.request_id), "answered"
469
+ finally:
470
+ self._open.pop(request.request_id, None)
471
+ self._replies.pop(request.request_id, None)
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Results
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ @dataclass(frozen=True)
480
+ class PanelTurn:
481
+ """One committed message: from the lead, or one member's reply."""
482
+
483
+ number: int
484
+ sender: str # "lead" or a member id
485
+ text: str
486
+ recipients: tuple[str, ...] = ()
487
+ done: bool = False
488
+ duration_seconds: float = 0.0
489
+ denials: tuple[str, ...] = ()
490
+ usage: TokenUsage | None = None
491
+
492
+
493
+ @dataclass
494
+ class PanelResult:
495
+ spec: PanelSpec
496
+ started_at: datetime
497
+ finished_at: datetime
498
+ stop_reason: StopReason
499
+ turns: list[PanelTurn] = field(default_factory=list)
500
+ error: str | None = None
501
+ # Member failures noted to the lead: (dispatch number, member id, reason).
502
+ member_failures: list[tuple[int, str, str]] = field(default_factory=list)
503
+ sessions: dict[str, str | None] = field(default_factory=dict)
504
+ answered_at_limit: bool = False
505
+ # Messages the lead actually sent to members.
506
+ dispatches: int = 0
507
+ # The highest turn number used, failed attempts included: a continued
508
+ # panel numbers its turns after it.
509
+ last_turn: int = 0
510
+ # In a shared panel: the other members' replies each member has not been
511
+ # sent yet, as ``(member id, text)``; a continued panel sends them first.
512
+ unseen: dict[str, tuple[tuple[str, str], ...]] = field(default_factory=dict)
513
+ # The lead's last message was committed at the message limit and never sent;
514
+ # a continued panel sends it first, if any messages are added.
515
+ held_back: bool = False
516
+ # Set by the panel functions of comitia.discussion.api: why the events file is
517
+ # missing or incomplete, and each on_event sink that raised and was dropped.
518
+ journal_error: str | None = None
519
+ sink_errors: tuple[str, ...] = ()
520
+
521
+ @property
522
+ def answered(self) -> bool:
523
+ return self.stop_reason is StopReason.ANSWERED
524
+
525
+ @property
526
+ def final_answer(self) -> str | None:
527
+ last = self.turns[-1] if self.turns else None
528
+ return last.text if last is not None and last.done else None
529
+
530
+ @property
531
+ def exit_code(self) -> int:
532
+ return EXIT_CODES[self.stop_reason]
533
+
534
+
535
+ # ---------------------------------------------------------------------------
536
+ # Engine
537
+ # ---------------------------------------------------------------------------
538
+
539
+
540
+ class _StopError(Exception):
541
+ def __init__(self, reason: StopReason, error: str) -> None:
542
+ super().__init__(error)
543
+ self.reason = reason
544
+ self.error = error
545
+
546
+
547
+ @dataclass
548
+ class _Seat:
549
+ member: Member
550
+ session_id: str | None = None
551
+ # Other members' replies a shared member has not seen yet.
552
+ pending: list[tuple[str, str]] = field(default_factory=list)
553
+
554
+
555
+ def render_notice(spec: PanelSpec) -> str:
556
+ roster = ", ".join(
557
+ f"@{member.id}" + (f" ({member.name})" if member.name else "") for member in spec.members
558
+ )
559
+ template = spec.protocol_notice or PANEL_NOTICE
560
+ return template.format(
561
+ goal=spec.goal, roster=roster, count=len(spec.members), max_rounds=spec.max_rounds
562
+ ).strip()
563
+
564
+
565
+ def combine_replies(
566
+ replies: Sequence[tuple[str, str | None, str | None]],
567
+ ) -> str:
568
+ """The lead's next message: each reply under its label, failures as notes."""
569
+ parts: list[str] = []
570
+ for member_id, text, failure in replies:
571
+ if text is not None:
572
+ parts.append(f"@{member_id}:\n{text}")
573
+ else:
574
+ parts.append(f"@{member_id} (no answer: {failure})")
575
+ return "\n\n".join(parts)
576
+
577
+
578
+ def _settings(backend: CliBackend | HumanBackend) -> dict[str, str | None]:
579
+ """The model and effort a seat asked for, as journaled; none for a person."""
580
+ if not isinstance(backend, CliBackend):
581
+ return {"model": None, "effort": None}
582
+ return {
583
+ "model": backend.model,
584
+ "effort": backend.effort.value if backend.effort is not None else None,
585
+ }
586
+
587
+
588
+ def render_member_notice(spec: PanelSpec, member: Member) -> str:
589
+ """The notice an agent member's first message starts with."""
590
+ ids = [f"@{item.id}" for item in spec.members]
591
+ roster = ids[0] if len(ids) == 1 else ", ".join(ids[:-1]) + f" and {ids[-1]}"
592
+ name = f" ({member.name})" if member.name else ""
593
+ return MEMBER_NOTICE.format(id=member.id, name=name, roster=roster)
594
+
595
+
596
+ def member_message(seat: _Seat, body: str, *, shared: bool) -> str:
597
+ """What a member receives: the lead's message, plus missed replies if shared."""
598
+ if not shared or not seat.pending:
599
+ return body
600
+ seen = "\n\n".join(f"@{member_id}:\n{text}" for member_id, text in seat.pending)
601
+ return f"{seen}\n\n@lead:\n{body}"
602
+
603
+
604
+ # The error a panel stopped through ``cancel`` ends with.
605
+ CANCELLED = "the panel was cancelled"
606
+
607
+
608
+ def _roster_data(spec: PanelSpec) -> list[dict[str, Any]]:
609
+ """Every seat as ``conversation.started`` journals it."""
610
+ return [
611
+ {
612
+ "participant": "lead",
613
+ "tool": spec.lead.tool_name,
614
+ **_settings(spec.lead.backend),
615
+ "read_only": spec.lead.read_only,
616
+ },
617
+ *[
618
+ {
619
+ "participant": member.id,
620
+ "name": member.name,
621
+ "tool": member.tool_name,
622
+ **_settings(member.backend),
623
+ "read_only": not member.human,
624
+ "readable_dirs": [str(path) for path in member.readable_dirs],
625
+ }
626
+ for member in spec.members
627
+ ],
628
+ ]
629
+
630
+
631
+ def _seats_of(data: Sequence[Mapping[str, Any]]) -> dict[str, tuple[Any, ...]]:
632
+ """Who sits where, as a continued panel must keep it: tool, model, effort, read-only."""
633
+ return {
634
+ str(item.get("participant")): (
635
+ item.get("tool"),
636
+ item.get("model"),
637
+ item.get("effort"),
638
+ bool(item.get("read_only")),
639
+ )
640
+ for item in data
641
+ }
642
+
643
+
644
+ def _check_roster(spec: PanelSpec, journaled: PanelSpec | Sequence[Mapping[str, Any]]) -> None:
645
+ """Refuse to continue a panel with seats other than the ones it ran with."""
646
+ before = _seats_of(_roster_data(journaled) if isinstance(journaled, PanelSpec) else journaled)
647
+ now = _seats_of(_roster_data(spec))
648
+ if before == now:
649
+ return
650
+ changed = sorted(key for key in before.keys() | now.keys() if before.get(key) != now.get(key))
651
+ raise PanelError(
652
+ "A panel continues with the seats it started with; these differ: "
653
+ + ", ".join("lead" if key == "lead" else f"@{key}" for key in changed)
654
+ )
655
+
656
+
657
+ def _missed_replies(
658
+ turns: Sequence[PanelTurn], member_ids: Sequence[str], breaks: Collection[int] = ()
659
+ ) -> dict[str, tuple[tuple[str, str], ...]]:
660
+ """Each member's unseen replies in a shared panel, replayed from its committed turns.
661
+
662
+ As in a live panel: the replies to one message are delivered together, a
663
+ member that answers has seen everything sent before it, and every reply
664
+ then reaches the other members. ``breaks`` are the indexes in ``turns``
665
+ where a continuation began: replies on either side of one were delivered
666
+ apart, even when they answer the same message.
667
+ """
668
+ pending: dict[str, list[tuple[str, str]]] = {member_id: [] for member_id in member_ids}
669
+ group: list[PanelTurn] = []
670
+
671
+ def flush() -> None:
672
+ for turn in group:
673
+ pending[turn.sender].clear()
674
+ for turn in group:
675
+ for other in member_ids:
676
+ if other != turn.sender:
677
+ pending[other].append((turn.sender, turn.text))
678
+ group.clear()
679
+
680
+ for index, turn in enumerate(turns):
681
+ if turn.sender == "lead" or index in breaks:
682
+ flush()
683
+ if turn.sender != "lead" and turn.sender in pending:
684
+ group.append(turn)
685
+ flush()
686
+ return {member_id: tuple(items) for member_id, items in pending.items()}
687
+
688
+
689
+ def result_from_journal(spec: PanelSpec, events: Sequence[ConversationEvent]) -> PanelResult:
690
+ """Rebuild a panel's result from its journal, as of its last event.
691
+
692
+ ``spec`` is the panel as the caller would run it again: its seats must be
693
+ the ones the journal names, each with the same tool, model and effort. A
694
+ panel that never recorded its end is reported as interrupted.
695
+ """
696
+ from comitia.discussion.journal import EventType
697
+
698
+ started = next((e for e in events if e.type is EventType.CONVERSATION_STARTED), None)
699
+ if started is None or started.data.get("kind") != "panel":
700
+ raise PanelError("The journal holds no panel.")
701
+ _check_roster(spec, started.data.get("participants") or [])
702
+ sessions: dict[str, str | None] = {"lead": None, **{m.id: None for m in spec.members}}
703
+ turns: list[PanelTurn] = []
704
+ failures: list[tuple[int, str, str]] = []
705
+ dispatches = 0
706
+ held = False
707
+ breaks: set[int] = set()
708
+ last_turn = 0
709
+ stop_reason = StopReason.INTERRUPTED
710
+ error: str | None = "the panel ended without recording its outcome"
711
+ answered_at_limit = False
712
+ finished_at = events[-1].ts
713
+
714
+ def moment(value: object, fallback: datetime) -> datetime:
715
+ return datetime.fromisoformat(value) if isinstance(value, str) else fallback
716
+
717
+ for event in events:
718
+ data = event.data
719
+ number = data.get("turn")
720
+ if isinstance(number, int):
721
+ last_turn = max(last_turn, number)
722
+ if event.type is EventType.CONVERSATION_CONTINUED:
723
+ stop_reason = StopReason.INTERRUPTED
724
+ error = "the panel ended without recording its outcome"
725
+ breaks.add(len(turns))
726
+ # A continuation that adds messages first sends one held back at the limit.
727
+ if held and int(data.get("added_rounds") or 0) > 0:
728
+ dispatches += 1
729
+ held = False
730
+ elif event.type is EventType.MESSAGE_COMMITTED:
731
+ turn = PanelTurn(
732
+ number=int(data["turn"]),
733
+ sender=str(data["participant"]),
734
+ text=str(data["text"]),
735
+ recipients=tuple(data.get("recipients") or ()),
736
+ done=bool(data.get("done")),
737
+ duration_seconds=float(data.get("duration_seconds") or 0.0),
738
+ denials=tuple(data.get("denials") or ()),
739
+ usage=TokenUsage.model_validate(data["usage"]) if data.get("usage") else None,
740
+ )
741
+ turns.append(turn)
742
+ if turn.sender == "lead" and not turn.done:
743
+ dispatches += 1
744
+ elif event.type is EventType.TURN_FINISHED:
745
+ participant = str(data.get("participant"))
746
+ status = data.get("status")
747
+ failed = data.get("error")
748
+ session = data.get("session_id")
749
+ if session and status == "succeeded" and not failed and not sessions.get(participant):
750
+ sessions[participant] = str(session)
751
+ if participant != "lead" and failed and status != "cancelled":
752
+ failures.append((dispatches, participant, str(failed)))
753
+ elif event.type is EventType.INPUT_RESOLVED:
754
+ # A person's seat has no session: its missed reply is recorded here.
755
+ participant = str(data.get("participant"))
756
+ status = data.get("status")
757
+ if participant != "lead" and status not in {"answered", "cancelled"}:
758
+ reason = data.get("error") or {
759
+ "timed_out": "no reply in time",
760
+ "empty": "the reply was empty",
761
+ }.get(str(status), str(status))
762
+ failures.append((dispatches, participant, str(reason)))
763
+ elif event.type is EventType.CONVERSATION_FINISHED:
764
+ stop_reason = StopReason(data["stop_reason"])
765
+ error = data.get("error")
766
+ answered_at_limit = bool(data.get("answered_at_limit"))
767
+ finished_at = moment(data.get("finished_at"), event.ts)
768
+ for key, session in (data.get("sessions") or {}).items():
769
+ if session:
770
+ sessions[str(key)] = str(session)
771
+ # What was really sent: at the message limit the lead's last message
772
+ # is committed but never sent.
773
+ rounds = data.get("rounds")
774
+ if isinstance(rounds, int):
775
+ dispatches = rounds
776
+ if "held_back" in data:
777
+ held = bool(data["held_back"])
778
+ elif stop_reason is StopReason.ROUND_LIMIT:
779
+ # A journal from before `held_back` was recorded.
780
+ held = bool(turns) and turns[-1].sender == "lead" and not turns[-1].done
781
+ if turns and turns[-1].done and stop_reason is not StopReason.ANSWERED:
782
+ # The final answer was committed but the run ended before recording it.
783
+ stop_reason, error = StopReason.ANSWERED, None
784
+ return PanelResult(
785
+ spec=spec,
786
+ started_at=moment(started.data.get("started_at"), started.ts),
787
+ finished_at=finished_at,
788
+ stop_reason=stop_reason,
789
+ turns=turns,
790
+ error=error,
791
+ member_failures=failures,
792
+ sessions=sessions,
793
+ answered_at_limit=answered_at_limit,
794
+ dispatches=dispatches,
795
+ last_turn=last_turn,
796
+ held_back=held and stop_reason is not StopReason.ANSWERED,
797
+ unseen=(
798
+ _missed_replies(turns, [m.id for m in spec.members], breaks)
799
+ if spec.visibility == "shared"
800
+ else {}
801
+ ),
802
+ )
803
+
804
+
805
+ def run_panel(
806
+ spec: PanelSpec,
807
+ *,
808
+ runner: TurnRunner | None = None,
809
+ journal: Journal | None = None,
810
+ inputs: HumanInput | None = None,
811
+ clock: Callable[[], float] = monotonic,
812
+ cancel: threading.Event | None = None,
813
+ resume: PanelResult | None = None,
814
+ added_rounds: int | None = None,
815
+ ) -> PanelResult:
816
+ """Run a panel until the lead gives its final answer, or a limit stops it.
817
+
818
+ Human seats get their replies from ``inputs`` (required when the panel has
819
+ one): each turn emits ``input.requested`` and then ``input.resolved``.
820
+
821
+ Setting ``cancel`` stops the running sessions and starts no new one; the
822
+ panel then ends ``interrupted``, keeping every reply already committed.
823
+
824
+ ``resume`` continues a panel that stopped without a final answer (see
825
+ :func:`result_from_journal`): every seat resumes its own session, members
826
+ that had not answered the lead's last message are asked again, and the
827
+ lead may send up to ``added_rounds`` more messages (by default
828
+ ``spec.max_rounds``); with 0 it may only give its final answer.
829
+ """
830
+ from crossby.ai_tools import HeadlessSessionError
831
+
832
+ from comitia.discussion.journal import EventType
833
+
834
+ check_depth()
835
+ has_human = spec.lead.human or any(member.human for member in spec.members)
836
+ if has_human and inputs is None:
837
+ raise PanelError("A panel with a human seat needs a HumanInput.")
838
+ if added_rounds is not None and (resume is None or added_rounds < 0):
839
+ raise PanelError("added_rounds is for continuing a panel, and cannot be negative.")
840
+ if resume is not None:
841
+ if resume.answered or (resume.turns and resume.turns[-1].done):
842
+ raise PanelError("That panel already has its final answer.")
843
+ _check_roster(spec, resume.spec)
844
+ human_inputs = inputs or HumanInput()
845
+ active: TurnRunner = runner or HeadlessTurnRunner()
846
+ started_at = resume.started_at if resume is not None else datetime.now(tz=UTC)
847
+ deadline = clock() + spec.timeout_seconds
848
+ member_ids = [member.id for member in spec.members]
849
+ seats = {member.id: _Seat(member) for member in spec.members}
850
+ lead_session: list[str | None] = [None]
851
+ turns: list[PanelTurn] = list(resume.turns) if resume is not None else []
852
+ failures: list[tuple[int, str, str]] = (
853
+ list(resume.member_failures) if resume is not None else []
854
+ )
855
+ if cancel is None:
856
+ cancel = threading.Event()
857
+ shared = spec.visibility == "shared"
858
+ answered_at_limit = [False]
859
+ sent = [resume.dispatches if resume is not None else 0]
860
+ # Messages the lead may send in all: those already sent plus this run's.
861
+ added = spec.max_rounds if added_rounds is None else added_rounds
862
+ cap = sent[0] + added
863
+ next_turn = [(resume.last_turn if resume is not None else 0) + 1]
864
+ # Whether the lead's last message is committed but unsent, held back at the limit.
865
+ held = [resume.held_back if resume is not None else False]
866
+ # The folders each member's sessions are granted for its ``readable_dirs``.
867
+ grants: dict[str, tuple[Path, ...]] = {}
868
+ if resume is not None:
869
+ lead_session[0] = resume.sessions.get("lead")
870
+ for member_id, seat in seats.items():
871
+ seat.session_id = resume.sessions.get(member_id)
872
+ if shared:
873
+ for member_id, missed in resume.unseen.items():
874
+ if member_id in seats:
875
+ seats[member_id].pending.extend(missed)
876
+
877
+ def claim() -> int:
878
+ """The next turn number: every lead turn and member attempt gets one."""
879
+ with lock:
880
+ number = next_turn[0]
881
+ next_turn[0] += 1
882
+ return number
883
+
884
+ lock = threading.Lock()
885
+
886
+ def emit(type_: EventType, **data: Any) -> None:
887
+ if journal is not None:
888
+ journal.emit(type_, **data)
889
+
890
+ def sessions() -> dict[str, str | None]:
891
+ return {"lead": lead_session[0], **{key: seat.session_id for key, seat in seats.items()}}
892
+
893
+ def finish(reason: StopReason, error: str | None = None) -> PanelResult:
894
+ if reason is StopReason.ROUND_LIMIT and turns:
895
+ last = turns[-1]
896
+ held[0] = held[0] or (last.sender == "lead" and not last.done)
897
+ if reason is StopReason.ANSWERED:
898
+ held[0] = False
899
+ result = PanelResult(
900
+ spec=spec,
901
+ started_at=started_at,
902
+ finished_at=datetime.now(tz=UTC),
903
+ stop_reason=reason,
904
+ turns=turns,
905
+ error=error,
906
+ member_failures=failures,
907
+ sessions=sessions(),
908
+ answered_at_limit=answered_at_limit[0],
909
+ dispatches=sent[0],
910
+ last_turn=next_turn[0] - 1,
911
+ unseen={key: tuple(seat.pending) for key, seat in seats.items()} if shared else {},
912
+ held_back=held[0],
913
+ )
914
+ emit(
915
+ EventType.CONVERSATION_FINISHED,
916
+ stop_reason=reason.value,
917
+ error=error,
918
+ answered_at_limit=answered_at_limit[0],
919
+ rounds=result.dispatches,
920
+ held_back=held[0],
921
+ sessions=result.sessions,
922
+ finished_at=result.finished_at.isoformat(),
923
+ )
924
+ return result
925
+
926
+ def remaining() -> float:
927
+ return deadline - clock()
928
+
929
+ def request(
930
+ prompt: str,
931
+ backend: CliBackend,
932
+ folder: Path,
933
+ *,
934
+ resume_id: str | None,
935
+ read_only: bool,
936
+ minimum_version: str | None = None,
937
+ mcp_servers: Mapping[str, dict[str, object]] | None = None,
938
+ trusted_dirs: tuple[Path, ...] = (),
939
+ ) -> HeadlessSessionRequest:
940
+ if cancel.is_set():
941
+ raise _StopError(StopReason.INTERRUPTED, CANCELLED)
942
+ left = remaining()
943
+ if left < MIN_TURN_SECONDS:
944
+ raise _StopError(
945
+ StopReason.TIMEOUT, f"panel time limit of {spec.timeout_seconds:g}s reached"
946
+ )
947
+ return HeadlessSessionRequest(
948
+ prompt=prompt,
949
+ working_dir=folder,
950
+ model=backend.model,
951
+ effort=backend.effort,
952
+ interaction_mode=HeadlessInteractionMode.UNATTENDED,
953
+ timeout_seconds=min(spec.turn_timeout_seconds, left),
954
+ resume_id=resume_id,
955
+ read_only=read_only,
956
+ mcp_servers=dict(mcp_servers or {}),
957
+ trusted_dirs=trusted_dirs,
958
+ isolated=read_only
959
+ and RestrictionChannel.READS_OUTSIDE_WORKSPACE in spec.require_blocked,
960
+ require_blocked=spec.require_blocked if read_only else frozenset(),
961
+ allow_project_hooks=spec.allow_project_hooks,
962
+ minimum_version=minimum_version,
963
+ environment=child_environment(),
964
+ )
965
+
966
+ def member_folder(member: Member) -> tuple[Path, str | None]:
967
+ workspace = member.workspace
968
+ assert workspace is not None # agent members always have one
969
+ if isinstance(workspace, OwnedWorkspace):
970
+ return workspace.path, workspace.layout.verified_version
971
+ return workspace.path, None
972
+
973
+ def member_servers(member: Member) -> dict[str, dict[str, object]]:
974
+ """A persona member's own MCP servers, on every turn as in an ask."""
975
+ if isinstance(member.workspace, OwnedWorkspace):
976
+ return member.workspace.session_mcp_servers()
977
+ return {}
978
+
979
+ def ask_human(
980
+ participant: str, kind: Literal["lead", "member"], number: int, message: str | None
981
+ ) -> tuple[HumanReply | None, str | None, float]:
982
+ """One human turn: ``(reply, failure, seconds)``."""
983
+ if cancel.is_set():
984
+ # Queued behind a turn that was stopped: the person is never asked.
985
+ return None, "the reply was cancelled", 0.0
986
+ request_id = f"{journal.run_id if journal is not None else 'panel'}-{number}-{participant}"
987
+ request = InputRequest(request_id, participant, kind, number, message)
988
+ # Open before announcing: a UI may submit as soon as it sees the event.
989
+ human_inputs._open_request(request)
990
+ emit(
991
+ EventType.INPUT_REQUESTED,
992
+ request_id=request_id,
993
+ participant=participant,
994
+ kind=kind,
995
+ turn=number,
996
+ message=message,
997
+ )
998
+ begun = clock()
999
+ left = min(spec.human_timeout_seconds, max(remaining(), 0.0))
1000
+ reply, status = human_inputs._await(request, left, cancel)
1001
+ if reply is not None and not reply.text.strip():
1002
+ reply, status = None, "empty"
1003
+ failure = (
1004
+ None
1005
+ if reply is not None
1006
+ else {
1007
+ "timed_out": f"no reply within {left:g}s",
1008
+ "cancelled": "the reply was cancelled",
1009
+ "empty": "the reply was empty",
1010
+ }.get(status, status)
1011
+ )
1012
+ emit(
1013
+ EventType.INPUT_RESOLVED,
1014
+ request_id=request_id,
1015
+ participant=participant,
1016
+ status=status,
1017
+ # Why there is no reply, as the lead is told: a continued panel keeps it.
1018
+ error=failure,
1019
+ )
1020
+ return reply, failure, clock() - begun
1021
+
1022
+ def progress(participant: str, number: int) -> Callable[[HeadlessEvent], None]:
1023
+ def handle(event: HeadlessEvent) -> None:
1024
+ kind = event.kind.value
1025
+ if kind in {"tool_started", "tool_completed", "assistant_message"}:
1026
+ emit(
1027
+ EventType.TURN_PROGRESS,
1028
+ turn=number,
1029
+ participant=participant,
1030
+ kind=kind,
1031
+ elapsed_seconds=round(event.elapsed_seconds, 3),
1032
+ )
1033
+
1034
+ return handle
1035
+
1036
+ def run_one(
1037
+ participant: str,
1038
+ number: int,
1039
+ built: HeadlessSessionRequest,
1040
+ tool: Any,
1041
+ *,
1042
+ needs_session: bool = False,
1043
+ ) -> tuple[HeadlessSessionResult | None, str | None, float]:
1044
+ """Run one session; ``(result, failure, seconds)``. Never raises a session error.
1045
+
1046
+ ``needs_session``: a seat's first turn, whose session its later turns resume;
1047
+ one that reports none fails, and its ``turn.finished`` says so.
1048
+ """
1049
+ emit(
1050
+ EventType.TURN_STARTED,
1051
+ turn=number,
1052
+ participant=participant,
1053
+ tool=tool.value,
1054
+ resumed=built.resume_id is not None,
1055
+ session_id=built.resume_id,
1056
+ )
1057
+ begun = clock()
1058
+ failure: str | None
1059
+ try:
1060
+ result = active.run(tool, built, cancel, on_event=progress(participant, number))
1061
+ except HeadlessSessionError as exc:
1062
+ failure = str(exc)
1063
+ emit(
1064
+ EventType.TURN_FINISHED,
1065
+ turn=number,
1066
+ participant=participant,
1067
+ status="failed",
1068
+ error=failure,
1069
+ duration_seconds=round(clock() - begun, 3),
1070
+ )
1071
+ return None, failure, clock() - begun
1072
+ failure = None
1073
+ text = (result.final_text or "").strip()
1074
+ if result.status is not HeadlessTerminalStatus.SUCCEEDED:
1075
+ from crossby.api import describe_session_status
1076
+
1077
+ failure = f"the session ended with status {describe_session_status(result)}"
1078
+ elif not text:
1079
+ failure = "the session returned no text"
1080
+ session = result.session_id or result.thread_id or result.conversation_id
1081
+ if failure is None and needs_session and session is None:
1082
+ failure = f"{tool.value} reported no session to resume"
1083
+ emit(
1084
+ EventType.TURN_FINISHED,
1085
+ turn=number,
1086
+ participant=participant,
1087
+ status=result.status.value,
1088
+ session_id=session,
1089
+ duration_seconds=round(clock() - begun, 3),
1090
+ denials=list(result.denials),
1091
+ failure_reason=result.failure_reason.value if result.failure_reason else None,
1092
+ error=failure,
1093
+ )
1094
+ return result, failure, clock() - begun
1095
+
1096
+ def commit(turn: PanelTurn) -> None:
1097
+ turns.append(turn)
1098
+ emit(
1099
+ EventType.MESSAGE_COMMITTED,
1100
+ turn=turn.number,
1101
+ participant=turn.sender,
1102
+ text=turn.text,
1103
+ recipients=list(turn.recipients),
1104
+ done=turn.done,
1105
+ duration_seconds=round(turn.duration_seconds, 3),
1106
+ denials=list(turn.denials),
1107
+ usage=_usage_data(turn.usage),
1108
+ )
1109
+
1110
+ def human_lead_turn(message: str | None, number: int) -> tuple[str, Dispatch, float]:
1111
+ reply, failure, seconds = ask_human("lead", "lead", number, message)
1112
+ if reply is None:
1113
+ if cancel.is_set():
1114
+ raise _StopError(StopReason.INTERRUPTED, CANCELLED)
1115
+ if remaining() <= 0:
1116
+ # The panel's time ran out, not the person's own reply window.
1117
+ raise _StopError(
1118
+ StopReason.TIMEOUT, f"panel time limit reached during turn {number}"
1119
+ )
1120
+ raise _StopError(StopReason.FAILED, f"lead turn {number}: {failure}")
1121
+ if reply.done:
1122
+ if reply.recipients:
1123
+ raise _StopError(
1124
+ StopReason.FAILED, f"lead turn {number}: a final answer names no members"
1125
+ )
1126
+ return reply.text.strip(), Dispatch(done=True), seconds
1127
+ recipients = [name.lstrip("@").lower() for name in reply.recipients]
1128
+ if recipients == ["all"]:
1129
+ chosen = tuple(member_ids)
1130
+ elif not recipients and len(member_ids) == 1:
1131
+ chosen = (member_ids[0],)
1132
+ else:
1133
+ unknown = [name for name in recipients if name not in member_ids]
1134
+ if not recipients or unknown or len(set(recipients)) != len(recipients):
1135
+ problem = (
1136
+ f"no member is named @{unknown[0]}" if unknown else "name members once each"
1137
+ )
1138
+ raise _StopError(
1139
+ StopReason.FAILED, f"lead turn {number}: {problem}; nothing was sent"
1140
+ )
1141
+ chosen = tuple(m for m in member_ids if m in recipients)
1142
+ return reply.text.strip(), Dispatch(done=False, recipients=chosen), seconds
1143
+
1144
+ def lead_turn(message: str, number: int) -> tuple[str, float, HeadlessSessionResult]:
1145
+ assert isinstance(spec.lead.backend, CliBackend) and spec.lead.folder is not None
1146
+ built = request(
1147
+ message,
1148
+ spec.lead.backend,
1149
+ spec.lead.folder,
1150
+ resume_id=lead_session[0],
1151
+ read_only=spec.lead.read_only,
1152
+ )
1153
+ result, failure, seconds = run_one("lead", number, built, spec.lead.backend.tool)
1154
+ if result is None or failure is not None:
1155
+ if cancel.is_set():
1156
+ raise _StopError(StopReason.INTERRUPTED, CANCELLED)
1157
+ if remaining() <= 0:
1158
+ raise _StopError(
1159
+ StopReason.TIMEOUT, f"panel time limit reached during turn {number}"
1160
+ )
1161
+ raise _StopError(StopReason.FAILED, f"lead turn {number}: {failure}")
1162
+ if lead_session[0] is None:
1163
+ handle = result.session_id or result.thread_id or result.conversation_id
1164
+ if handle is None:
1165
+ raise _StopError(
1166
+ StopReason.FAILED,
1167
+ f"lead turn {number}: {spec.lead.backend.tool.value} reported no session",
1168
+ )
1169
+ lead_session[0] = handle
1170
+ return (result.final_text or "").strip(), seconds, result
1171
+
1172
+ def mend_line(
1173
+ text: str, problem: ProtocolError, number: int
1174
+ ) -> tuple[str, Dispatch, float, HeadlessSessionResult]:
1175
+ """Ask the lead once for the last line its reply lacked; the reply is kept as written.
1176
+
1177
+ Only the line it answers with is read, so a reply written out again is
1178
+ not sent twice; a wrong line again stops the panel.
1179
+ """
1180
+ if cancel.is_set():
1181
+ raise _StopError(StopReason.INTERRUPTED, CANCELLED)
1182
+ retry = claim()
1183
+ answer, seconds, result = lead_turn(LINE_REPAIR.format(problem=problem), retry)
1184
+ line = _last_line(answer)
1185
+ try:
1186
+ if not _NEXT_LINE.match(line):
1187
+ raise ProtocolError("the last line is not `NEXT: ASK @id …` or `NEXT: DONE`")
1188
+ _marker_only, dispatch = parse_dispatch(line, member_ids)
1189
+ except ProtocolError as exc:
1190
+ raise _StopError(
1191
+ StopReason.FAILED,
1192
+ f"lead turn {number}: {problem}; asked again in turn {retry}: {exc}; "
1193
+ "nothing was sent",
1194
+ ) from None
1195
+ return _body_without_line(text), dispatch, seconds, result
1196
+
1197
+ def member_turn(
1198
+ seat: _Seat, body: str, number: int
1199
+ ) -> tuple[str, str | None, str | None, float, HeadlessSessionResult | None]:
1200
+ member = seat.member
1201
+ message = member_message(seat, body, shared=shared)
1202
+ if member.human:
1203
+ reply, failure, seconds = ask_human(member.id, "member", number, message)
1204
+ if reply is not None:
1205
+ with lock:
1206
+ seat.pending.clear()
1207
+ return member.id, (reply.text.strip() if reply else None), failure, seconds, None
1208
+ assert isinstance(member.backend, CliBackend)
1209
+ folder, minimum = member_folder(member)
1210
+ if seat.session_id is None:
1211
+ # A new session learns which @id is its own before the first question.
1212
+ message = f"{render_member_notice(spec, member)}\n\n{message}"
1213
+ if isinstance(member.workspace, ProjectWorkspace):
1214
+ message = render_envelope(message, member.workspace.instructions)
1215
+ try:
1216
+ built = request(
1217
+ message,
1218
+ member.backend,
1219
+ folder,
1220
+ resume_id=seat.session_id,
1221
+ read_only=True,
1222
+ minimum_version=minimum,
1223
+ mcp_servers=member_servers(member),
1224
+ trusted_dirs=grants.get(member.id, ()),
1225
+ )
1226
+ except _StopError as stop:
1227
+ # Queued past the deadline, or stopped: this attempt never starts, and
1228
+ # the members who already answered keep their replies. Journaled, so a
1229
+ # panel read back keeps the failure.
1230
+ emit(
1231
+ EventType.TURN_FINISHED,
1232
+ turn=number,
1233
+ participant=member.id,
1234
+ status="cancelled" if stop.reason is StopReason.INTERRUPTED else "failed",
1235
+ error=stop.error,
1236
+ duration_seconds=0.0,
1237
+ )
1238
+ return member.id, None, stop.error, 0.0, None
1239
+ result, failure, seconds = run_one(
1240
+ member.id,
1241
+ number,
1242
+ built,
1243
+ member.backend.tool,
1244
+ needs_session=seat.session_id is None,
1245
+ )
1246
+ text = (result.final_text or "").strip() if result is not None else None
1247
+ if failure is None and result is not None and seat.session_id is None:
1248
+ seat.session_id = result.session_id or result.thread_id or result.conversation_id
1249
+ if failure is None:
1250
+ with lock:
1251
+ seat.pending.clear()
1252
+ return member.id, (text if failure is None else None), failure, seconds, result
1253
+
1254
+ def preflight() -> None:
1255
+ from crossby.api import WorkspaceDriftError
1256
+ from crossby.api import verify_workspace as verify
1257
+
1258
+ for member in spec.members:
1259
+ if isinstance(member.workspace, OwnedWorkspace):
1260
+ try:
1261
+ verify(member.workspace)
1262
+ except WorkspaceDriftError as exc:
1263
+ raise _StopError(
1264
+ StopReason.FAILED,
1265
+ f"@{member.id}'s persona folder changed since it was provisioned: "
1266
+ f"{', '.join(exc.changed[:5])}; provision it again",
1267
+ ) from None
1268
+ from crossby.api import AskError, read_grants
1269
+
1270
+ for member in spec.members:
1271
+ if isinstance(member.backend, CliBackend) and member.readable_dirs:
1272
+ try:
1273
+ grants[member.id] = read_grants(member.backend.tool, member.readable_dirs)
1274
+ except AskError as exc:
1275
+ raise _StopError(StopReason.FAILED, f"@{member.id}: {exc}") from None
1276
+ checks: list[
1277
+ tuple[str, CliBackend, Path, bool, str | None, dict[str, dict[str, object]]]
1278
+ ] = []
1279
+ if isinstance(spec.lead.backend, CliBackend) and spec.lead.folder is not None:
1280
+ checks.append(
1281
+ ("lead", spec.lead.backend, spec.lead.folder, spec.lead.read_only, None, {})
1282
+ )
1283
+ for member in spec.members:
1284
+ if isinstance(member.backend, CliBackend):
1285
+ folder, minimum = member_folder(member)
1286
+ checks.append(
1287
+ (member.id, member.backend, folder, True, minimum, member_servers(member))
1288
+ )
1289
+ for participant, backend, folder, read_only, minimum, servers in checks:
1290
+ probe = request(
1291
+ "preflight",
1292
+ backend,
1293
+ folder,
1294
+ resume_id=PREFLIGHT_RESUME_ID,
1295
+ read_only=read_only,
1296
+ minimum_version=minimum,
1297
+ mcp_servers=servers,
1298
+ trusted_dirs=grants.get(participant, ()) if participant != "lead" else (),
1299
+ )
1300
+ try:
1301
+ report = active.preflight(backend.tool, probe)
1302
+ except HeadlessSessionError as exc:
1303
+ raise _StopError(
1304
+ StopReason.FAILED, f"{participant} cannot run headless: {exc}"
1305
+ ) from None
1306
+ emit(
1307
+ EventType.PARTICIPANT_READY,
1308
+ participant=participant,
1309
+ tool=backend.tool.value,
1310
+ model=backend.model,
1311
+ folder=str(folder),
1312
+ read_only=read_only,
1313
+ version=report.detected_version if report is not None else None,
1314
+ restrictions=(
1315
+ {item.channel.value: item.state.value for item in report.restrictions}
1316
+ if report is not None
1317
+ else {}
1318
+ ),
1319
+ warnings=list(report.warnings) if report is not None else [],
1320
+ )
1321
+
1322
+ def fan_out(
1323
+ body: str,
1324
+ recipients: tuple[str, ...],
1325
+ dispatch: int,
1326
+ answered: Mapping[str, str] | None = None,
1327
+ ) -> str:
1328
+ """Send ``body`` to ``recipients``; the lead's next message, from all their replies.
1329
+
1330
+ Members in ``answered`` (a continued panel) already replied to this
1331
+ message: they are not asked again, and their replies come back as given.
1332
+ """
1333
+ answered = answered or {}
1334
+ asking = tuple(member_id for member_id in recipients if member_id not in answered)
1335
+ # Each member's attempt gets its own turn number, kept when its reply
1336
+ # is committed; a failed attempt's number is never reused.
1337
+ numbers = {member_id: claim() for member_id in asking}
1338
+ outcomes: dict[str, tuple[str | None, str | None, float, HeadlessSessionResult | None]] = {}
1339
+ unexpected: BaseException | None = None
1340
+ interrupted = False
1341
+
1342
+ def collect(future: Future[Any], member_id: str) -> None:
1343
+ nonlocal unexpected
1344
+ try:
1345
+ _member, text, failure, seconds, result = future.result()
1346
+ except Exception as exc:
1347
+ unexpected = unexpected or exc
1348
+ outcomes[member_id] = (None, f"the turn failed: {exc}", 0.0, None)
1349
+ return
1350
+ outcomes[member_id] = (text, failure, seconds, result)
1351
+
1352
+ with ThreadPoolExecutor(max_workers=max(min(spec.concurrency, len(asking)), 1)) as pool:
1353
+ futures: dict[Future[Any], str] = {
1354
+ pool.submit(member_turn, seats[member_id], body, numbers[member_id]): member_id
1355
+ for member_id in asking
1356
+ }
1357
+ pending_futures = set(futures)
1358
+ try:
1359
+ while pending_futures:
1360
+ done, pending_futures = wait(
1361
+ pending_futures, timeout=0.1, return_when=FIRST_COMPLETED
1362
+ )
1363
+ for future in done:
1364
+ collect(future, futures[future])
1365
+ except KeyboardInterrupt:
1366
+ # Stop the turns still running and start no queued one; the
1367
+ # replies that already came in are committed below.
1368
+ interrupted = True
1369
+ cancel.set()
1370
+ for future in pending_futures:
1371
+ future.cancel()
1372
+ if interrupted:
1373
+ # The pool has waited for the stopped turns; keep what finished.
1374
+ for future, member_id in futures.items():
1375
+ if member_id not in outcomes and not future.cancelled():
1376
+ collect(future, member_id)
1377
+ replies: list[tuple[str, str | None, str | None]] = []
1378
+ # Stopped through ``cancel`` (Ctrl-C notes its failures, as it always has).
1379
+ stopped = cancel.is_set() and not interrupted
1380
+ for member_id in recipients: # roster order
1381
+ if member_id in answered:
1382
+ replies.append((member_id, answered[member_id], None))
1383
+ continue
1384
+ text, failure, seconds, result = outcomes.get(
1385
+ member_id, (None, "interrupted before it started", 0.0, None)
1386
+ )
1387
+ if text is not None:
1388
+ commit(
1389
+ PanelTurn(
1390
+ number=numbers[member_id],
1391
+ sender=member_id,
1392
+ text=text,
1393
+ recipients=("lead",),
1394
+ duration_seconds=seconds,
1395
+ denials=tuple(result.denials) if result is not None else (),
1396
+ usage=result.usage if result is not None else None,
1397
+ )
1398
+ )
1399
+ if shared:
1400
+ with lock:
1401
+ for other in seats.values():
1402
+ if other.member.id != member_id:
1403
+ other.pending.append((member_id, text))
1404
+ elif stopped and (result is None or result.status is HeadlessTerminalStatus.CANCELLED):
1405
+ # Stopped by ``cancel``, or never started: not a failure. It is
1406
+ # asked again when the panel continues.
1407
+ pass
1408
+ else:
1409
+ failures.append((dispatch, member_id, failure or "no answer"))
1410
+ replies.append((member_id, text, failure))
1411
+ # Every completed reply is committed above before either propagates.
1412
+ if interrupted:
1413
+ raise KeyboardInterrupt
1414
+ if unexpected is not None:
1415
+ raise unexpected
1416
+ if stopped:
1417
+ raise _StopError(StopReason.INTERRUPTED, CANCELLED)
1418
+ if all(text is None for _member, text, _failure in replies):
1419
+ if remaining() < MIN_TURN_SECONDS:
1420
+ # The panel's time ran out, not its members: nothing more can start.
1421
+ raise _StopError(
1422
+ StopReason.TIMEOUT, f"panel time limit reached during message {dispatch}"
1423
+ )
1424
+ raise _StopError(
1425
+ StopReason.FAILED,
1426
+ f"every member addressed in message {dispatch} failed: "
1427
+ + "; ".join(f"@{member} {failure}" for member, _text, failure in replies),
1428
+ )
1429
+ return combine_replies(replies)
1430
+
1431
+ if resume is None:
1432
+ emit(
1433
+ EventType.CONVERSATION_STARTED,
1434
+ goal=spec.goal,
1435
+ kind="panel",
1436
+ visibility=spec.visibility,
1437
+ notice_version=PANEL_NOTICE_VERSION,
1438
+ member_notice_version=MEMBER_NOTICE_VERSION,
1439
+ participants=_roster_data(spec),
1440
+ max_rounds=spec.max_rounds,
1441
+ started_at=started_at.isoformat(),
1442
+ )
1443
+ else:
1444
+ emit(
1445
+ EventType.CONVERSATION_CONTINUED,
1446
+ kind="panel",
1447
+ previous_stop_reason=resume.stop_reason.value,
1448
+ max_rounds=cap,
1449
+ added_rounds=added,
1450
+ timeout_seconds=spec.timeout_seconds,
1451
+ turn_timeout_seconds=spec.turn_timeout_seconds,
1452
+ )
1453
+
1454
+ def owed() -> str:
1455
+ """A continued panel's next message for the lead.
1456
+
1457
+ Members that had not answered the lead's last message are asked it
1458
+ again; with no message from the lead yet, it gets its opening.
1459
+ """
1460
+ last = next((turn for turn in reversed(turns) if turn.sender == "lead"), None)
1461
+ if last is None:
1462
+ return render_notice(spec)
1463
+ replies = {
1464
+ turn.sender: turn.text
1465
+ for turn in turns
1466
+ if turn.number > last.number and turn.sender != "lead"
1467
+ }
1468
+ if held[0]:
1469
+ # Committed at the message limit, so never sent: it is sent now, as one
1470
+ # of the messages added; with none added, the lead is asked to finish.
1471
+ if sent[0] >= cap:
1472
+ return FINAL_NUDGE.format(max_rounds=cap)
1473
+ sent[0] += 1
1474
+ held[0] = False
1475
+ return fan_out(last.text, last.recipients, sent[0], answered=replies)
1476
+
1477
+ try:
1478
+ preflight()
1479
+ first = not any(turn.sender == "lead" for turn in turns)
1480
+ message = owed() if resume is not None else render_notice(spec)
1481
+ dispatches = sent[0]
1482
+ nudge = FINAL_NUDGE.format(max_rounds=cap)
1483
+ if not first and dispatches == cap and not message.endswith(nudge):
1484
+ message = f"{message}\n\n{nudge}"
1485
+ while True:
1486
+ if cancel.is_set():
1487
+ raise _StopError(StopReason.INTERRUPTED, CANCELLED)
1488
+ final = dispatches >= cap
1489
+ number = claim()
1490
+ if spec.lead.human:
1491
+ body, dispatch, seconds = human_lead_turn(None if first else message, number)
1492
+ result = None
1493
+ else:
1494
+ text, seconds, result = lead_turn(message, number)
1495
+ try:
1496
+ body, dispatch = parse_dispatch(text, member_ids)
1497
+ except ProtocolError as exc:
1498
+ written = result
1499
+ body, dispatch, more, result = mend_line(text, exc, number)
1500
+ seconds += more
1501
+ # The reply came from the first session; the line from the second.
1502
+ result = result.model_copy(
1503
+ update={
1504
+ "usage": written.usage,
1505
+ "denials": (*written.denials, *result.denials),
1506
+ }
1507
+ )
1508
+ first = False
1509
+ if not body:
1510
+ raise _StopError(StopReason.FAILED, f"lead turn {number} sent only the marker")
1511
+ commit(
1512
+ PanelTurn(
1513
+ number=number,
1514
+ sender="lead",
1515
+ text=body,
1516
+ recipients=dispatch.recipients,
1517
+ done=dispatch.done,
1518
+ duration_seconds=seconds,
1519
+ denials=tuple(result.denials) if result is not None else (),
1520
+ usage=result.usage if result is not None else None,
1521
+ )
1522
+ )
1523
+ if dispatch.done:
1524
+ answered_at_limit[0] = final
1525
+ return finish(StopReason.ANSWERED)
1526
+ if final:
1527
+ return finish(StopReason.ROUND_LIMIT)
1528
+ dispatches += 1
1529
+ sent[0] = dispatches
1530
+ message = fan_out(body, dispatch.recipients, dispatches)
1531
+ if dispatches == cap:
1532
+ message = f"{message}\n\n{FINAL_NUDGE.format(max_rounds=cap)}"
1533
+ except _StopError as stop:
1534
+ return finish(stop.reason, stop.error)
1535
+ except KeyboardInterrupt:
1536
+ cancel.set()
1537
+ return finish(StopReason.INTERRUPTED)
1538
+
1539
+
1540
+ def describe_panel_stop(result: PanelResult) -> str:
1541
+ """How the panel ended, in one sentence, for people and ``--json``'s ``outcome``."""
1542
+
1543
+ def sent(none: str) -> str:
1544
+ count = result.dispatches
1545
+ if count == 0:
1546
+ return none
1547
+ return f"after {count} message{'' if count == 1 else 's'} to the members"
1548
+
1549
+ reason = result.stop_reason
1550
+ if reason is StopReason.ANSWERED:
1551
+ when = " at the message limit" if result.answered_at_limit else ""
1552
+ asked = sent("without asking the members")
1553
+ return f"answered: the lead gave its final answer {asked}{when}"
1554
+ if reason is StopReason.ROUND_LIMIT:
1555
+ allowed = result.spec.max_rounds
1556
+ return (
1557
+ f"message limit reached ({allowed} message{'' if allowed == 1 else 's'}) "
1558
+ "and the lead gave no final answer"
1559
+ )
1560
+ detail = f": {result.error}" if result.error else ""
1561
+ before = "before the lead asked the members"
1562
+ if reason is StopReason.TIMEOUT:
1563
+ return f"stopped on the time limit {sent(before)}{detail}"
1564
+ if reason is StopReason.INTERRUPTED:
1565
+ return f"interrupted by the user {sent(before)}"
1566
+ return f"failed {sent(before)}{detail}"
1567
+
1568
+
1569
+ def render_panel_transcript(result: PanelResult) -> str:
1570
+ """The panel as markdown: roster, goal, then every committed message."""
1571
+ from comitia.discussion.converse import _fenced
1572
+
1573
+ spec = result.spec
1574
+ lead = (
1575
+ "a person"
1576
+ if spec.lead.human
1577
+ else f"{spec.lead.tool_name}{', read-only' if spec.lead.read_only else ''}, "
1578
+ f"in `{spec.lead.folder}`"
1579
+ )
1580
+ lines = ["# Panel", "", f"- Lead: {lead}"]
1581
+ for member in spec.members:
1582
+ name = f" ({member.name})" if member.name else ""
1583
+ if member.workspace is None:
1584
+ lines.append(f"- @{member.id}{name}: a person")
1585
+ continue
1586
+ folder = member.workspace.path
1587
+ kind = "persona folder" if isinstance(member.workspace, OwnedWorkspace) else "folder"
1588
+ lines.append(f"- @{member.id}{name}: {member.tool_name}, read-only, {kind} `{folder}`")
1589
+ lines += [
1590
+ f"- Visibility: {spec.visibility}",
1591
+ f"- Started: {result.started_at.isoformat(timespec='seconds')}",
1592
+ f"- Finished: {result.finished_at.isoformat(timespec='seconds')}",
1593
+ f"- Messages allowed: {spec.max_rounds}",
1594
+ f"- Outcome: {describe_panel_stop(result)}",
1595
+ "",
1596
+ "## Goal (sent only to the lead)",
1597
+ "",
1598
+ _fenced(spec.goal),
1599
+ "",
1600
+ ]
1601
+ for turn in result.turns:
1602
+ if turn.sender == "lead":
1603
+ target = "final answer" if turn.done else " ".join(f"@{r}" for r in turn.recipients)
1604
+ heading = f"## Turn {turn.number} · lead ({spec.lead.tool_name}) → {target}"
1605
+ else:
1606
+ heading = f"## Turn {turn.number} · @{turn.sender} → lead"
1607
+ lines += ["---", "", heading, "", turn.text or "(empty message)", ""]
1608
+ if result.member_failures:
1609
+ lines += ["---", "", "## Members that did not answer", ""]
1610
+ lines += [
1611
+ f"- message {dispatch}: @{member} — {reason}"
1612
+ for dispatch, member, reason in result.member_failures
1613
+ ]
1614
+ return "\n".join(lines).rstrip() + "\n"
1615
+
1616
+
1617
+ __all__ = [
1618
+ "CANCELLED",
1619
+ "FINAL_NUDGE",
1620
+ "LINE_REPAIR",
1621
+ "MAX_MEMBERS",
1622
+ "MEMBER_NOTICE",
1623
+ "MEMBER_NOTICE_VERSION",
1624
+ "PANEL_NOTICE",
1625
+ "PANEL_NOTICE_VERSION",
1626
+ "Dispatch",
1627
+ "HumanBackend",
1628
+ "HumanInput",
1629
+ "HumanReply",
1630
+ "InputRequest",
1631
+ "Lead",
1632
+ "Member",
1633
+ "PanelError",
1634
+ "PanelResult",
1635
+ "PanelSpec",
1636
+ "PanelTurn",
1637
+ "ProtocolError",
1638
+ "combine_replies",
1639
+ "describe_panel_stop",
1640
+ "member_message",
1641
+ "parse_dispatch",
1642
+ "render_member_notice",
1643
+ "render_notice",
1644
+ "render_panel_transcript",
1645
+ "result_from_journal",
1646
+ "run_panel",
1647
+ ]