deliberaide-cli 0.1.4__tar.gz → 0.1.5__tar.gz

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 (23) hide show
  1. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/PKG-INFO +26 -1
  2. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli/README.md +26 -1
  3. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli/__main__.py +1 -1
  4. deliberaide_cli-0.1.5/deliberaide_cli/copilot_chat.py +482 -0
  5. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli/core/__init__.py +1 -1
  6. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli/core/manifest.py +1 -1
  7. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli/deliberaide_cli.py +992 -985
  8. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli/route_manifest.json +41357 -40049
  9. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli/utils/__init__.py +1 -1
  10. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli/utils/api_backend.py +138 -138
  11. deliberaide_cli-0.1.5/deliberaide_cli/utils/formatting.py +137 -0
  12. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli/utils/repl_skin.py +1 -1
  13. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli.egg-info/PKG-INFO +26 -1
  14. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli.egg-info/SOURCES.txt +1 -0
  15. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/setup.py +1 -1
  16. deliberaide_cli-0.1.4/deliberaide_cli/utils/formatting.py +0 -86
  17. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli/__init__.py +0 -0
  18. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli/core/session.py +0 -0
  19. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli.egg-info/dependency_links.txt +0 -0
  20. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli.egg-info/entry_points.txt +0 -0
  21. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli.egg-info/requires.txt +0 -0
  22. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/deliberaide_cli.egg-info/top_level.txt +0 -0
  23. {deliberaide_cli-0.1.4 → deliberaide_cli-0.1.5}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deliberaide-cli
3
- Version: 0.1.4
3
+ Version: 0.1.5
4
4
  Summary: Stateful, agent-native CLI for the deliberAIde v2 API
5
5
  Home-page: https://deliberaide.com
6
6
  Author: deliberAIde
@@ -110,6 +110,31 @@ Or load JSON from a file:
110
110
  deliberaide-cli projects create-project --body-file .\payload.json
111
111
  ```
112
112
 
113
+ ## Co-Pilot turns
114
+
115
+ The web app talks to the Co-Pilot over the WebSocket `/api/v1/ws/copilot`, not over the
116
+ blocking `POST /copilot/conversations/{id}/messages`. `copilot chat` does the same: it
117
+ sends one `copilot_message` frame carrying the web client's `runtime_context` (selected
118
+ workflow, discussion scope), streams the server's progress frames, keeps the connection
119
+ alive with pings, and returns the final message when the turn ends. Turns can take
120
+ several minutes.
121
+
122
+ ```powershell
123
+ # new conversation on a discussion; streams frames, prints the final answer
124
+ deliberaide-cli copilot chat --discussion-id <uuid> --x-organisation-id <uuid> --text "..."
125
+
126
+ # continue an existing conversation; scope and workflow are restored from it
127
+ deliberaide-cli --json copilot chat --conversation-id <uuid> --text "..." --no-stream
128
+
129
+ # show the frame that would be sent, without sending it
130
+ deliberaide-cli copilot chat --conversation-id <uuid> --text "..." --dry-run
131
+
132
+ # a turn started with the blocking POST timed out client-side: poll for the answer
133
+ deliberaide-cli copilot wait --conversation-id <uuid>
134
+ ```
135
+
136
+ Object-typed body fields such as `--runtime-context` accept JSON text or `@file`.
137
+
113
138
  ## Multipart uploads
114
139
 
115
140
  ```powershell
@@ -72,6 +72,31 @@ Or load JSON from a file:
72
72
  deliberaide-cli projects create-project --body-file .\payload.json
