formist-cli 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.
formist_cli/chat.py ADDED
@@ -0,0 +1,618 @@
1
+ """``fm chat``: an interactive REPL against the server-side agent.
2
+
3
+ ``fm chats`` (plural) reads history: it lists a space's chats and
4
+ prints a transcript. This module is the other half: it posts a turn
5
+ and streams the reply as it arrives, over the same route the browser
6
+ chat uses (an SSE endpoint). Fetching a chat and paging its transcript
7
+ are reused from :mod:`formist_cli.chats`, not re-implemented here.
8
+
9
+ Scope is the same as ``fm chats``: this command can continue a chat
10
+ the current session owns, or start a new one (always user-owned). It
11
+ cannot open another member's private chat, and it cannot run a turn
12
+ on a workspace chat someone else's automation created; those requests
13
+ are rejected server-side. There is no resolve-by-title, since chat
14
+ titles are auto-generated and duplicate heavily.
15
+
16
+ Token events are best-effort; the persisted final message is
17
+ authoritative. A dropped connection mid-run can leave the terminal
18
+ holding a partial reply with no visible sign that it is partial, so
19
+ this module tracks whether a terminal event
20
+ (``on_agent_run_completed`` / ``on_agent_run_failed``) was actually
21
+ seen (:class:`TurnState`) and says so loudly
22
+ (:func:`render_incomplete`) when the stream ends without one.
23
+
24
+ ``parse_sse`` is reused from :mod:`formist_cli.logs` rather than
25
+ re-implemented, since it already handles the one hazard that matters
26
+ here: a multi-line SSE ``data:`` field is only complete once its
27
+ terminating blank line arrives.
28
+
29
+ Stdlib only: this module must not add a runtime dependency.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import io
35
+ import json
36
+ import sys
37
+ from collections.abc import Callable, Iterable, Iterator, Sequence
38
+ from dataclasses import dataclass, field
39
+ from typing import Any
40
+
41
+ from formist_cli import api
42
+ from formist_cli.chats import ChatsError, fetch_messages, get_chat
43
+ from formist_cli.logs import OUT, STATE, Kind, parse_sse
44
+ from formist_cli.targets import Target, require_space_id
45
+
46
+ #: The two events that end a run. Seeing one is the only way to tell
47
+ #: "the turn finished" from "the connection stopped handing us bytes".
48
+ TERMINAL_EVENTS = frozenset({"on_agent_run_completed", "on_agent_run_failed"})
49
+
50
+ #: SSE read timeout for one interactive turn. Sized generously: the
51
+ #: endpoint pings periodically, but a turn can also sit silent for a
52
+ #: long tool call (a search, a document read) with nothing on the
53
+ #: wire in between, and that silence is not a sign of anything wrong.
54
+ READ_TIMEOUT = 300.0
55
+
56
+ #: SSE read timeout for ``fm chat --message``, effectively unbounded.
57
+ #: A real agent run can take an hour, and the server ends the run the
58
+ #: moment this client's socket disconnects, so a timeout sized for an
59
+ #: interactive turn would abort a run that was working fine. Large
60
+ #: but finite because Python's socket layer rejects an actual
61
+ #: infinite float.
62
+ NON_INTERACTIVE_READ_TIMEOUT = 6 * 60 * 60.0
63
+
64
+ #: How much of one tool call's arguments to keep. They are
65
+ #: identifiers (a file id, a path, a search query), not results, so
66
+ #: this adds nothing new in kind to what a run record already
67
+ #: carries. The cap exists because one tool's arguments are not an
68
+ #: identifier at all: a reported-feedback screenshot can carry a
69
+ #: data-url image, and an unbounded capture would put a megabyte of
70
+ #: it in every record.
71
+ TOOL_ARG_CAP = 300
72
+
73
+ #: Events whose payload carries the resolved model and run id.
74
+ #: ``on_agent_run_started`` reaches this stream only on a retry, so a
75
+ #: run that never retried learns its model from the message or the
76
+ #: terminal event instead.
77
+ _MODEL_BEARING_EVENTS = frozenset({
78
+ "on_agent_run_started", "on_chat_message", "on_agent_run_completed",
79
+ })
80
+
81
+ StreamOpener = Callable[..., Any]
82
+ Poster = Callable[..., Any]
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class ToolCall:
87
+ """One tool invocation: what was called, and on what.
88
+
89
+ ``args`` is the JSON the server sent on the tool-start event,
90
+ truncated to :data:`TOOL_ARG_CAP`. It is the argument, never the
91
+ result, since the result can be the customer's own document
92
+ text.
93
+ """
94
+
95
+ tool: str
96
+ args: str
97
+
98
+ def identifier(self) -> str | None:
99
+ """The id or path this call names, if it names one.
100
+
101
+ Returns ``None`` rather than a guess: a tool whose arguments
102
+ carry no identifier (a search query, say) must not be
103
+ reported as having opened something.
104
+ """
105
+ import json as _json
106
+
107
+ try:
108
+ parsed = _json.loads(self.args)
109
+ except ValueError:
110
+ return None
111
+ if not isinstance(parsed, dict):
112
+ return None
113
+ for key in ("file_id", "path", "id", "file", "document_id"):
114
+ value = parsed.get(key)
115
+ if isinstance(value, str) and value.strip():
116
+ return value.strip()
117
+ return None
118
+
119
+
120
+ @dataclass
121
+ class TurnState:
122
+ """One user turn's outcome, mutated in place as :func:`consume_turn`
123
+ drains the SSE: a caller that stops draining early (a dropped
124
+ connection, a KeyboardInterrupt) still needs an accurate record of
125
+ what happened before that.
126
+ """
127
+
128
+ chat_id: str
129
+ #: Whether any ``on_agent_token`` delta was printed for the run
130
+ #: currently in progress (reset on a retry, see :func:`consume_turn`).
131
+ printed_any_token: bool = False
132
+ #: True only once a member of TERMINAL_EVENTS was actually seen.
133
+ terminal_seen: bool = False
134
+ status: str | None = None
135
+ error: str | None = None
136
+ #: The model the server said it ran, off ``on_agent_run_started``.
137
+ #: Not the model that was asked for: the server falls back
138
+ #: silently for an id it does not recognise, so reporting the
139
+ #: requested id would report a value nobody measured. None until
140
+ #: the server states one.
141
+ model: str | None = None
142
+ #: The server's id for this run, so a line in a report can be
143
+ #: found again in the server's own logs (``fm logs --run <id>``).
144
+ run_id: str | None = None
145
+ #: Tokens the run reported. ``usage_measured`` is the server's own
146
+ #: measured flag, and is the whole point of carrying these: the
147
+ #: server emits 0/0 for a backend that reports nothing, and "0
148
+ #: tokens" and "unknown tokens" are different facts. None until
149
+ #: the server states one.
150
+ input_tokens: int | None = None
151
+ output_tokens: int | None = None
152
+ usage_measured: bool | None = None
153
+ #: The attachment chips the assistant message carries, the files
154
+ #: this run produced. Read off ``on_chat_message``, which carries
155
+ #: the same list the server persists, so it costs no second
156
+ #: request.
157
+ #:
158
+ #: ``None`` means the event never arrived (a dropped stream) and
159
+ #: ``[]`` means it arrived carrying none; those are different
160
+ #: facts.
161
+ attachments: list[dict] | None = None
162
+ #: Every tool call this run made, in order, with its arguments.
163
+ #: Populated from the tool-start event, which already carries
164
+ #: ``args``, so this needs no server change.
165
+ tool_calls: list[ToolCall] = field(default_factory=list)
166
+ #: The exact concatenation of every OUT-kind chunk this run
167
+ #: printed (streamed tokens, or the assistant-message fallback
168
+ #: when none streamed), populated by :func:`run_turn`. This is
169
+ #: ``fm chat --message``'s only way to report the reply in
170
+ #: ``--json``.
171
+ final_text: str = ""
172
+
173
+ @property
174
+ def total_tokens(self) -> int | None:
175
+ """Tokens this run is known to have spent, or None when unknowable."""
176
+ if not self.usage_measured:
177
+ return None
178
+ return (self.input_tokens or 0) + (self.output_tokens or 0)
179
+
180
+
181
+ def consume_turn(state: TurnState, records: Iterable[dict]) -> Iterator[tuple[Kind, str]]:
182
+ """Drive one turn's parsed SSE records into printable ``(kind, text)`` pairs.
183
+
184
+ ``OUT`` is the assistant's own words, meant for stdout, streamed
185
+ as they arrive. ``STATE`` is everything else (tool calls, retries,
186
+ errors), meant for stderr, so it never mixes into reply text a
187
+ caller might want to pipe or paste.
188
+
189
+ Stops as soon as a :data:`TERMINAL_EVENTS` member is seen. Whether
190
+ the input ran out without one is left on ``state.terminal_seen``
191
+ for the caller to read once this generator is exhausted.
192
+ """
193
+ for record in records:
194
+ if state.terminal_seen:
195
+ return
196
+ name = record.get("event")
197
+ data = record.get("data")
198
+ payload = data if isinstance(data, dict) else {}
199
+
200
+ # Recorded off whichever event states them, before any branch
201
+ # can return. The resolved model is not knowable any other
202
+ # way from the client, since the server falls back silently
203
+ # for an id it does not recognise. ``on_agent_usage`` is
204
+ # deliberately not one of these events, because its own
205
+ # `model` is what the provider reported for the call, a
206
+ # different fact with the same key.
207
+ if name in _MODEL_BEARING_EVENTS:
208
+ state.model = payload.get("model") or state.model
209
+ state.run_id = payload.get("run_id") or state.run_id
210
+
211
+ if name == "on_agent_token":
212
+ delta = payload.get("delta")
213
+ if delta:
214
+ state.printed_any_token = True
215
+ yield (OUT, delta)
216
+
217
+ elif name == "on_agent_run_started":
218
+ if payload.get("retry_attempt"):
219
+ # A retry re-announces run_started, meaning every
220
+ # token streamed so far belongs to an abandoned
221
+ # attempt. A terminal cannot un-print what already
222
+ # scrolled by, so this marks the seam instead of
223
+ # silently gluing the retried reply onto the stale
224
+ # one.
225
+ state.printed_any_token = False
226
+ reason = payload.get("reason") or "rate limited"
227
+ yield (STATE, f"\n[retrying: {reason}]")
228
+
229
+ elif name == "on_agent_usage":
230
+ # Recorded, not printed. `measured` is carried verbatim: a
231
+ # False here means the backend reported nothing, not that
232
+ # the run was free.
233
+ state.input_tokens = payload.get("input_tokens")
234
+ state.output_tokens = payload.get("output_tokens")
235
+ state.usage_measured = payload.get("measured")
236
+
237
+ elif name == "on_agent_tool_start":
238
+ # Recorded structurally; the printed line is unchanged, so
239
+ # `fm chat`'s output and anything parsing that trace keep
240
+ # working.
241
+ state.tool_calls.append(ToolCall(
242
+ tool=str(payload.get("tool") or "?"),
243
+ args=json.dumps(payload.get("args"), default=str)[:TOOL_ARG_CAP],
244
+ ))
245
+ yield (STATE, f" -> {payload.get('tool') or '?'}")
246
+
247
+ elif name == "on_agent_tool_end":
248
+ mark = "ok" if payload.get("ok") else "ERROR"
249
+ yield (STATE, f" <- {payload.get('tool') or '?'} {mark}")
250
+
251
+ elif name == "on_chat_message" and payload.get("role") == "ASSISTANT":
252
+ # The attachment chips, captured before the printing
253
+ # branch below: they must be recorded whether or not the
254
+ # tokens already streamed.
255
+ raw_attachments = payload.get("attachments")
256
+ state.attachments = (
257
+ [a for a in raw_attachments if isinstance(a, dict)]
258
+ if isinstance(raw_attachments, list) else []
259
+ )
260
+ # The authoritative final text, which the server persists
261
+ # exactly. Tokens are best-effort, so this is the
262
+ # fallback for a run that streamed none (a non-streaming
263
+ # backend, or a retry that landed with no further
264
+ # deltas); printed only then, so a real answer is never
265
+ # silently missing, and never duplicated when the deltas
266
+ # already showed it.
267
+ if not state.printed_any_token:
268
+ content = payload.get("content") or ""
269
+ if content:
270
+ yield (OUT, content)
271
+
272
+ elif name in TERMINAL_EVENTS:
273
+ state.terminal_seen = True
274
+ if name == "on_agent_run_failed":
275
+ state.status = "FAILED"
276
+ state.error = payload.get("error")
277
+ yield (STATE, f"\n[error] {state.error}")
278
+ else:
279
+ state.status = payload.get("status") or "COMPLETED"
280
+ if state.status == "CANCELLED":
281
+ yield (STATE, "\n[cancelled]")
282
+
283
+
284
+ def render_incomplete(state: TurnState) -> str:
285
+ """Render the warning for an SSE input that ended without a terminal event.
286
+
287
+ Never say a turn finished on the strength of nothing more
288
+ arriving: that is exactly as true of a connection that just died
289
+ as of one that ended tidily.
290
+ """
291
+ return (
292
+ f"chat {state.chat_id}: the stream ended without the server "
293
+ "confirming this turn finished (no on_agent_run_completed / "
294
+ "on_agent_run_failed arrived); the reply above may be PARTIAL.\n"
295
+ f"Run `fm chats {state.chat_id} --messages` to read what was actually "
296
+ "persisted."
297
+ )
298
+
299
+
300
+ def build_run_body(
301
+ content: str,
302
+ *,
303
+ model: str | None = None,
304
+ effort: str | None = None,
305
+ attachments: Sequence[dict] | None = None,
306
+ ) -> dict:
307
+ """Build the POST body for ``/chats/{id}/run``.
308
+
309
+ Only ``content`` is required. ``model``/``effort``/``attachments``
310
+ ride along only when the operator asked for them: an unset flag
311
+ reaches the server as an absent field, so its own default
312
+ applies, never an explicit ``null``.
313
+
314
+ ``attachments`` is the same list the browser sends when a person
315
+ drops an image into the chat. It is passed through verbatim
316
+ rather than reshaped here, since composing a second attachment
317
+ encoder here would test something other than the product's own.
318
+
319
+ An empty list is dropped, not sent: ``[]`` and "absent" mean the
320
+ same thing to the server, and sending ``[]`` would make a
321
+ text-only turn look, in a server log, like one that carried
322
+ attachments and lost them.
323
+ """
324
+ body: dict = {"content": content}
325
+ if model:
326
+ body["model"] = model
327
+ if effort:
328
+ body["effort"] = effort
329
+ if attachments:
330
+ body["attachments"] = list(attachments)
331
+ return body
332
+
333
+
334
+ def create_chat(
335
+ target: Target,
336
+ space: str,
337
+ *,
338
+ token: str | None,
339
+ model: str | None = None,
340
+ post: Poster | None = None,
341
+ ) -> dict:
342
+ """Start a new chat (``POST /projects/{id}/chats``) and return it.
343
+
344
+ No ``title`` is sent: chat titles are auto-generated, and this
345
+ command always addresses the chat it just created by the id
346
+ handed back, never by a title.
347
+ """
348
+ space = require_space_id(space)
349
+ post = post or api.post
350
+ body: dict = {}
351
+ if model:
352
+ body["model"] = model
353
+ chat = post(target, f"/projects/{space}/chats", body, token=token)
354
+ if not isinstance(chat, dict) or not chat.get("id"):
355
+ raise ChatsError(
356
+ f"POST /projects/{space}/chats returned no chat id (got {chat!r})."
357
+ )
358
+ return chat
359
+
360
+
361
+ def run_turn(
362
+ target: Target,
363
+ space: str,
364
+ chat_id: str,
365
+ content: str,
366
+ *,
367
+ token: str | None,
368
+ model: str | None = None,
369
+ effort: str | None = None,
370
+ attachments: Sequence[dict] | None = None,
371
+ stream_fn: StreamOpener | None = None,
372
+ out: Any = None,
373
+ err: Any = None,
374
+ read_timeout: float | None = None,
375
+ ) -> TurnState:
376
+ """POST one user turn and print the reply as it streams. Returns the outcome.
377
+
378
+ Printing lives here, not one layer up in the REPL loop, since the
379
+ property this module exists for (a dropped or partial SSE input
380
+ must not read as a finished turn) belongs to consuming the
381
+ stream. Keeping it here also lets a test drive canned SSE text
382
+ through the same path the REPL uses, with no terminal involved.
383
+
384
+ ``out``/``err`` default to ``None`` and are resolved to
385
+ ``sys.stdout`` / ``sys.stderr`` inside the call, not in the
386
+ signature, so a test fixture that swaps either stream for the
387
+ duration of one call still takes effect.
388
+ """
389
+ out = sys.stdout if out is None else out
390
+ err = sys.stderr if err is None else err
391
+ space = require_space_id(space)
392
+ stream_fn = stream_fn or api.stream_post
393
+ path = f"/projects/{space}/chats/{chat_id}/run"
394
+ body = build_run_body(content, model=model, effort=effort, attachments=attachments)
395
+ state = TurnState(chat_id=chat_id)
396
+
397
+ try:
398
+ timeout = READ_TIMEOUT if read_timeout is None else read_timeout
399
+ with stream_fn(target, path, body, token=token, read_timeout=timeout) as lines:
400
+ for kind, text in consume_turn(state, parse_sse(lines)):
401
+ if kind is OUT:
402
+ print(text, end="", flush=True, file=out)
403
+ state.final_text += text
404
+ else:
405
+ print(text, file=err, flush=True)
406
+ except api.StreamClosed as exc:
407
+ print(f"\nerror: {exc}", file=err)
408
+
409
+ print(file=out) # the reply always ends its own line, however the run ended
410
+ if not state.terminal_seen:
411
+ print(render_incomplete(state), file=err)
412
+ return state
413
+
414
+
415
+ # ===========================================================================
416
+ # The CLI surface. One `add_parser` per module.
417
+ # ===========================================================================
418
+ def _print_context(target: Target, space: str, chat_id: str, *, token: str | None) -> None:
419
+ """Print what `fm chat <id>` shows before the first prompt.
420
+
421
+ Reuses :mod:`formist_cli.chats`' own reader rather than a second
422
+ one: the 404 it can raise here already explains the chat-privacy
423
+ rule, and the transcript it prints already carries its own
424
+ completeness warning if the space's history exceeds one page.
425
+ """
426
+ chat = get_chat(target, space, chat_id, token=token)
427
+ print(
428
+ f"{chat.get('id')} {chat.get('kind', '?')} {chat.get('title') or ''}",
429
+ file=sys.stderr,
430
+ )
431
+ transcript = fetch_messages(target, space, chat_id, token=token)
432
+ print(transcript.render(), file=sys.stderr)
433
+ print(file=sys.stderr)
434
+
435
+
436
+ def _repl(
437
+ target: Target,
438
+ space: str,
439
+ chat_id: str,
440
+ *,
441
+ token: str | None,
442
+ model: str | None,
443
+ effort: str | None,
444
+ input_fn: Callable[[str], str] = input,
445
+ stream_fn: StreamOpener | None = None,
446
+ ) -> int:
447
+ print(
448
+ f"fm chat: {chat_id} ({target.name})\n"
449
+ "type a message and press enter; Ctrl-D or /exit to quit",
450
+ file=sys.stderr,
451
+ )
452
+ while True:
453
+ try:
454
+ line = input_fn("you> ")
455
+ except EOFError:
456
+ print(file=sys.stderr)
457
+ break
458
+ text = line.strip()
459
+ if not text:
460
+ continue
461
+ if text in ("/exit", "/quit"):
462
+ break
463
+ print("fm> ", end="", flush=True)
464
+ try:
465
+ run_turn(
466
+ target,
467
+ space,
468
+ chat_id,
469
+ text,
470
+ token=token,
471
+ model=model,
472
+ effort=effort,
473
+ stream_fn=stream_fn,
474
+ )
475
+ except KeyboardInterrupt:
476
+ print("\n[interrupted]", file=sys.stderr)
477
+ return 0
478
+
479
+
480
+ def add_parser(sub) -> None:
481
+ import argparse
482
+
483
+ from formist_cli.cli import _add_env, _add_space
484
+
485
+ p = sub.add_parser(
486
+ "chat",
487
+ help="interactive REPL against the server-side agent (WRITE)",
488
+ description=(
489
+ "Opens an interactive conversation with the server-side agent, "
490
+ "the same one the browser chat runs, over an SSE endpoint. Give "
491
+ "a chat id to continue that conversation (its recent transcript "
492
+ "prints first, via `fm chats`' own reader); omit it to start a "
493
+ "new one.\n\n"
494
+ "Scope is the same as `fm chats` (this reuses its transport and "
495
+ "its privacy rule, not a second one): you can only continue a "
496
+ "chat you may read under the member route, your own chats plus "
497
+ "workspace-scoped ones your role can see, and only run a turn "
498
+ "on a chat you own (a workspace chat is read-only). A "
499
+ "background run someone else triggered is invisible here too, "
500
+ "on purpose; the API never reveals that it exists. There is no "
501
+ "resolve-by-title: chat titles are auto-generated and "
502
+ "duplicate heavily.\n\n"
503
+ "This creates chats, spends the project's agent quota and "
504
+ "persists real messages, so, like `fm upload` / `fm update`, "
505
+ "the target is never inherited from `fm use`: pass --env (or "
506
+ "--host) explicitly.\n\n"
507
+ "--message TEXT switches to non-interactive mode: sends "
508
+ "exactly this one turn (creating a chat first if no id was "
509
+ "given), streams it compactly (assistant text on stdout, one "
510
+ "line per tool call on stderr), and exits when the run "
511
+ "finishes, no REPL, no prompt. The HTTP stream is held open "
512
+ "for the whole run with no meaningful read timeout, because "
513
+ "the server ends the run the moment this client disconnects "
514
+ "and a real run can take an hour. Exit code is non-zero if "
515
+ "the run failed (on_agent_run_failed) or the stream ended "
516
+ "without a terminal event. --json then prints one final "
517
+ "summary object instead of streaming to the terminal: "
518
+ "{chat_id, tool_calls, failed, final_message}."
519
+ ),
520
+ formatter_class=argparse.RawDescriptionHelpFormatter,
521
+ )
522
+ _add_env(p, for_write=True)
523
+ _add_space(p)
524
+ p.add_argument(
525
+ "chat_id", nargs="?", help="continue this chat (UUID); omit to start a new one"
526
+ )
527
+ p.add_argument("--model", default=None, help="override the chat's model for this run")
528
+ p.add_argument(
529
+ "--effort", default=None, help="low|medium|high|xhigh (ignored by models with no knob)"
530
+ )
531
+ p.add_argument(
532
+ "--message", default=None, metavar="TEXT",
533
+ help="send this one message non-interactively and exit when the run "
534
+ "finishes, instead of opening the REPL",
535
+ )
536
+ p.add_argument(
537
+ "--json", action="store_true",
538
+ help="with --message: print a final summary "
539
+ "{chat_id, tool_calls, failed, final_message} instead of streaming",
540
+ )
541
+
542
+
543
+ def cmd_chat(args) -> int:
544
+ """Resolve or create the chat, then either run the REPL or, with
545
+ ``--message``, run exactly one non-interactive turn and exit."""
546
+ from formist_cli import context
547
+
548
+ eff = context.resolve(args, for_write=True, need_space=True, need_token=True)
549
+ token = eff.token
550
+ chat_id = args.chat_id
551
+
552
+ if getattr(args, "message", None):
553
+ return _run_message(eff.target, eff.space, chat_id, args.message, token=token, args=args)
554
+
555
+ if chat_id:
556
+ _print_context(eff.target, eff.space, chat_id, token=token)
557
+ else:
558
+ chat = create_chat(eff.target, eff.space, token=token, model=args.model)
559
+ chat_id = str(chat.get("id"))
560
+ print(f" started new chat {chat_id}", file=sys.stderr)
561
+
562
+ return _repl(
563
+ eff.target, eff.space, chat_id, token=token, model=args.model, effort=args.effort
564
+ )
565
+
566
+
567
+ def _run_message(
568
+ target: Target, space: str, chat_id: str | None, content: str, *, token: str | None, args
569
+ ) -> int:
570
+ """Run one turn non-interactively, held open for however long the
571
+ run actually takes (see :data:`NON_INTERACTIVE_READ_TIMEOUT`).
572
+
573
+ No REPL banner and no transcript print: this mode is for
574
+ scripting, and exits with a status that says whether the run
575
+ worked.
576
+
577
+ ``--json`` prints exactly one object and nothing else on stdout:
578
+ the streamed assistant text is captured into an in-memory buffer
579
+ instead of being written live, so a caller parsing stdout as JSON
580
+ never has to split it away from text that would otherwise have
581
+ printed ahead of it. Tool-call lines still go to stderr either
582
+ way, since they are diagnostics, not part of the ``--json``
583
+ contract.
584
+ """
585
+ if not chat_id:
586
+ chat = create_chat(target, space, token=token, model=args.model)
587
+ chat_id = str(chat.get("id"))
588
+ print(f" started new chat {chat_id}", file=sys.stderr)
589
+
590
+ as_json = bool(getattr(args, "json", False))
591
+ captured_out = io.StringIO() if as_json else None
592
+
593
+ state = run_turn(
594
+ target,
595
+ space,
596
+ chat_id,
597
+ content,
598
+ token=token,
599
+ model=args.model,
600
+ effort=args.effort,
601
+ read_timeout=NON_INTERACTIVE_READ_TIMEOUT,
602
+ out=captured_out,
603
+ )
604
+
605
+ failed = state.status == "FAILED"
606
+ incomplete = not state.terminal_seen
607
+
608
+ if as_json:
609
+ print(json.dumps(
610
+ {
611
+ "chat_id": chat_id,
612
+ "tool_calls": len(state.tool_calls),
613
+ "failed": failed,
614
+ "final_message": state.final_text,
615
+ },
616
+ indent=2, ensure_ascii=False,
617
+ ))
618
+ return 1 if (failed or incomplete) else 0