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.
- comitia/__init__.py +3 -0
- comitia/__main__.py +3 -0
- comitia/api.py +68 -0
- comitia/catalog.py +82 -0
- comitia/cli.py +950 -0
- comitia/control.py +156 -0
- comitia/diffs.py +120 -0
- comitia/discussion/__init__.py +0 -0
- comitia/discussion/api.py +152 -0
- comitia/discussion/cli.py +1254 -0
- comitia/discussion/config.py +167 -0
- comitia/discussion/console.py +366 -0
- comitia/discussion/converse.py +1221 -0
- comitia/discussion/journal.py +382 -0
- comitia/discussion/panel.py +1647 -0
- comitia/discussion/panel_view.py +445 -0
- comitia/discussion/prompts/converse_asker.md +3 -0
- comitia/discussion/prompts/converse_summary.md +27 -0
- comitia/discussion/transcript.py +88 -0
- comitia/engine.py +1223 -0
- comitia/findings.py +270 -0
- comitia/host.py +2067 -0
- comitia/plan.py +957 -0
- comitia/posting.py +328 -0
- comitia/prompts.py +750 -0
- comitia/recipe.py +430 -0
- comitia/report.py +581 -0
- comitia/settings.py +66 -0
- comitia/skill/SKILL.md +75 -0
- comitia/starters/decision-debate.yml +27 -0
- comitia/starters/deep-review.yml +12 -0
- comitia/starters/message-test.yml +15 -0
- comitia/starters/pr-review-light.yml +78 -0
- comitia/starters/pr-review.yml +100 -0
- comitia/starters/prd-review.yml +10 -0
- comitia/store.py +212 -0
- comitia/web/__init__.py +13 -0
- comitia/web/server.py +244 -0
- comitia/web/service.py +679 -0
- comitia/web/static/app.js +1521 -0
- comitia/web/static/index.html +38 -0
- comitia/web/static/styles.css +262 -0
- comitia-0.1.0.dist-info/METADATA +589 -0
- comitia-0.1.0.dist-info/RECORD +48 -0
- comitia-0.1.0.dist-info/WHEEL +4 -0
- comitia-0.1.0.dist-info/entry_points.txt +2 -0
- comitia-0.1.0.dist-info/licenses/LICENSE +21 -0
- comitia-0.1.0.dist-info/licenses/LICENSES/crossby-MIT.txt +21 -0
|
@@ -0,0 +1,1221 @@
|
|
|
1
|
+
# Copied from crossby v0.71.0 (src/crossby/services/converse.py), imports aside.
|
|
2
|
+
"""Goal-driven consultations between two headless AI coding agents.
|
|
3
|
+
|
|
4
|
+
``crossby converse ASKER RESPONDER --goal ...`` lets one agent consult another.
|
|
5
|
+
The asker holds the goal: it decides what to ask, judges each answer, asks
|
|
6
|
+
follow-up questions, and decides when it has enough. The responder never sees
|
|
7
|
+
the goal; it only answers the asker's messages. ``crossby ask`` (see
|
|
8
|
+
:mod:`crossby.services.ask`) is the single-question primitive.
|
|
9
|
+
|
|
10
|
+
Each side keeps its own native session: every turn after its first resumes
|
|
11
|
+
that session and carries only the other agent's latest message, whole. Nothing
|
|
12
|
+
is replayed, budgeted or cut, so the only limit on a conversation is each
|
|
13
|
+
model's own context, which its tool manages. A CLI build whose unattended
|
|
14
|
+
resume was not verified is refused at preflight, with the build to upgrade to,
|
|
15
|
+
and a turn that reports no session to resume stops the conversation.
|
|
16
|
+
|
|
17
|
+
The responder never changes files: its turns (and ``ask`` and the summary) run
|
|
18
|
+
with the adapter's verified read-only profile, and a tool without one is
|
|
19
|
+
refused at preflight. The asker is the user's own agent and keeps its folder's
|
|
20
|
+
normal unattended policy.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
import threading
|
|
28
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
29
|
+
from dataclasses import dataclass, field
|
|
30
|
+
from datetime import UTC, datetime
|
|
31
|
+
from enum import StrEnum
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
from time import monotonic
|
|
34
|
+
from typing import TYPE_CHECKING, Any, Protocol
|
|
35
|
+
|
|
36
|
+
from crossby.ai_tools import (
|
|
37
|
+
HeadlessEvent,
|
|
38
|
+
HeadlessEventKind,
|
|
39
|
+
HeadlessInteractionMode,
|
|
40
|
+
HeadlessSessionPreflight,
|
|
41
|
+
HeadlessSessionRequest,
|
|
42
|
+
HeadlessSessionResult,
|
|
43
|
+
HeadlessTerminalStatus,
|
|
44
|
+
TokenUsage,
|
|
45
|
+
)
|
|
46
|
+
from crossby.api import AIToolID, EffortLevel
|
|
47
|
+
|
|
48
|
+
if TYPE_CHECKING:
|
|
49
|
+
from comitia.discussion.journal import ConversationEvent, Journal
|
|
50
|
+
from comitia.discussion.transcript import ConversationTranscript
|
|
51
|
+
|
|
52
|
+
DEPTH_ENV = "CROSSBY_CONVERSE_DEPTH"
|
|
53
|
+
# Agents started by ``ask``/``converse`` may not start another one: the depth
|
|
54
|
+
# counter is inherited by child processes, so this stops agents from consulting
|
|
55
|
+
# each other in an unbounded chain.
|
|
56
|
+
MAX_DEPTH = 1
|
|
57
|
+
|
|
58
|
+
DEFAULT_MAX_ROUNDS = 5
|
|
59
|
+
DEFAULT_TIMEOUT_SECONDS = 1800.0
|
|
60
|
+
DEFAULT_TURN_TIMEOUT_SECONDS = 600.0
|
|
61
|
+
DEFAULT_SUMMARY_TIMEOUT_SECONDS = 300.0
|
|
62
|
+
PREFLIGHT_TIMEOUT_SECONDS = 20.0
|
|
63
|
+
# A turn needs a realistic minimum to start a native CLI and answer; with less
|
|
64
|
+
# than this left on the overall deadline the conversation stops as timed out.
|
|
65
|
+
MIN_TURN_SECONDS = 5.0
|
|
66
|
+
# Preflight validates each side as the resumed session every turn after its
|
|
67
|
+
# first will be: the adapter then refuses a build whose resume is unverified.
|
|
68
|
+
# Only the ID's shape is checked (some tools require a UUID); nothing is opened.
|
|
69
|
+
PREFLIGHT_RESUME_ID = "00000000-0000-4000-8000-000000000000"
|
|
70
|
+
|
|
71
|
+
ASKER_PROMPT_FILE = "converse_asker.md"
|
|
72
|
+
SUMMARY_PROMPT_FILE = "converse_summary.md"
|
|
73
|
+
|
|
74
|
+
FINAL_NUDGE = (
|
|
75
|
+
"You have used all {max_rounds} messages. Write your final answer now and end "
|
|
76
|
+
"with the line `NEXT: DONE`."
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class ConverseError(RuntimeError):
|
|
81
|
+
"""A consultation request is invalid before any agent is started."""
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class ConverseDepthError(ConverseError):
|
|
85
|
+
"""``ask``/``converse`` was invoked from inside another consultation."""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ConverseSummaryError(RuntimeError):
|
|
89
|
+
"""The summary session failed; the transcript is unaffected."""
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Role(StrEnum):
|
|
93
|
+
ASKER = "asker"
|
|
94
|
+
RESPONDER = "responder"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class Next(StrEnum):
|
|
98
|
+
"""What the asker's reply is: a message to send, or its final answer."""
|
|
99
|
+
|
|
100
|
+
ASK = "ASK"
|
|
101
|
+
DONE = "DONE"
|
|
102
|
+
MISSING = "MISSING"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class StopReason(StrEnum):
|
|
106
|
+
"""Why a consultation ended."""
|
|
107
|
+
|
|
108
|
+
ANSWERED = "answered"
|
|
109
|
+
ROUND_LIMIT = "round_limit"
|
|
110
|
+
TIMEOUT = "timeout"
|
|
111
|
+
FAILED = "failed"
|
|
112
|
+
INTERRUPTED = "interrupted"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
EXIT_CODES: dict[StopReason, int] = {
|
|
116
|
+
StopReason.ANSWERED: 0,
|
|
117
|
+
StopReason.FAILED: 1,
|
|
118
|
+
StopReason.ROUND_LIMIT: 2,
|
|
119
|
+
StopReason.TIMEOUT: 2,
|
|
120
|
+
StopReason.INTERRUPTED: 130,
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True)
|
|
125
|
+
class Participant:
|
|
126
|
+
"""One side of a consultation."""
|
|
127
|
+
|
|
128
|
+
tool: AIToolID
|
|
129
|
+
role: Role
|
|
130
|
+
model: str | None = None
|
|
131
|
+
effort: EffortLevel | None = None
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def label(self) -> str:
|
|
135
|
+
return f"{self.role.value} ({self.tool.value})"
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
def settings(self) -> str:
|
|
139
|
+
"""``claude-opus-5-5, high effort``: the model and effort asked for, if any."""
|
|
140
|
+
parts = [self.model] if self.model else []
|
|
141
|
+
if self.effort is not None:
|
|
142
|
+
parts.append(f"{self.effort.value} effort")
|
|
143
|
+
return ", ".join(parts)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@dataclass(frozen=True)
|
|
147
|
+
class ConverseTurn:
|
|
148
|
+
"""One relayed message."""
|
|
149
|
+
|
|
150
|
+
number: int
|
|
151
|
+
role: Role
|
|
152
|
+
tool: AIToolID
|
|
153
|
+
text: str
|
|
154
|
+
next: Next | None
|
|
155
|
+
duration_seconds: float
|
|
156
|
+
# What the tool reported denying during this turn (bounded, count-only
|
|
157
|
+
# diagnostics from the adapter, never the denied input).
|
|
158
|
+
denials: tuple[str, ...] = ()
|
|
159
|
+
# Tokens as the tool reported them for this turn, when it did.
|
|
160
|
+
usage: TokenUsage | None = None
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def is_final_answer(self) -> bool:
|
|
164
|
+
return self.role is Role.ASKER and self.next is Next.DONE
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@dataclass
|
|
168
|
+
class ConversationResult:
|
|
169
|
+
"""The full outcome of a consultation, including partial progress."""
|
|
170
|
+
|
|
171
|
+
goal: str
|
|
172
|
+
asker: Participant
|
|
173
|
+
responder: Participant
|
|
174
|
+
max_rounds: int
|
|
175
|
+
started_at: datetime
|
|
176
|
+
finished_at: datetime
|
|
177
|
+
stop_reason: StopReason
|
|
178
|
+
turns: list[ConverseTurn] = field(default_factory=list)
|
|
179
|
+
error: str | None = None
|
|
180
|
+
answered_at_limit: bool = False
|
|
181
|
+
# Each side's native session (``None`` until its first turn reported one).
|
|
182
|
+
sessions: dict[Role, str | None] = field(default_factory=dict)
|
|
183
|
+
# The folder each side ran in.
|
|
184
|
+
folders: dict[Role, Path] = field(default_factory=dict)
|
|
185
|
+
|
|
186
|
+
@property
|
|
187
|
+
def answered(self) -> bool:
|
|
188
|
+
return self.stop_reason is StopReason.ANSWERED
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def final_answer(self) -> str | None:
|
|
192
|
+
last = self.turns[-1] if self.turns else None
|
|
193
|
+
return last.text if last is not None and last.is_final_answer else None
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
def rounds(self) -> int:
|
|
197
|
+
"""Answers the responder gave."""
|
|
198
|
+
return sum(1 for turn in self.turns if turn.role is Role.RESPONDER)
|
|
199
|
+
|
|
200
|
+
@property
|
|
201
|
+
def exit_code(self) -> int:
|
|
202
|
+
return EXIT_CODES[self.stop_reason]
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class TurnRunner(Protocol):
|
|
206
|
+
"""Runs managed headless sessions; injectable so tests need no real CLIs."""
|
|
207
|
+
|
|
208
|
+
def preflight(
|
|
209
|
+
self, tool: AIToolID, request: HeadlessSessionRequest
|
|
210
|
+
) -> HeadlessSessionPreflight | None: ...
|
|
211
|
+
|
|
212
|
+
def run(
|
|
213
|
+
self,
|
|
214
|
+
tool: AIToolID,
|
|
215
|
+
request: HeadlessSessionRequest,
|
|
216
|
+
cancel_event: threading.Event,
|
|
217
|
+
on_event: Callable[[HeadlessEvent], None] | None = None,
|
|
218
|
+
) -> HeadlessSessionResult: ...
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class HeadlessTurnRunner:
|
|
222
|
+
"""Default runner backed by each adapter's managed headless session."""
|
|
223
|
+
|
|
224
|
+
def preflight(
|
|
225
|
+
self, tool: AIToolID, request: HeadlessSessionRequest
|
|
226
|
+
) -> HeadlessSessionPreflight | None:
|
|
227
|
+
from crossby.ai_tools import preflight_headless_session
|
|
228
|
+
|
|
229
|
+
return preflight_headless_session(tool, request, timeout_seconds=PREFLIGHT_TIMEOUT_SECONDS)
|
|
230
|
+
|
|
231
|
+
def run(
|
|
232
|
+
self,
|
|
233
|
+
tool: AIToolID,
|
|
234
|
+
request: HeadlessSessionRequest,
|
|
235
|
+
cancel_event: threading.Event,
|
|
236
|
+
on_event: Callable[[HeadlessEvent], None] | None = None,
|
|
237
|
+
) -> HeadlessSessionResult:
|
|
238
|
+
"""Run one session in a worker so Ctrl-C cancels it cleanly."""
|
|
239
|
+
from crossby.api import run_cancellable
|
|
240
|
+
|
|
241
|
+
return run_cancellable(tool, request, cancel_event, event_handler=on_event)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
# ---------------------------------------------------------------------------
|
|
245
|
+
# Recursion guard
|
|
246
|
+
# ---------------------------------------------------------------------------
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def current_depth() -> int:
|
|
250
|
+
raw = os.environ.get(DEPTH_ENV, "").strip()
|
|
251
|
+
try:
|
|
252
|
+
return max(int(raw), 0) if raw else 0
|
|
253
|
+
except ValueError:
|
|
254
|
+
return 0
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def check_depth() -> None:
|
|
258
|
+
"""Refuse to start agents from inside an agent that crossby started."""
|
|
259
|
+
if current_depth() >= MAX_DEPTH:
|
|
260
|
+
raise ConverseDepthError(
|
|
261
|
+
"crossby ask/converse was called from an agent that crossby itself started "
|
|
262
|
+
f"({DEPTH_ENV}={current_depth()}). Nested consultations are disabled to "
|
|
263
|
+
"prevent agents from calling each other in a loop."
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def child_environment() -> dict[str, str]:
|
|
268
|
+
"""The variables that mark an agent crossby starts as one level deeper.
|
|
269
|
+
|
|
270
|
+
They travel in each session request, so only that agent's process gets
|
|
271
|
+
them: the caller's own environment never changes, and concurrent
|
|
272
|
+
consultations in one process cannot see or undo each other's.
|
|
273
|
+
"""
|
|
274
|
+
return {DEPTH_ENV: str(current_depth() + 1)}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# ---------------------------------------------------------------------------
|
|
278
|
+
# Capabilities, prompts and parsing
|
|
279
|
+
# ---------------------------------------------------------------------------
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def make_participants(
|
|
283
|
+
asker: AIToolID,
|
|
284
|
+
responder: AIToolID,
|
|
285
|
+
*,
|
|
286
|
+
asker_model: str | None = None,
|
|
287
|
+
responder_model: str | None = None,
|
|
288
|
+
asker_effort: EffortLevel | None = None,
|
|
289
|
+
responder_effort: EffortLevel | None = None,
|
|
290
|
+
) -> tuple[Participant, Participant]:
|
|
291
|
+
return (
|
|
292
|
+
Participant(tool=asker, role=Role.ASKER, model=asker_model, effort=asker_effort),
|
|
293
|
+
Participant(
|
|
294
|
+
tool=responder, role=Role.RESPONDER, model=responder_model, effort=responder_effort
|
|
295
|
+
),
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
_NEXT_LINE = re.compile(
|
|
300
|
+
r"^[\s*_`>#-]*next\s*:\s*[*_`]*\s*(ask|done)\b[\s*_`.!]*$",
|
|
301
|
+
re.IGNORECASE,
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def parse_next(text: str) -> tuple[str, Next]:
|
|
306
|
+
"""Split an asker reply into ``(body, next)``.
|
|
307
|
+
|
|
308
|
+
The marker must be the last non-empty line; markdown decoration such as
|
|
309
|
+
``**NEXT: DONE**`` is tolerated. A reply without one is ``MISSING`` and is
|
|
310
|
+
sent on as a message, never taken as a final answer.
|
|
311
|
+
"""
|
|
312
|
+
lines = text.rstrip().splitlines()
|
|
313
|
+
for index in range(len(lines) - 1, -1, -1):
|
|
314
|
+
if lines[index].strip():
|
|
315
|
+
match = _NEXT_LINE.match(lines[index])
|
|
316
|
+
if match is None:
|
|
317
|
+
return text.strip(), Next.MISSING
|
|
318
|
+
return "\n".join(lines[:index]).strip(), Next(match.group(1).upper())
|
|
319
|
+
return "", Next.MISSING
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _load(filename: str) -> str:
|
|
323
|
+
from importlib.resources import files
|
|
324
|
+
|
|
325
|
+
return (files("comitia.discussion") / "prompts" / filename).read_text(encoding="utf-8")
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def asker_opening(*, goal: str, responder: Participant, max_rounds: int) -> str:
|
|
329
|
+
return (
|
|
330
|
+
_load(ASKER_PROMPT_FILE)
|
|
331
|
+
.format(goal=goal, responder=responder.tool.value, max_rounds=max_rounds)
|
|
332
|
+
.strip()
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def reply_for_asker(reply: str, *, final: bool, max_rounds: int) -> str:
|
|
337
|
+
"""What the asker receives: the responder's answer as is.
|
|
338
|
+
|
|
339
|
+
Only after the last allowed message is one line added, asking for the
|
|
340
|
+
final answer.
|
|
341
|
+
"""
|
|
342
|
+
if not final:
|
|
343
|
+
return reply
|
|
344
|
+
return f"{reply}\n\n{FINAL_NUDGE.format(max_rounds=max_rounds)}"
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _request(
|
|
348
|
+
participant: Participant | None,
|
|
349
|
+
*,
|
|
350
|
+
prompt: str,
|
|
351
|
+
working_dir: Path,
|
|
352
|
+
timeout_seconds: float,
|
|
353
|
+
model: str | None = None,
|
|
354
|
+
effort: EffortLevel | None = None,
|
|
355
|
+
resume_id: str | None = None,
|
|
356
|
+
read_only: bool = False,
|
|
357
|
+
allow_project_hooks: bool = False,
|
|
358
|
+
) -> HeadlessSessionRequest:
|
|
359
|
+
return HeadlessSessionRequest(
|
|
360
|
+
prompt=prompt,
|
|
361
|
+
working_dir=working_dir,
|
|
362
|
+
model=participant.model if participant is not None else model,
|
|
363
|
+
effort=participant.effort if participant is not None else effort,
|
|
364
|
+
interaction_mode=HeadlessInteractionMode.UNATTENDED,
|
|
365
|
+
timeout_seconds=timeout_seconds,
|
|
366
|
+
resume_id=resume_id,
|
|
367
|
+
read_only=read_only,
|
|
368
|
+
allow_project_hooks=allow_project_hooks,
|
|
369
|
+
environment=child_environment(),
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _read_only(participant: Participant) -> bool:
|
|
374
|
+
"""A responder never changes files: its sessions run read-only.
|
|
375
|
+
|
|
376
|
+
The asker is the user's own agent in the user's project, so it keeps the
|
|
377
|
+
folder's normal unattended policy.
|
|
378
|
+
"""
|
|
379
|
+
return participant.role is Role.RESPONDER
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _status(result: HeadlessSessionResult) -> str:
|
|
383
|
+
"""``failed``, plus the recognized reason and the tool's own status.
|
|
384
|
+
|
|
385
|
+
For example ``failed: not signed in (native: api_error)``; see
|
|
386
|
+
:func:`crossby.services.ask.describe_session_status`.
|
|
387
|
+
"""
|
|
388
|
+
from crossby.api import describe_session_status
|
|
389
|
+
|
|
390
|
+
return describe_session_status(result)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _session_handle(result: HeadlessSessionResult) -> str | None:
|
|
394
|
+
return result.session_id or result.thread_id or result.conversation_id
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
# ---------------------------------------------------------------------------
|
|
398
|
+
# converse
|
|
399
|
+
# ---------------------------------------------------------------------------
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
class _StopError(Exception):
|
|
403
|
+
def __init__(self, reason: StopReason, error: str | None = None) -> None:
|
|
404
|
+
super().__init__(error)
|
|
405
|
+
self.reason = reason
|
|
406
|
+
self.error = error
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
@dataclass
|
|
410
|
+
class _Side:
|
|
411
|
+
participant: Participant
|
|
412
|
+
session_id: str | None = None
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
@dataclass(frozen=True)
|
|
416
|
+
class _Reply:
|
|
417
|
+
"""What one turn produced, before the asker's marker is parsed."""
|
|
418
|
+
|
|
419
|
+
text: str
|
|
420
|
+
duration: float
|
|
421
|
+
denials: tuple[str, ...]
|
|
422
|
+
usage: TokenUsage | None = None
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
# Runtime event kinds forwarded as ``turn.progress``; each names only the kind
|
|
426
|
+
# of step a tool took, never its content.
|
|
427
|
+
_PROGRESS_KINDS = {
|
|
428
|
+
HeadlessEventKind.TOOL_STARTED: "tool_started",
|
|
429
|
+
HeadlessEventKind.TOOL_COMPLETED: "tool_completed",
|
|
430
|
+
HeadlessEventKind.ASSISTANT_MESSAGE: "assistant_message",
|
|
431
|
+
HeadlessEventKind.PROGRESS: "progress",
|
|
432
|
+
}
|
|
433
|
+
# At most one generic "progress" event per second per turn: streaming tools
|
|
434
|
+
# emit one per native frame.
|
|
435
|
+
_PROGRESS_INTERVAL_SECONDS = 1.0
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _usage_data(usage: TokenUsage | None) -> dict[str, Any] | None:
|
|
439
|
+
if usage is None:
|
|
440
|
+
return None
|
|
441
|
+
data = usage.model_dump(
|
|
442
|
+
include={
|
|
443
|
+
"input_tokens",
|
|
444
|
+
"output_tokens",
|
|
445
|
+
"cached_tokens",
|
|
446
|
+
"total_tokens",
|
|
447
|
+
"premium_requests",
|
|
448
|
+
"reported_cost_usd",
|
|
449
|
+
"tool_steps",
|
|
450
|
+
},
|
|
451
|
+
exclude_none=True,
|
|
452
|
+
)
|
|
453
|
+
return data or None
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def run_conversation(
|
|
457
|
+
goal: str,
|
|
458
|
+
participants: tuple[Participant, Participant],
|
|
459
|
+
*,
|
|
460
|
+
working_dir: Path,
|
|
461
|
+
responder_dir: Path | None = None,
|
|
462
|
+
max_rounds: int = DEFAULT_MAX_ROUNDS,
|
|
463
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
464
|
+
turn_timeout_seconds: float = DEFAULT_TURN_TIMEOUT_SECONDS,
|
|
465
|
+
runner: TurnRunner | None = None,
|
|
466
|
+
on_turn_start: Callable[[int, Participant], None] | None = None,
|
|
467
|
+
on_turn: Callable[[ConverseTurn], None] | None = None,
|
|
468
|
+
clock: Callable[[], float] = monotonic,
|
|
469
|
+
allow_project_hooks: bool = False,
|
|
470
|
+
journal: Journal | None = None,
|
|
471
|
+
resume: ConversationResult | None = None,
|
|
472
|
+
) -> ConversationResult:
|
|
473
|
+
"""Let the asker consult the responder until it gives a final answer.
|
|
474
|
+
|
|
475
|
+
The asker runs in ``working_dir`` and the responder in ``responder_dir``
|
|
476
|
+
(default: the same folder), each with that folder's own files and setup.
|
|
477
|
+
|
|
478
|
+
The asker holds the goal and ends every reply with ``NEXT: ASK`` (send it
|
|
479
|
+
to the responder) or ``NEXT: DONE`` (its final answer). After the last
|
|
480
|
+
allowed round the asker is told to answer now; a limit, a failure or Ctrl-C
|
|
481
|
+
always returns the turns completed so far.
|
|
482
|
+
|
|
483
|
+
``journal`` receives every event as it happens (see
|
|
484
|
+
:mod:`crossby.services.journal`). ``resume`` continues a consultation that
|
|
485
|
+
stopped without an answer: both sides resume their own sessions, the next
|
|
486
|
+
side gets the message it was owed, and up to ``max_rounds`` more answers
|
|
487
|
+
are allowed.
|
|
488
|
+
"""
|
|
489
|
+
from crossby.ai_tools import HeadlessSessionError
|
|
490
|
+
|
|
491
|
+
from comitia.discussion.journal import EventType
|
|
492
|
+
|
|
493
|
+
check_depth()
|
|
494
|
+
if not goal.strip():
|
|
495
|
+
raise ConverseError("The goal is empty.")
|
|
496
|
+
if max_rounds < 1:
|
|
497
|
+
raise ConverseError("--max-rounds must be at least 1.")
|
|
498
|
+
if timeout_seconds <= 0 or turn_timeout_seconds <= 0:
|
|
499
|
+
raise ConverseError("Timeouts must be positive.")
|
|
500
|
+
asker, responder = participants
|
|
501
|
+
if asker.role is not Role.ASKER or responder.role is not Role.RESPONDER:
|
|
502
|
+
raise ConverseError("Participants must be (asker, responder).")
|
|
503
|
+
if resume is not None and (
|
|
504
|
+
resume.answered or (resume.turns and resume.turns[-1].is_final_answer)
|
|
505
|
+
):
|
|
506
|
+
raise ConverseError("That consultation already has its final answer.")
|
|
507
|
+
|
|
508
|
+
active_runner: TurnRunner = runner or HeadlessTurnRunner()
|
|
509
|
+
folders = {Role.ASKER: working_dir, Role.RESPONDER: responder_dir or working_dir}
|
|
510
|
+
started_at = resume.started_at if resume is not None else datetime.now(tz=UTC)
|
|
511
|
+
deadline = clock() + timeout_seconds
|
|
512
|
+
turns: list[ConverseTurn] = list(resume.turns) if resume is not None else []
|
|
513
|
+
sides = {Role.ASKER: _Side(asker), Role.RESPONDER: _Side(responder)}
|
|
514
|
+
if resume is not None:
|
|
515
|
+
for role, side in sides.items():
|
|
516
|
+
side.session_id = resume.sessions.get(role)
|
|
517
|
+
answers = sum(1 for turn in turns if turn.role is Role.RESPONDER)
|
|
518
|
+
# Answers allowed in all: the ones already given plus this run's.
|
|
519
|
+
cap = answers + max_rounds
|
|
520
|
+
opening = asker_opening(goal=goal, responder=responder, max_rounds=max_rounds)
|
|
521
|
+
in_progress: int | None = None
|
|
522
|
+
answered_at_limit = False
|
|
523
|
+
|
|
524
|
+
def emit(type_: EventType, **data: Any) -> None:
|
|
525
|
+
if journal is not None:
|
|
526
|
+
journal.emit(type_, **data)
|
|
527
|
+
|
|
528
|
+
def side_data(participant: Participant) -> dict[str, Any]:
|
|
529
|
+
return {
|
|
530
|
+
"role": participant.role.value,
|
|
531
|
+
"tool": participant.tool.value,
|
|
532
|
+
"model": participant.model,
|
|
533
|
+
"effort": participant.effort.value if participant.effort is not None else None,
|
|
534
|
+
"folder": str(folders[participant.role]),
|
|
535
|
+
"read_only": _read_only(participant),
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
if resume is None:
|
|
539
|
+
emit(
|
|
540
|
+
EventType.CONVERSATION_STARTED,
|
|
541
|
+
goal=goal,
|
|
542
|
+
participants=[side_data(asker), side_data(responder)],
|
|
543
|
+
max_rounds=cap,
|
|
544
|
+
timeout_seconds=timeout_seconds,
|
|
545
|
+
turn_timeout_seconds=turn_timeout_seconds,
|
|
546
|
+
started_at=started_at.isoformat(),
|
|
547
|
+
)
|
|
548
|
+
else:
|
|
549
|
+
emit(
|
|
550
|
+
EventType.CONVERSATION_CONTINUED,
|
|
551
|
+
previous_stop_reason=resume.stop_reason.value,
|
|
552
|
+
max_rounds=cap,
|
|
553
|
+
added_rounds=max_rounds,
|
|
554
|
+
timeout_seconds=timeout_seconds,
|
|
555
|
+
turn_timeout_seconds=turn_timeout_seconds,
|
|
556
|
+
)
|
|
557
|
+
|
|
558
|
+
def finish(reason: StopReason, error: str | None = None) -> ConversationResult:
|
|
559
|
+
result = ConversationResult(
|
|
560
|
+
goal=goal,
|
|
561
|
+
asker=asker,
|
|
562
|
+
responder=responder,
|
|
563
|
+
max_rounds=cap,
|
|
564
|
+
started_at=started_at,
|
|
565
|
+
finished_at=datetime.now(tz=UTC),
|
|
566
|
+
stop_reason=reason,
|
|
567
|
+
turns=turns,
|
|
568
|
+
error=error,
|
|
569
|
+
answered_at_limit=answered_at_limit,
|
|
570
|
+
sessions={role: side.session_id for role, side in sides.items()},
|
|
571
|
+
folders=dict(folders),
|
|
572
|
+
)
|
|
573
|
+
emit(
|
|
574
|
+
EventType.CONVERSATION_FINISHED,
|
|
575
|
+
stop_reason=reason.value,
|
|
576
|
+
error=error,
|
|
577
|
+
answered_at_limit=answered_at_limit,
|
|
578
|
+
rounds=result.rounds,
|
|
579
|
+
sessions={role.value: session for role, session in result.sessions.items()},
|
|
580
|
+
finished_at=result.finished_at.isoformat(),
|
|
581
|
+
)
|
|
582
|
+
return result
|
|
583
|
+
|
|
584
|
+
def out_of_time(when: str) -> _StopError:
|
|
585
|
+
return _StopError(
|
|
586
|
+
StopReason.TIMEOUT, f"conversation time limit of {timeout_seconds:g}s reached {when}"
|
|
587
|
+
)
|
|
588
|
+
|
|
589
|
+
def progress_handler(number: int) -> Callable[[HeadlessEvent], None]:
|
|
590
|
+
last_progress = [float("-inf")]
|
|
591
|
+
|
|
592
|
+
def handle(event: HeadlessEvent) -> None:
|
|
593
|
+
kind = _PROGRESS_KINDS.get(event.kind)
|
|
594
|
+
if kind is None:
|
|
595
|
+
return
|
|
596
|
+
if event.kind is HeadlessEventKind.PROGRESS:
|
|
597
|
+
if event.elapsed_seconds - last_progress[0] < _PROGRESS_INTERVAL_SECONDS:
|
|
598
|
+
return
|
|
599
|
+
last_progress[0] = event.elapsed_seconds
|
|
600
|
+
emit(
|
|
601
|
+
EventType.TURN_PROGRESS,
|
|
602
|
+
turn=number,
|
|
603
|
+
kind=kind,
|
|
604
|
+
elapsed_seconds=round(event.elapsed_seconds, 3),
|
|
605
|
+
)
|
|
606
|
+
|
|
607
|
+
return handle
|
|
608
|
+
|
|
609
|
+
def turn_finished(
|
|
610
|
+
number: int,
|
|
611
|
+
role: Role,
|
|
612
|
+
result: HeadlessSessionResult | None,
|
|
613
|
+
*,
|
|
614
|
+
status: str,
|
|
615
|
+
duration: float,
|
|
616
|
+
error: str | None = None,
|
|
617
|
+
) -> None:
|
|
618
|
+
emit(
|
|
619
|
+
EventType.TURN_FINISHED,
|
|
620
|
+
turn=number,
|
|
621
|
+
role=role.value,
|
|
622
|
+
tool=sides[role].participant.tool.value,
|
|
623
|
+
status=status,
|
|
624
|
+
duration_seconds=round(duration, 3),
|
|
625
|
+
session_id=(_session_handle(result) if result is not None else None)
|
|
626
|
+
or sides[role].session_id,
|
|
627
|
+
usage=_usage_data(result.usage) if result is not None else None,
|
|
628
|
+
denials=list(result.denials) if result is not None else [],
|
|
629
|
+
failure_reason=(
|
|
630
|
+
result.failure_reason.value
|
|
631
|
+
if result is not None and result.failure_reason is not None
|
|
632
|
+
else None
|
|
633
|
+
),
|
|
634
|
+
error=error,
|
|
635
|
+
)
|
|
636
|
+
|
|
637
|
+
def take_turn(role: Role, message: str) -> _Reply:
|
|
638
|
+
"""Run one turn for ``role`` and return its reply.
|
|
639
|
+
|
|
640
|
+
The prompt is the message itself, whole: the session holds everything
|
|
641
|
+
said before. Only the asker's very first turn sends its opening.
|
|
642
|
+
"""
|
|
643
|
+
nonlocal in_progress
|
|
644
|
+
side = sides[role]
|
|
645
|
+
number = len(turns) + 1
|
|
646
|
+
remaining = deadline - clock()
|
|
647
|
+
if remaining < MIN_TURN_SECONDS:
|
|
648
|
+
raise out_of_time(f"before turn {number}")
|
|
649
|
+
bounded_by_deadline = remaining <= turn_timeout_seconds
|
|
650
|
+
request = _request(
|
|
651
|
+
side.participant,
|
|
652
|
+
prompt=message if turns else opening,
|
|
653
|
+
working_dir=folders[role],
|
|
654
|
+
timeout_seconds=min(turn_timeout_seconds, remaining),
|
|
655
|
+
resume_id=side.session_id,
|
|
656
|
+
read_only=_read_only(side.participant),
|
|
657
|
+
allow_project_hooks=allow_project_hooks,
|
|
658
|
+
)
|
|
659
|
+
in_progress = number
|
|
660
|
+
emit(
|
|
661
|
+
EventType.TURN_STARTED,
|
|
662
|
+
turn=number,
|
|
663
|
+
role=role.value,
|
|
664
|
+
tool=side.participant.tool.value,
|
|
665
|
+
resumed=side.session_id is not None,
|
|
666
|
+
session_id=side.session_id,
|
|
667
|
+
)
|
|
668
|
+
if on_turn_start is not None:
|
|
669
|
+
on_turn_start(number, side.participant)
|
|
670
|
+
turn_started = clock()
|
|
671
|
+
label = side.participant.label
|
|
672
|
+
|
|
673
|
+
def stop(reason: StopReason, error: str, result: HeadlessSessionResult | None) -> None:
|
|
674
|
+
status = result.status.value if result is not None else "failed"
|
|
675
|
+
turn_finished(
|
|
676
|
+
number, role, result, status=status, duration=clock() - turn_started, error=error
|
|
677
|
+
)
|
|
678
|
+
raise _StopError(reason, error)
|
|
679
|
+
|
|
680
|
+
try:
|
|
681
|
+
result = active_runner.run(
|
|
682
|
+
side.participant.tool, request, cancel_event, on_event=progress_handler(number)
|
|
683
|
+
)
|
|
684
|
+
except HeadlessSessionError as exc:
|
|
685
|
+
# The runtime re-probes the version before it starts and raises
|
|
686
|
+
# (rather than returning TIMED_OUT) when the deadline runs out there.
|
|
687
|
+
if clock() >= deadline:
|
|
688
|
+
timeout = out_of_time(f"during turn {number}")
|
|
689
|
+
stop(timeout.reason, timeout.error or "", None)
|
|
690
|
+
stop(StopReason.FAILED, f"{label} turn {number}: {exc}", None)
|
|
691
|
+
raise AssertionError("unreachable") from None # pragma: no cover
|
|
692
|
+
if result.status is HeadlessTerminalStatus.TIMED_OUT:
|
|
693
|
+
if bounded_by_deadline:
|
|
694
|
+
timeout = out_of_time(f"during turn {number}")
|
|
695
|
+
stop(timeout.reason, timeout.error or "", result)
|
|
696
|
+
stop(
|
|
697
|
+
StopReason.FAILED,
|
|
698
|
+
f"{label} turn {number} timed out after {turn_timeout_seconds:g}s",
|
|
699
|
+
result,
|
|
700
|
+
)
|
|
701
|
+
# A tool that denied an action may end its turn without an answer
|
|
702
|
+
# (Antigravity CLI does); name the denials so the failure explains itself.
|
|
703
|
+
denied = f" ({'; '.join(result.denials)})" if result.denials else ""
|
|
704
|
+
if result.status is not HeadlessTerminalStatus.SUCCEEDED:
|
|
705
|
+
stop(
|
|
706
|
+
StopReason.FAILED,
|
|
707
|
+
f"{label} turn {number} ended with status {_status(result)}{denied}",
|
|
708
|
+
result,
|
|
709
|
+
)
|
|
710
|
+
text = (result.final_text or "").strip()
|
|
711
|
+
if not text:
|
|
712
|
+
stop(StopReason.FAILED, f"{label} turn {number} returned no text{denied}", result)
|
|
713
|
+
if side.session_id is None:
|
|
714
|
+
handle = _session_handle(result)
|
|
715
|
+
if handle is None:
|
|
716
|
+
# Its next turn could only start over without the conversation.
|
|
717
|
+
stop(
|
|
718
|
+
StopReason.FAILED,
|
|
719
|
+
f"{label} turn {number}: {side.participant.tool.value} reported no "
|
|
720
|
+
"session to resume, so the conversation cannot continue",
|
|
721
|
+
result,
|
|
722
|
+
)
|
|
723
|
+
side.session_id = handle
|
|
724
|
+
duration = clock() - turn_started
|
|
725
|
+
turn_finished(number, role, result, status=result.status.value, duration=duration)
|
|
726
|
+
return _Reply(text, duration, tuple(result.denials), result.usage)
|
|
727
|
+
|
|
728
|
+
def record(role: Role, reply: _Reply, body: str, next_: Next | None) -> ConverseTurn:
|
|
729
|
+
nonlocal in_progress
|
|
730
|
+
turn = ConverseTurn(
|
|
731
|
+
number=len(turns) + 1,
|
|
732
|
+
role=role,
|
|
733
|
+
tool=sides[role].participant.tool,
|
|
734
|
+
text=body,
|
|
735
|
+
next=next_,
|
|
736
|
+
duration_seconds=reply.duration,
|
|
737
|
+
denials=reply.denials,
|
|
738
|
+
usage=reply.usage,
|
|
739
|
+
)
|
|
740
|
+
turns.append(turn)
|
|
741
|
+
in_progress = None
|
|
742
|
+
emit(
|
|
743
|
+
EventType.MESSAGE_COMMITTED,
|
|
744
|
+
turn=turn.number,
|
|
745
|
+
role=role.value,
|
|
746
|
+
tool=turn.tool.value,
|
|
747
|
+
text=body,
|
|
748
|
+
next=next_.value if next_ is not None else None,
|
|
749
|
+
duration_seconds=round(reply.duration, 3),
|
|
750
|
+
denials=list(reply.denials),
|
|
751
|
+
usage=_usage_data(reply.usage),
|
|
752
|
+
)
|
|
753
|
+
if on_turn is not None:
|
|
754
|
+
on_turn(turn)
|
|
755
|
+
return turn
|
|
756
|
+
|
|
757
|
+
def preflight() -> None:
|
|
758
|
+
for participant in dict.fromkeys(participants):
|
|
759
|
+
remaining = deadline - clock()
|
|
760
|
+
if remaining < MIN_TURN_SECONDS:
|
|
761
|
+
raise out_of_time("during preflight")
|
|
762
|
+
probe = _request(
|
|
763
|
+
participant,
|
|
764
|
+
prompt="preflight",
|
|
765
|
+
working_dir=folders[participant.role],
|
|
766
|
+
timeout_seconds=min(turn_timeout_seconds, remaining),
|
|
767
|
+
resume_id=PREFLIGHT_RESUME_ID,
|
|
768
|
+
read_only=_read_only(participant),
|
|
769
|
+
allow_project_hooks=allow_project_hooks,
|
|
770
|
+
)
|
|
771
|
+
try:
|
|
772
|
+
report = active_runner.preflight(participant.tool, probe)
|
|
773
|
+
except HeadlessSessionError as exc:
|
|
774
|
+
if clock() >= deadline:
|
|
775
|
+
raise out_of_time("during preflight") from None
|
|
776
|
+
raise _StopError(
|
|
777
|
+
StopReason.FAILED, f"{participant.label} cannot run headless: {exc}"
|
|
778
|
+
) from None
|
|
779
|
+
emit(
|
|
780
|
+
EventType.PARTICIPANT_READY,
|
|
781
|
+
**side_data(participant),
|
|
782
|
+
version=report.detected_version if report is not None else None,
|
|
783
|
+
restrictions=(
|
|
784
|
+
{item.channel.value: item.state.value for item in report.restrictions}
|
|
785
|
+
if report is not None
|
|
786
|
+
else {}
|
|
787
|
+
),
|
|
788
|
+
warnings=list(report.warnings) if report is not None else [],
|
|
789
|
+
)
|
|
790
|
+
|
|
791
|
+
def relay() -> ConversationResult:
|
|
792
|
+
nonlocal answered_at_limit, answers
|
|
793
|
+
preflight()
|
|
794
|
+
# Whose turn it is, and the message it is owed.
|
|
795
|
+
if turns and turns[-1].role is Role.RESPONDER:
|
|
796
|
+
next_role = Role.ASKER
|
|
797
|
+
message = reply_for_asker(turns[-1].text, final=answers >= cap, max_rounds=cap)
|
|
798
|
+
elif turns:
|
|
799
|
+
next_role, message = Role.RESPONDER, turns[-1].text
|
|
800
|
+
else:
|
|
801
|
+
next_role, message = Role.ASKER, "" # the first turn sends the opening
|
|
802
|
+
while True:
|
|
803
|
+
if next_role is Role.ASKER:
|
|
804
|
+
final = answers >= cap
|
|
805
|
+
asked = take_turn(Role.ASKER, message)
|
|
806
|
+
body, next_ = parse_next(asked.text)
|
|
807
|
+
if not body:
|
|
808
|
+
# A bare marker is neither an answer nor a message to send.
|
|
809
|
+
what = "final answer" if next_ is Next.DONE else "message"
|
|
810
|
+
raise _StopError(
|
|
811
|
+
StopReason.FAILED,
|
|
812
|
+
f"{asker.label} turn {len(turns) + 1} sent only the NEXT marker, "
|
|
813
|
+
f"with no {what}",
|
|
814
|
+
)
|
|
815
|
+
record(Role.ASKER, asked, body, next_)
|
|
816
|
+
if next_ is Next.DONE:
|
|
817
|
+
answered_at_limit = final
|
|
818
|
+
return finish(StopReason.ANSWERED)
|
|
819
|
+
if final:
|
|
820
|
+
return finish(StopReason.ROUND_LIMIT)
|
|
821
|
+
next_role, message = Role.RESPONDER, body
|
|
822
|
+
else:
|
|
823
|
+
answer = take_turn(Role.RESPONDER, message)
|
|
824
|
+
record(Role.RESPONDER, answer, answer.text, None)
|
|
825
|
+
answers += 1
|
|
826
|
+
message = reply_for_asker(answer.text, final=answers == cap, max_rounds=cap)
|
|
827
|
+
next_role = Role.ASKER
|
|
828
|
+
|
|
829
|
+
cancel_event = threading.Event()
|
|
830
|
+
# Ctrl-C can land anywhere: in a session, a preflight, or a caller's
|
|
831
|
+
# callback while it prints a reply. Every case keeps the completed turns.
|
|
832
|
+
try:
|
|
833
|
+
return relay()
|
|
834
|
+
except _StopError as stop:
|
|
835
|
+
return finish(stop.reason, stop.error)
|
|
836
|
+
except KeyboardInterrupt:
|
|
837
|
+
where = f"during turn {in_progress}" if in_progress else f"after {_turns(len(turns))}"
|
|
838
|
+
if in_progress is not None:
|
|
839
|
+
emit(
|
|
840
|
+
EventType.TURN_FINISHED,
|
|
841
|
+
turn=in_progress,
|
|
842
|
+
role=(
|
|
843
|
+
sides[Role.ASKER] if in_progress % 2 else sides[Role.RESPONDER]
|
|
844
|
+
).participant.role.value,
|
|
845
|
+
status="cancelled",
|
|
846
|
+
error="interrupted",
|
|
847
|
+
)
|
|
848
|
+
return finish(StopReason.INTERRUPTED, f"interrupted {where}")
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
def result_from_journal(events: Sequence[ConversationEvent]) -> ConversationResult:
|
|
852
|
+
"""Rebuild a consultation's result from its journal, as of its last event.
|
|
853
|
+
|
|
854
|
+
A run that never recorded its end is reported as interrupted.
|
|
855
|
+
"""
|
|
856
|
+
from comitia.discussion.journal import EventType
|
|
857
|
+
|
|
858
|
+
started = next((e for e in events if e.type is EventType.CONVERSATION_STARTED), None)
|
|
859
|
+
if started is None:
|
|
860
|
+
raise ConverseError("The journal has no conversation.started event.")
|
|
861
|
+
data = started.data
|
|
862
|
+
if data.get("kind") == "panel":
|
|
863
|
+
raise ConverseError("The journal holds a panel, not a consultation.")
|
|
864
|
+
sides: dict[Role, Participant] = {}
|
|
865
|
+
folders: dict[Role, Path] = {}
|
|
866
|
+
for item in data.get("participants", []):
|
|
867
|
+
role = Role(item["role"])
|
|
868
|
+
effort = item.get("effort")
|
|
869
|
+
sides[role] = Participant(
|
|
870
|
+
tool=AIToolID(item["tool"]),
|
|
871
|
+
role=role,
|
|
872
|
+
model=item.get("model"),
|
|
873
|
+
effort=EffortLevel(effort) if effort else None,
|
|
874
|
+
)
|
|
875
|
+
folders[role] = Path(item["folder"])
|
|
876
|
+
if set(sides) != {Role.ASKER, Role.RESPONDER}:
|
|
877
|
+
raise ConverseError("The journal does not name both sides of the consultation.")
|
|
878
|
+
max_rounds = int(data.get("max_rounds", DEFAULT_MAX_ROUNDS))
|
|
879
|
+
turns: list[ConverseTurn] = []
|
|
880
|
+
sessions: dict[Role, str | None] = {Role.ASKER: None, Role.RESPONDER: None}
|
|
881
|
+
stop_reason = StopReason.INTERRUPTED
|
|
882
|
+
error: str | None = "the run ended without recording its outcome"
|
|
883
|
+
answered_at_limit = False
|
|
884
|
+
finished_at = events[-1].ts if events else started.ts
|
|
885
|
+
|
|
886
|
+
def moment(value: object, fallback: datetime) -> datetime:
|
|
887
|
+
return datetime.fromisoformat(value) if isinstance(value, str) else fallback
|
|
888
|
+
|
|
889
|
+
for event in events:
|
|
890
|
+
if event.type is EventType.CONVERSATION_CONTINUED:
|
|
891
|
+
max_rounds = int(event.data.get("max_rounds", max_rounds))
|
|
892
|
+
stop_reason = StopReason.INTERRUPTED
|
|
893
|
+
error = "the run ended without recording its outcome"
|
|
894
|
+
elif event.type is EventType.MESSAGE_COMMITTED:
|
|
895
|
+
role = Role(event.data["role"])
|
|
896
|
+
usage = event.data.get("usage")
|
|
897
|
+
turns.append(
|
|
898
|
+
ConverseTurn(
|
|
899
|
+
number=int(event.data["turn"]),
|
|
900
|
+
role=role,
|
|
901
|
+
tool=AIToolID(event.data["tool"]),
|
|
902
|
+
text=str(event.data["text"]),
|
|
903
|
+
next=Next(event.data["next"]) if event.data.get("next") else None,
|
|
904
|
+
duration_seconds=float(event.data.get("duration_seconds", 0.0)),
|
|
905
|
+
denials=tuple(event.data.get("denials", ())),
|
|
906
|
+
usage=TokenUsage.model_validate(usage) if usage else None,
|
|
907
|
+
)
|
|
908
|
+
)
|
|
909
|
+
elif event.type is EventType.TURN_FINISHED:
|
|
910
|
+
session = event.data.get("session_id")
|
|
911
|
+
if session:
|
|
912
|
+
sessions[Role(event.data["role"])] = session
|
|
913
|
+
elif event.type is EventType.CONVERSATION_FINISHED:
|
|
914
|
+
stop_reason = StopReason(event.data["stop_reason"])
|
|
915
|
+
error = event.data.get("error")
|
|
916
|
+
answered_at_limit = bool(event.data.get("answered_at_limit"))
|
|
917
|
+
finished_at = moment(event.data.get("finished_at"), event.ts)
|
|
918
|
+
for role_name, session in (event.data.get("sessions") or {}).items():
|
|
919
|
+
if session:
|
|
920
|
+
sessions[Role(role_name)] = session
|
|
921
|
+
if turns and turns[-1].is_final_answer and stop_reason is not StopReason.ANSWERED:
|
|
922
|
+
# The final answer was committed but the run ended (a crash or Ctrl-C)
|
|
923
|
+
# before recording its outcome: it is answered, never continuable.
|
|
924
|
+
stop_reason, error = StopReason.ANSWERED, None
|
|
925
|
+
return ConversationResult(
|
|
926
|
+
goal=str(data["goal"]),
|
|
927
|
+
asker=sides[Role.ASKER],
|
|
928
|
+
responder=sides[Role.RESPONDER],
|
|
929
|
+
max_rounds=max_rounds,
|
|
930
|
+
started_at=moment(data.get("started_at"), started.ts),
|
|
931
|
+
finished_at=finished_at,
|
|
932
|
+
stop_reason=stop_reason,
|
|
933
|
+
turns=turns,
|
|
934
|
+
error=error,
|
|
935
|
+
answered_at_limit=answered_at_limit,
|
|
936
|
+
sessions=sessions,
|
|
937
|
+
folders=folders,
|
|
938
|
+
)
|
|
939
|
+
|
|
940
|
+
|
|
941
|
+
# ---------------------------------------------------------------------------
|
|
942
|
+
# Transcript, summary, and files
|
|
943
|
+
# ---------------------------------------------------------------------------
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
def _turns(count: int) -> str:
|
|
947
|
+
return f"{count} turn" if count == 1 else f"{count} turns"
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
def _questions(count: int) -> str:
|
|
951
|
+
return f"{count} question" if count == 1 else f"{count} questions"
|
|
952
|
+
|
|
953
|
+
|
|
954
|
+
def _asked(result: ConversationResult) -> int:
|
|
955
|
+
"""Questions the asker sent; its final answer is not one."""
|
|
956
|
+
return sum(1 for turn in result.turns if turn.role is Role.ASKER and not turn.is_final_answer)
|
|
957
|
+
|
|
958
|
+
|
|
959
|
+
def _where(result: ConversationResult) -> str:
|
|
960
|
+
"""Where a consultation that did not answer stood when it stopped."""
|
|
961
|
+
asked = _asked(result)
|
|
962
|
+
if asked > result.rounds:
|
|
963
|
+
return f"while the responder was answering question {asked}"
|
|
964
|
+
if asked == 0:
|
|
965
|
+
return "before the asker's first question"
|
|
966
|
+
return f"after {_questions(asked)}, while the asker was writing"
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def describe_stop(result: ConversationResult) -> str:
|
|
970
|
+
"""How the consultation ended, in one sentence, for people and ``--json``'s ``outcome``."""
|
|
971
|
+
if result.stop_reason is StopReason.ANSWERED:
|
|
972
|
+
asked = _asked(result)
|
|
973
|
+
after = f"after {_questions(asked)}" if asked else "without asking a question"
|
|
974
|
+
when = " at the question limit" if result.answered_at_limit else ""
|
|
975
|
+
return f"answered: the asker gave its final answer {after}{when}"
|
|
976
|
+
if result.stop_reason is StopReason.ROUND_LIMIT:
|
|
977
|
+
return (
|
|
978
|
+
f"question limit reached ({_questions(result.max_rounds)}) "
|
|
979
|
+
"and the asker gave no final answer"
|
|
980
|
+
)
|
|
981
|
+
if result.stop_reason is StopReason.INTERRUPTED:
|
|
982
|
+
# The error only restates where it stopped.
|
|
983
|
+
return f"interrupted by the user {_where(result)}"
|
|
984
|
+
detail = f": {result.error}" if result.error else ""
|
|
985
|
+
if result.stop_reason is StopReason.TIMEOUT:
|
|
986
|
+
return f"stopped on the time limit {_where(result)}{detail}"
|
|
987
|
+
return f"a session failed {_where(result)}{detail}"
|
|
988
|
+
|
|
989
|
+
|
|
990
|
+
def render_transcript(result: ConversationResult) -> str:
|
|
991
|
+
"""Render a finished consultation as markdown."""
|
|
992
|
+
return _render_transcript(
|
|
993
|
+
goal=result.goal,
|
|
994
|
+
asker=result.asker,
|
|
995
|
+
responder=result.responder,
|
|
996
|
+
max_rounds=result.max_rounds,
|
|
997
|
+
started_at=result.started_at,
|
|
998
|
+
finished_at=result.finished_at,
|
|
999
|
+
turns=result.turns,
|
|
1000
|
+
outcome=describe_stop(result),
|
|
1001
|
+
folders=result.folders,
|
|
1002
|
+
sessions=result.sessions,
|
|
1003
|
+
)
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
def render_partial_transcript(
|
|
1007
|
+
*,
|
|
1008
|
+
goal: str,
|
|
1009
|
+
asker: Participant,
|
|
1010
|
+
responder: Participant,
|
|
1011
|
+
max_rounds: int,
|
|
1012
|
+
started_at: datetime,
|
|
1013
|
+
turns: Sequence[ConverseTurn],
|
|
1014
|
+
folders: Mapping[Role, Path] | None = None,
|
|
1015
|
+
) -> str:
|
|
1016
|
+
"""Render a consultation that is still running, so completed turns survive a crash."""
|
|
1017
|
+
return _render_transcript(
|
|
1018
|
+
goal=goal,
|
|
1019
|
+
asker=asker,
|
|
1020
|
+
responder=responder,
|
|
1021
|
+
max_rounds=max_rounds,
|
|
1022
|
+
started_at=started_at,
|
|
1023
|
+
finished_at=None,
|
|
1024
|
+
turns=turns,
|
|
1025
|
+
outcome=f"in progress: {_turns(len(turns))} completed",
|
|
1026
|
+
folders=folders or {},
|
|
1027
|
+
sessions={},
|
|
1028
|
+
)
|
|
1029
|
+
|
|
1030
|
+
|
|
1031
|
+
def _fenced(text: str) -> str:
|
|
1032
|
+
"""``text`` verbatim in a code fence no line of it can close."""
|
|
1033
|
+
longest = max((len(run) for run in re.findall(r"`+", text)), default=0)
|
|
1034
|
+
fence = "`" * max(3, longest + 1)
|
|
1035
|
+
return f"{fence}text\n{text}\n{fence}"
|
|
1036
|
+
|
|
1037
|
+
|
|
1038
|
+
def _side_line(
|
|
1039
|
+
label: str, participant: Participant, folder: Path | None, *, read_only: bool
|
|
1040
|
+
) -> str:
|
|
1041
|
+
settings = participant.settings
|
|
1042
|
+
facts = [participant.tool.value + (f" ({settings})" if settings else "")]
|
|
1043
|
+
if read_only:
|
|
1044
|
+
facts.append("read-only")
|
|
1045
|
+
if folder is not None:
|
|
1046
|
+
facts.append(f"in `{folder}`")
|
|
1047
|
+
return f"- {label}: {', '.join(facts)}"
|
|
1048
|
+
|
|
1049
|
+
|
|
1050
|
+
def _render_transcript(
|
|
1051
|
+
*,
|
|
1052
|
+
goal: str,
|
|
1053
|
+
asker: Participant,
|
|
1054
|
+
responder: Participant,
|
|
1055
|
+
max_rounds: int,
|
|
1056
|
+
started_at: datetime,
|
|
1057
|
+
finished_at: datetime | None,
|
|
1058
|
+
turns: Sequence[ConverseTurn],
|
|
1059
|
+
outcome: str,
|
|
1060
|
+
folders: Mapping[Role, Path],
|
|
1061
|
+
sessions: Mapping[Role, str | None],
|
|
1062
|
+
) -> str:
|
|
1063
|
+
"""The transcript: run facts, the goal, then every message as written.
|
|
1064
|
+
|
|
1065
|
+
The goal sits in a code fence and each turn under a numbered "Turn"
|
|
1066
|
+
heading after a rule, so headings inside the goal or a message never read
|
|
1067
|
+
as the transcript's own structure.
|
|
1068
|
+
"""
|
|
1069
|
+
lines = [
|
|
1070
|
+
"# Consultation",
|
|
1071
|
+
"",
|
|
1072
|
+
_side_line("Asker", asker, folders.get(Role.ASKER), read_only=False),
|
|
1073
|
+
_side_line("Responder", responder, folders.get(Role.RESPONDER), read_only=True),
|
|
1074
|
+
f"- Started: {started_at.isoformat(timespec='seconds')}",
|
|
1075
|
+
]
|
|
1076
|
+
if finished_at is not None:
|
|
1077
|
+
lines.append(f"- Finished: {finished_at.isoformat(timespec='seconds')}")
|
|
1078
|
+
lines += [f"- Rounds allowed: {max_rounds}", f"- Outcome: {outcome}"]
|
|
1079
|
+
known = [
|
|
1080
|
+
f"{side.tool.value} `{sessions[side.role]}`"
|
|
1081
|
+
for side in (asker, responder)
|
|
1082
|
+
if sessions.get(side.role)
|
|
1083
|
+
]
|
|
1084
|
+
if known:
|
|
1085
|
+
lines.append(f"- Sessions: {', '.join(known)}")
|
|
1086
|
+
lines += ["", "## Goal (sent only to the asker)", "", _fenced(goal), ""]
|
|
1087
|
+
for turn in turns:
|
|
1088
|
+
if turn.is_final_answer:
|
|
1089
|
+
heading = f"## Turn {turn.number} · final answer ({turn.tool.value})"
|
|
1090
|
+
elif turn.role is Role.ASKER:
|
|
1091
|
+
heading = f"## Turn {turn.number} · asker ({turn.tool.value}) → responder"
|
|
1092
|
+
else:
|
|
1093
|
+
heading = f"## Turn {turn.number} · responder ({turn.tool.value}) → asker"
|
|
1094
|
+
body = turn.text or "(empty message)"
|
|
1095
|
+
lines += ["---", "", heading, "", body, "", f"*{turn_footer(turn)}*", ""]
|
|
1096
|
+
return "\n".join(lines).rstrip() + "\n"
|
|
1097
|
+
|
|
1098
|
+
|
|
1099
|
+
def turn_footer(turn: ConverseTurn) -> str:
|
|
1100
|
+
"""The one-line run facts shown under a turn: marker, time, denials."""
|
|
1101
|
+
parts = [f"NEXT: {turn.next.value}"] if turn.next is not None else []
|
|
1102
|
+
parts.append(f"{turn.duration_seconds:.0f}s")
|
|
1103
|
+
parts += [f"denied: {denial}" for denial in turn.denials]
|
|
1104
|
+
return " · ".join(parts)
|
|
1105
|
+
|
|
1106
|
+
|
|
1107
|
+
def to_handoff_transcript(result: ConversationResult, path: Path) -> ConversationTranscript:
|
|
1108
|
+
"""Express the consultation in the handoff model so the summarizer can read it."""
|
|
1109
|
+
from comitia.discussion.transcript import (
|
|
1110
|
+
ConversationTranscript,
|
|
1111
|
+
ConversationTurn,
|
|
1112
|
+
SessionRef,
|
|
1113
|
+
)
|
|
1114
|
+
|
|
1115
|
+
def label(turn: ConverseTurn) -> str:
|
|
1116
|
+
if turn.is_final_answer:
|
|
1117
|
+
return f"asker ({turn.tool.value}), final answer"
|
|
1118
|
+
return f"{turn.role.value} ({turn.tool.value})"
|
|
1119
|
+
|
|
1120
|
+
return ConversationTranscript(
|
|
1121
|
+
session_ref=SessionRef(
|
|
1122
|
+
tool_id=result.asker.tool,
|
|
1123
|
+
session_id=path.parent.name,
|
|
1124
|
+
path=path,
|
|
1125
|
+
started_at=result.started_at,
|
|
1126
|
+
),
|
|
1127
|
+
turns=[
|
|
1128
|
+
ConversationTurn(
|
|
1129
|
+
role="user" if turn.role is Role.ASKER else "assistant",
|
|
1130
|
+
content=f"{label(turn)}, turn {turn.number}:\n{turn.text}",
|
|
1131
|
+
)
|
|
1132
|
+
for turn in result.turns
|
|
1133
|
+
],
|
|
1134
|
+
)
|
|
1135
|
+
|
|
1136
|
+
|
|
1137
|
+
def build_summary_prompt(result: ConversationResult, *, transcript_path: Path) -> str:
|
|
1138
|
+
"""Assemble the summary prompt: the instructions, then the whole transcript.
|
|
1139
|
+
|
|
1140
|
+
Nothing is dropped or clipped; a transcript too large for the summarizer's
|
|
1141
|
+
model fails in that tool, which reports it.
|
|
1142
|
+
"""
|
|
1143
|
+
from comitia.discussion.transcript import render_turn
|
|
1144
|
+
|
|
1145
|
+
header = (
|
|
1146
|
+
_load(SUMMARY_PROMPT_FILE)
|
|
1147
|
+
.format(
|
|
1148
|
+
asker=result.asker.tool.value,
|
|
1149
|
+
responder=result.responder.tool.value,
|
|
1150
|
+
goal=result.goal,
|
|
1151
|
+
stop_reason=describe_stop(result),
|
|
1152
|
+
)
|
|
1153
|
+
.strip()
|
|
1154
|
+
)
|
|
1155
|
+
lines = [header, "", "--- Transcript ---\n"]
|
|
1156
|
+
for turn in to_handoff_transcript(result, transcript_path).turns:
|
|
1157
|
+
lines += [render_turn(turn), ""]
|
|
1158
|
+
return "\n".join(lines)
|
|
1159
|
+
|
|
1160
|
+
|
|
1161
|
+
def summarize_conversation(
|
|
1162
|
+
result: ConversationResult,
|
|
1163
|
+
*,
|
|
1164
|
+
transcript_path: Path,
|
|
1165
|
+
tool: AIToolID,
|
|
1166
|
+
working_dir: Path,
|
|
1167
|
+
model: str | None = None,
|
|
1168
|
+
effort: EffortLevel | None = None,
|
|
1169
|
+
timeout_seconds: float = DEFAULT_SUMMARY_TIMEOUT_SECONDS,
|
|
1170
|
+
runner: TurnRunner | None = None,
|
|
1171
|
+
allow_project_hooks: bool = False,
|
|
1172
|
+
) -> str:
|
|
1173
|
+
"""Summarize a finished consultation in one managed read-only session.
|
|
1174
|
+
|
|
1175
|
+
The summary runs through the same boundary as the turns, so it gets the
|
|
1176
|
+
runtime's deadline, cancellation, process-group cleanup and each tool's
|
|
1177
|
+
read-only profile, plus the recursion guard. Failures raise
|
|
1178
|
+
:class:`ConverseSummaryError`; the transcript is already on disk.
|
|
1179
|
+
"""
|
|
1180
|
+
from crossby.ai_tools import HeadlessSessionError
|
|
1181
|
+
|
|
1182
|
+
prompt = build_summary_prompt(result, transcript_path=transcript_path)
|
|
1183
|
+
request = _request(
|
|
1184
|
+
None,
|
|
1185
|
+
prompt=prompt,
|
|
1186
|
+
working_dir=working_dir,
|
|
1187
|
+
timeout_seconds=timeout_seconds,
|
|
1188
|
+
model=model,
|
|
1189
|
+
effort=effort,
|
|
1190
|
+
read_only=True,
|
|
1191
|
+
allow_project_hooks=allow_project_hooks,
|
|
1192
|
+
)
|
|
1193
|
+
runner = runner or HeadlessTurnRunner()
|
|
1194
|
+
try:
|
|
1195
|
+
session = runner.run(tool, request, threading.Event())
|
|
1196
|
+
except HeadlessSessionError as exc:
|
|
1197
|
+
raise ConverseSummaryError(str(exc)) from None
|
|
1198
|
+
if session.status is not HeadlessTerminalStatus.SUCCEEDED:
|
|
1199
|
+
raise ConverseSummaryError(
|
|
1200
|
+
f"{tool.value} summary session ended with status {_status(session)}"
|
|
1201
|
+
)
|
|
1202
|
+
text = (session.final_text or "").strip()
|
|
1203
|
+
if not text:
|
|
1204
|
+
raise ConverseSummaryError(f"{tool.value} returned an empty summary")
|
|
1205
|
+
return text
|
|
1206
|
+
|
|
1207
|
+
|
|
1208
|
+
def render_summary(result: ConversationResult, body: str) -> str:
|
|
1209
|
+
return (
|
|
1210
|
+
"# Consultation summary\n\n"
|
|
1211
|
+
f"**Goal:** {result.goal}\n\n"
|
|
1212
|
+
f"- Asker: {result.asker.tool.value}\n"
|
|
1213
|
+
f"- Responder: {result.responder.tool.value}\n"
|
|
1214
|
+
f"- Outcome: {describe_stop(result)}\n\n"
|
|
1215
|
+
f"{body.strip()}\n"
|
|
1216
|
+
)
|
|
1217
|
+
|
|
1218
|
+
|
|
1219
|
+
def conversation_dir(project_root: Path, started_at: datetime) -> Path:
|
|
1220
|
+
stamp = started_at.strftime("%Y%m%dT%H%M%S%f")
|
|
1221
|
+
return project_root / ".crossby" / "conversations" / stamp
|