73
73
  ```
74
74
 
75
+ ## Co-Pilot turns
76
+
77
+ The web app talks to the Co-Pilot over the WebSocket `/api/v1/ws/copilot`, not over the
78
+ blocking `POST /copilot/conversations/{id}/messages`. `copilot chat` does the same: it
79
+ sends one `copilot_message` frame carrying the web client's `runtime_context` (selected
80
+ workflow, discussion scope), streams the server's progress frames, keeps the connection
81
+ alive with pings, and returns the final message when the turn ends. Turns can take
82
+ several minutes.
83
+
84
+ ```powershell
85
+ # new conversation on a discussion; streams frames, prints the final answer
86
+ deliberaide-cli copilot chat --discussion-id <uuid> --x-organisation-id <uuid> --text "..."
87
+
88
+ # continue an existing conversation; scope and workflow are restored from it
89
+ deliberaide-cli --json copilot chat --conversation-id <uuid> --text "..." --no-stream
90
+
91
+ # show the frame that would be sent, without sending it
92
+ deliberaide-cli copilot chat --conversation-id <uuid> --text "..." --dry-run
93
+
94
+ # a turn started with the blocking POST timed out client-side: poll for the answer
95
+ deliberaide-cli copilot wait --conversation-id <uuid>
96
+ ```
97
+
98
+ Object-typed body fields such as `--runtime-context` accept JSON text or `@file`.
99
+
75
100
  ## Multipart uploads
76
101
 
77
102
  ```powershell
@@ -119,4 +144,4 @@ exit
119
144
 
120
145
  ```powershell
121
146
  python -m pytest .\agent-harness\deliberaide_cli\tests -v
122
- ```
147
+ ```
@@ -2,4 +2,4 @@ from deliberaide_cli.deliberaide_cli import main
2
2
 
3
3
 
4
4
  if __name__ == "__main__":
5
- main()
5
+ main()
@@ -0,0 +1,482 @@
1
+ """Co-Pilot turns the way the web app does them.
2
+
3
+ The web client (``lib/hooks/use-unified-chat-controller.ts`` + ``lib/websocket/client.ts``)
4
+ never uses the blocking ``POST /copilot/conversations/{id}/messages``. It keeps a
5
+ WebSocket open on ``/api/v1/ws/copilot`` (cookie-authenticated), sends one
6
+ ``copilot_message`` frame whose ``runtime_context`` carries the selected workflow and the
7
+ discussion scope, streams the server's progress frames, and treats
8
+ ``copilot_response_final`` followed by ``copilot_done`` as the end of the turn.
9
+
10
+ ``copilot chat`` reproduces exactly that. ``copilot wait`` is the fallback for callers
11
+ that already used the blocking POST and hit a client timeout: it polls the conversation
12
+ until a non-interim assistant message appears.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import time
19
+ from dataclasses import dataclass, field
20
+ from typing import Any, Callable, Iterable
21
+
22
+ import click
23
+ from websockets.exceptions import ConnectionClosed
24
+ from websockets.sync.client import connect as websocket_connect
25
+
26
+ from deliberaide_cli.utils.formatting import json_dumps
27
+
28
+ WORKFLOWS: tuple[str, ...] = ("agent", "chat", "plan", "discuss", "analyze", "report")
29
+ DEFAULT_WORKFLOW = "agent" # lib/stores/conversation.ts getInitialWorkflow()
30
+ WS_PATH = "/api/v1/ws/copilot"
31
+ ORG_HEADER = "x-organisation-id"
32
+ TERMINAL_FRAMES = {"copilot_done", "error", "quota_exceeded"}
33
+
34
+
35
+ # ------------------------------------------------------------------ runtime_context
36
+
37
+
38
+ def build_runtime_context(
39
+ *,
40
+ selected_workflow: str = DEFAULT_WORKFLOW,
41
+ discussion_ids: Iterable[str] | None = None,
42
+ discussion_id: str | None = None,
43
+ session_id: str | None = None,
44
+ event_id: str | None = None,
45
+ project_id: str | None = None,
46
+ workspace_state: dict[str, Any] | None = None,
47
+ canvas_context: dict[str, Any] | None = None,
48
+ ) -> dict[str, Any]:
49
+ """Mirror ``buildRuntimeContext`` in use-unified-chat-controller.ts.
50
+
51
+ Top-level scope ids are omitted when unknown (the web passes ``?? undefined``);
52
+ ``scope_context`` always carries the four keys, null when unknown; ``scope_type`` is
53
+ derived from the number of discussion ids exactly like the web does.
54
+ """
55
+ workflow = (selected_workflow or DEFAULT_WORKFLOW).strip().lower()
56
+ if workflow not in WORKFLOWS:
57
+ raise ValueError(f"selected_workflow must be one of {', '.join(WORKFLOWS)}; got {selected_workflow!r}")
58
+
59
+ ids: list[str] = []
60
+ for raw in list(discussion_ids or []) + ([discussion_id] if discussion_id else []):
61
+ value = str(raw).strip()
62
+ if value and value not in ids:
63
+ ids.append(value)
64
+ primary_discussion = discussion_id or (ids[0] if ids else None)
65
+
66
+ context: dict[str, Any] = {"selected_workflow": workflow}
67
+ if canvas_context:
68
+ context.update(canvas_context)
69
+ context["discussion_ids"] = ids
70
+ for key, value in (
71
+ ("discussion_id", primary_discussion),
72
+ ("session_id", session_id),
73
+ ("event_id", event_id),
74
+ ("project_id", project_id),
75
+ ):
76
+ if value:
77
+ context[key] = value
78
+ context["scope_context"] = {
79
+ "discussion_id": primary_discussion,
80
+ "session_id": session_id,
81
+ "event_id": event_id,
82
+ "project_id": project_id,
83
+ }
84
+ context["scope_type"] = "multi" if len(ids) > 1 else "single" if len(ids) == 1 else "none"
85
+ context["scope_label"] = None
86
+ context["selection_origin"] = None
87
+ context["workspace_state"] = {
88
+ **(workspace_state or {}),
89
+ "discussion_ids": ids,
90
+ "scope_label": (workspace_state or {}).get("scope_label"),
91
+ "selection_origin": (workspace_state or {}).get("selection_origin"),
92
+ }
93
+ return context
94
+
95
+
96
+ def scope_from_conversation(detail: dict[str, Any]) -> dict[str, Any]:
97
+ """Pull the scope the web app would restore when it opens an existing conversation."""
98
+ metadata = detail.get("metadata_json") if isinstance(detail.get("metadata_json"), dict) else {}
99
+ workspace_state = metadata.get("workspace_state") if isinstance(metadata.get("workspace_state"), dict) else {}
100
+ ids = [str(x) for x in (workspace_state.get("discussion_ids") or []) if x]
101
+ if not ids and detail.get("discussion_id"):
102
+ ids = [str(detail["discussion_id"])]
103
+ workflow = metadata.get("selected_workflow")
104
+ return {
105
+ "discussion_ids": ids,
106
+ "discussion_id": str(detail["discussion_id"]) if detail.get("discussion_id") else (ids[0] if ids else None),
107
+ "project_id": str(detail["project_id"]) if detail.get("project_id") else None,
108
+ "selected_workflow": workflow if isinstance(workflow, str) and workflow.lower() in WORKFLOWS else None,
109
+ "workspace_state": workspace_state,
110
+ }
111
+
112
+
113
+ # ----------------------------------------------------------------------- the turn
114
+
115
+
116
+ @dataclass
117
+ class ChatResult:
118
+ conversation_id: str | None
119
+ final: dict[str, Any] | None = None
120
+ error: dict[str, Any] | None = None
121
+ frames: int = 0
122
+ frame_counts: dict[str, int] = field(default_factory=dict)
123
+ duration_seconds: float = 0.0
124
+ timed_out: bool = False
125
+
126
+ @property
127
+ def ok(self) -> bool:
128
+ return self.final is not None and self.error is None and not self.timed_out
129
+
130
+
131
+ def copilot_message_frame(
132
+ *,
133
+ text: str,
134
+ conversation_id: str | None,
135
+ runtime_context: dict[str, Any],
136
+ reasoning_effort: str | None,
137
+ web_search_enabled: bool | None,
138
+ show_in_chat: bool | None,
139
+ organisation_id: str | None,
140
+ ) -> dict[str, Any]:
141
+ """Mirror ``WebSocketClient.sendCopilotMessage``; optional keys are omitted, not nulled."""
142
+ data: dict[str, Any] = {"text": text, "runtime_context": runtime_context}
143
+ if conversation_id:
144
+ data["conversation_id"] = conversation_id
145
+ if reasoning_effort:
146
+ data["reasoning_effort"] = reasoning_effort
147
+ if web_search_enabled is not None:
148
+ data["web_search_enabled"] = web_search_enabled
149
+ if show_in_chat is not None:
150
+ data["show_in_chat"] = show_in_chat
151
+ if organisation_id:
152
+ data["organisation_id"] = organisation_id
153
+ return {"type": "copilot_message", "data": data}
154
+
155
+
156
+ def run_chat_turn(
157
+ websocket: Any,
158
+ frame: dict[str, Any],
159
+ *,
160
+ conversation_id: str | None,
161
+ timeout_seconds: float,
162
+ ping_interval: float,
163
+ on_frame: Callable[[dict[str, Any]], None] | None = None,
164
+ ) -> ChatResult:
165
+ """Send one frame and consume server frames until the turn ends.
166
+
167
+ ``websocket`` needs ``send(str)`` and ``recv(timeout=float)`` (websockets.sync); a
168
+ ``TimeoutError`` from ``recv`` means silence, which is answered with a ``ping`` like
169
+ the web client's heartbeat. The turn ends on ``copilot_done``, ``error``,
170
+ ``quota_exceeded``, connection close, or the overall deadline.
171
+ """
172
+ started = time.monotonic()
173
+ deadline = started + timeout_seconds
174
+ result = ChatResult(conversation_id=conversation_id)
175
+ websocket.send(json_dumps(frame, compact=True))
176
+
177
+ while True:
178
+ remaining = deadline - time.monotonic()
179
+ if remaining <= 0:
180
+ result.timed_out = True
181
+ break
182
+ try:
183
+ raw = websocket.recv(timeout=min(ping_interval, remaining))
184
+ except TimeoutError:
185
+ websocket.send(json_dumps({"type": "ping", "data": {}}, compact=True))
186
+ continue
187
+ except ConnectionClosed as exc:
188
+ if result.final is None:
189
+ result.error = {"message": f"connection closed before the turn finished: {exc}"}
190
+ break
191
+
192
+ try:
193
+ event = json.loads(raw)
194
+ except (TypeError, ValueError):
195
+ continue
196
+ if not isinstance(event, dict):
197
+ continue
198
+ frame_type = str(event.get("type") or "")
199
+ data = event.get("data") if isinstance(event.get("data"), dict) else {}
200
+ result.frames += 1
201
+ result.frame_counts[frame_type] = result.frame_counts.get(frame_type, 0) + 1
202
+ if on_frame is not None:
203
+ on_frame(event)
204
+
205
+ if frame_type == "copilot_conversation_created" and data.get("conversation_id"):
206
+ result.conversation_id = str(data["conversation_id"])
207
+ elif frame_type == "copilot_response_final":
208
+ result.final = data
209
+ if data.get("conversation_id"):
210
+ result.conversation_id = str(data["conversation_id"])
211
+ elif frame_type in ("error", "quota_exceeded"):
212
+ result.error = {"type": frame_type, **data}
213
+ break
214
+ elif frame_type == "copilot_done":
215
+ break
216
+
217
+ result.duration_seconds = round(time.monotonic() - started, 1)
218
+ return result
219
+
220
+
221
+ # ------------------------------------------------------------------ wait (HTTP)
222
+
223
+
224
+ def select_terminal_message(messages: list[dict[str, Any]], *, after: str | None = None) -> dict[str, Any] | None:
225
+ """The newest assistant message that is not an interim note and is newer than ``after``.
226
+
227
+ ``after`` is an ISO timestamp; when omitted, the latest user message's timestamp is
228
+ used so that an old answer is never mistaken for the new one.
229
+ """
230
+ if after is None:
231
+ user_times = [m.get("created_at") or "" for m in messages if m.get("role") == "user"]
232
+ after = max(user_times) if user_times else ""
233
+ candidates = [
234
+ m
235
+ for m in messages
236
+ if m.get("role") == "assistant"
237
+ and (m.get("content") or "").strip()
238
+ and (m.get("metadata_json") or {}).get("kind") != "interim_note"
239
+ and (m.get("created_at") or "") > (after or "")
240
+ ]
241
+ return max(candidates, key=lambda m: m.get("created_at") or "") if candidates else None
242
+
243
+
244
+ # ----------------------------------------------------------------------- commands
245
+
246
+
247
+ def _org_header(runtime: Any, explicit: str | None) -> dict[str, str]:
248
+ value = explicit or runtime.profile.defaults.get("x_organisation_id") or runtime.profile.defaults.get(ORG_HEADER)
249
+ return {ORG_HEADER: str(value)} if value else {}
250
+
251
+
252
+ def _cookie_header(runtime: Any) -> dict[str, str]:
253
+ cookie = "; ".join(f"{c.name}={c.value}" for c in runtime.backend.export_cookies() if c.value)
254
+ return {"Cookie": cookie} if cookie else {}
255
+
256
+
257
+ def _fetch_conversation(runtime: Any, conversation_id: str, headers: dict[str, str]) -> dict[str, Any]:
258
+ response = runtime.backend.request("GET", f"/api/v1/copilot/conversations/{conversation_id}", headers=headers)
259
+ if not response.is_success:
260
+ raise click.ClickException(f"GET conversation {conversation_id} failed: HTTP {response.status_code} {response.text[:200]}")
261
+ return response.json()
262
+
263
+
264
+ def _human_frame_printer(echo: Callable[[str], None]) -> Callable[[dict[str, Any]], None]:
265
+ state = {"reasoning_open": False}
266
+
267
+ def close_reasoning() -> None:
268
+ if state["reasoning_open"]:
269
+ click.echo("")
270
+ state["reasoning_open"] = False
271
+
272
+ def render(event: dict[str, Any]) -> None:
273
+ kind = str(event.get("type") or "")
274
+ data = event.get("data") if isinstance(event.get("data"), dict) else {}
275
+ if kind in ("pong", "connected", "progress", "credit_balance_update", "copilot_reasoning_info", "copilot_title_update"):
276
+ return
277
+ if kind == "copilot_reasoning_delta":
278
+ # The web app shows the model's reasoning summary as it streams; do the same inline.
279
+ if not state["reasoning_open"]:
280
+ click.echo(" [reasoning] ", nl=False)
281
+ state["reasoning_open"] = True
282
+ click.echo(str(data.get("delta", "")).replace("\n", " "), nl=False)
283
+ return
284
+ close_reasoning()
285
+ if kind == "copilot_thinking":
286
+ if data.get("heartbeat"):
287
+ return
288
+ echo(f" [thinking] {data.get('message', '')}")
289
+ elif kind == "copilot_tool_call":
290
+ # The web app shows the server-provided display labels, not raw tool names.
291
+ label = (
292
+ data.get("display_label_completed") if data.get("status") == "completed" else data.get("display_label_active")
293
+ ) or data.get("display_label") or data.get("tool_name") or data.get("name") or ""
294
+ echo(f" [tool {data.get('status', '')}] {label}")
295
+ elif kind == "copilot_subagent_spawned":
296
+ echo(f" [subagent] {data.get('subagent_name', '')}: {data.get('display_label') or str(data.get('task_preview', ''))[:100]}")
297
+ elif kind == "copilot_interim_message":
298
+ echo(f" [interim] {str(data.get('content', '')).strip()}")
299
+ elif kind == "copilot_response_chunk":
300
+ # The answer streams in chunks; print them inline and skip the duplicate on final.
301
+ if not state.get("chunked"):
302
+ echo("")
303
+ state["chunked"] = True
304
+ click.echo(str(data.get("chunk", "")), nl=False)
305
+ elif kind == "copilot_conversation_created":
306
+ echo(f" [conversation] {data.get('conversation_id')}")
307
+ elif kind == "copilot_response_final":
308
+ if state.get("chunked"):
309
+ click.echo("")
310
+ else:
311
+ echo("")
312
+ echo(str(data.get("content", "")))
313
+ elif kind in ("error", "quota_exceeded", "quota_warning"):
314
+ echo(f" [{kind}] {json_dumps(data, compact=True)}")
315
+ elif kind == "copilot_done":
316
+ echo(" [done]")
317
+ else:
318
+ echo(f" [{kind}] {json_dumps(data, compact=True)[:160]}")
319
+
320
+ return render
321
+
322
+
323
+ def install_copilot_commands(root: click.Group) -> None:
324
+ group = root.commands.get("copilot")
325
+ if not isinstance(group, click.Group):
326
+ group = click.Group("copilot")
327
+ root.add_command(group)
328
+
329
+ @click.command("chat")
330
+ @click.option("--text", required=True, help="The message to send.")
331
+ @click.option("--conversation-id", default=None, help="Existing conversation; omit to let the server create one.")
332
+ @click.option("--discussion-id", "discussion_ids", multiple=True, help="Discussion scope; repeat for several. Defaults to the conversation's scope.")
333
+ @click.option("--project-id", default=None)
334
+ @click.option("--session-id", default=None)
335
+ @click.option("--event-id", default=None)
336
+ @click.option("--workflow", type=click.Choice(WORKFLOWS), default=None, show_default=False,
337
+ help=f"selected_workflow; defaults to the conversation's stored workflow, else '{DEFAULT_WORKFLOW}' like the web app.")
338
+ @click.option("--reasoning-effort", type=click.Choice(["low", "high"]), default=None, help="Omit to use the server default (high).")
339
+ @click.option("--web-search/--no-web-search", default=None, help="web_search_enabled; omitted unless given.")
340
+ @click.option("--hide-from-chat", is_flag=True, help="Run the turn without a visible user message (show_in_chat=false).")
341
+ @click.option("--x-organisation-id", default=None, help="Organisation header; falls back to the profile default.")
342
+ @click.option("--timeout-seconds", type=float, default=900.0, show_default=True, help="Overall budget for the turn.")
343
+ @click.option("--ping-interval", type=float, default=30.0, show_default=True, help="Heartbeat while the server is silent.")
344
+ @click.option("--stream/--no-stream", default=True, show_default=True, help="Print server frames as they arrive (NDJSON in --json mode).")
345
+ @click.option("--dry-run", is_flag=True, help="Print the frame that would be sent and exit.")
346
+ @click.pass_obj
347
+ def copilot_chat(
348
+ runtime: Any,
349
+ text: str,
350
+ conversation_id: str | None,
351
+ discussion_ids: tuple[str, ...],
352
+ project_id: str | None,
353
+ session_id: str | None,
354
+ event_id: str | None,
355
+ workflow: str | None,
356
+ reasoning_effort: str | None,
357
+ web_search: bool | None,
358
+ hide_from_chat: bool,
359
+ x_organisation_id: str | None,
360
+ timeout_seconds: float,
361
+ ping_interval: float,
362
+ stream: bool,
363
+ dry_run: bool,
364
+ ) -> None:
365
+ """Send one Co-Pilot message over the WebSocket, exactly like the web app, and stream the turn."""
366
+ org_headers = _org_header(runtime, x_organisation_id)
367
+ scope: dict[str, Any] = {"discussion_ids": list(discussion_ids), "discussion_id": None, "project_id": project_id,
368
+ "selected_workflow": None, "workspace_state": {}}
369
+ if conversation_id and not discussion_ids:
370
+ scope = scope_from_conversation(_fetch_conversation(runtime, conversation_id, org_headers))
371
+ if project_id:
372
+ scope["project_id"] = project_id
373
+ runtime_context = build_runtime_context(
374
+ selected_workflow=workflow or scope.get("selected_workflow") or DEFAULT_WORKFLOW,
375
+ discussion_ids=scope.get("discussion_ids") or [],
376
+ discussion_id=scope.get("discussion_id"),
377
+ session_id=session_id,
378
+ event_id=event_id,
379
+ project_id=scope.get("project_id"),
380
+ workspace_state=scope.get("workspace_state") or None,
381
+ )
382
+ frame = copilot_message_frame(
383
+ text=text,
384
+ conversation_id=conversation_id,
385
+ runtime_context=runtime_context,
386
+ reasoning_effort=reasoning_effort,
387
+ web_search_enabled=web_search,
388
+ show_in_chat=False if hide_from_chat else None,
389
+ organisation_id=org_headers.get(ORG_HEADER),
390
+ )
391
+ if dry_run:
392
+ click.echo(json_dumps({"url": runtime.backend.build_websocket_url(WS_PATH), "frame": frame}))
393
+ return
394
+
395
+ url = runtime.backend.build_websocket_url(WS_PATH)
396
+ headers = {**_cookie_header(runtime), **org_headers}
397
+ if "Cookie" not in headers:
398
+ raise click.ClickException("No session cookies for this profile. Run `deliberaide-cli auth login` first.")
399
+
400
+ def on_frame(event: dict[str, Any]) -> None:
401
+ if not stream:
402
+ return
403
+ if runtime.json_output:
404
+ click.echo(json_dumps({"frame": event}, compact=True))
405
+ else:
406
+ _human_frame_printer(click.echo)(event)
407
+
408
+ with websocket_connect(url, additional_headers=headers, open_timeout=runtime.profile.timeout_seconds) as websocket:
409
+ result = run_chat_turn(
410
+ websocket,
411
+ frame,
412
+ conversation_id=conversation_id,
413
+ timeout_seconds=timeout_seconds,
414
+ ping_interval=ping_interval,
415
+ on_frame=on_frame,
416
+ )
417
+
418
+ envelope = {
419
+ "ok": result.ok,
420
+ "operation": "copilot.chat",
421
+ "request": {"method": "WEBSOCKET", "path": WS_PATH, "url": url, "frame": frame},
422
+ "response": {
423
+ "conversation_id": result.conversation_id,
424
+ "message": result.final,
425
+ "error": result.error,
426
+ "timed_out": result.timed_out,
427
+ "frames": result.frames,
428
+ "frame_counts": result.frame_counts,
429
+ "duration_seconds": result.duration_seconds,
430
+ },
431
+ }
432
+ if runtime.json_output:
433
+ click.echo(json_dumps(envelope, compact=True))
434
+ elif not stream:
435
+ click.echo(str((result.final or {}).get("content") or ""))
436
+ if not result.ok:
437
+ if not runtime.json_output:
438
+ reason = "timed out" if result.timed_out else json_dumps(result.error or {}, compact=True)
439
+ click.echo(f"Co-Pilot turn did not finish: {reason}", err=True)
440
+ raise SystemExit(1)
441
+
442
+ @click.command("wait")
443
+ @click.option("--conversation-id", required=True)
444
+ @click.option("--after", default=None, help="ISO timestamp; only answers created after it count. Defaults to the latest user message.")
445
+ @click.option("--x-organisation-id", default=None)
446
+ @click.option("--timeout-seconds", type=float, default=900.0, show_default=True)
447
+ @click.option("--interval", type=float, default=15.0, show_default=True)
448
+ @click.pass_obj
449
+ def copilot_wait(
450
+ runtime: Any,
451
+ conversation_id: str,
452
+ after: str | None,
453
+ x_organisation_id: str | None,
454
+ timeout_seconds: float,
455
+ interval: float,
456
+ ) -> None:
457
+ """Poll a conversation until a non-interim assistant message arrives (for turns started over HTTP)."""
458
+ headers = _org_header(runtime, x_organisation_id)
459
+ deadline = time.monotonic() + timeout_seconds
460
+ while True:
461
+ response = runtime.backend.request(
462
+ "GET", f"/api/v1/copilot/conversations/{conversation_id}/messages", params={"limit": 200}, headers=headers
463
+ )
464
+ if not response.is_success:
465
+ raise click.ClickException(f"GET messages failed: HTTP {response.status_code} {response.text[:200]}")
466
+ body = response.json()
467
+ messages = body if isinstance(body, list) else (body.get("items") or body.get("messages") or [])
468
+ message = select_terminal_message(messages, after=after)
469
+ if message is not None:
470
+ envelope = {"ok": True, "operation": "copilot.wait", "response": {"conversation_id": conversation_id, "message": message}}
471
+ click.echo(json_dumps(envelope, compact=True) if runtime.json_output else str(message.get("content") or ""))
472
+ return
473
+ if time.monotonic() >= deadline:
474
+ if runtime.json_output:
475
+ click.echo(json_dumps({"ok": False, "operation": "copilot.wait", "response": {"conversation_id": conversation_id, "message": None, "timed_out": True}}, compact=True))
476
+ else:
477
+ click.echo("No terminal assistant message yet.", err=True)
478
+ raise SystemExit(1)
479
+ time.sleep(interval)
480
+
481
+ group.add_command(copilot_chat)
482
+ group.add_command(copilot_wait)
@@ -1 +1 @@
1
- """Core helpers for deliberaide-cli."""
1
+ """Core helpers for deliberaide-cli."""
@@ -158,4 +158,4 @@ class RouteManifest:
158
158
  def load_manifest() -> RouteManifest:
159
159
  manifest_path = files("deliberaide_cli").joinpath("route_manifest.json")
160
160
  payload = json.loads(manifest_path.read_text(encoding="utf-8"))
161
- return RouteManifest.from_dict(payload)
161
+ return RouteManifest.from_dict(payload)