xiii-cli-core 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.
- xiii_cli_core/__init__.py +1 -0
- xiii_cli_core/client.py +568 -0
- xiii_cli_core/config.py +527 -0
- xiii_cli_core/describe.py +196 -0
- xiii_cli_core/direct.py +1158 -0
- xiii_cli_core/errors.py +103 -0
- xiii_cli_core/main.py +732 -0
- xiii_cli_core/oauth.py +750 -0
- xiii_cli_core/openapi.py +643 -0
- xiii_cli_core/py.typed +0 -0
- xiii_cli_core/render.py +44 -0
- xiii_cli_core/skill.py +89 -0
- xiii_cli_core/thread.py +230 -0
- xiii_cli_core/tokens.py +115 -0
- xiii_cli_core-0.1.0.dist-info/METADATA +86 -0
- xiii_cli_core-0.1.0.dist-info/RECORD +18 -0
- xiii_cli_core-0.1.0.dist-info/WHEEL +4 -0
- xiii_cli_core-0.1.0.dist-info/licenses/LICENSE +202 -0
xiii_cli_core/main.py
ADDED
|
@@ -0,0 +1,732 @@
|
|
|
1
|
+
import getpass
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
import time
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Annotated, Any
|
|
9
|
+
from uuid import uuid4
|
|
10
|
+
|
|
11
|
+
from cyclopts import App, CycloptsError, Group, Parameter
|
|
12
|
+
from rich.console import Console
|
|
13
|
+
from rich.markup import escape
|
|
14
|
+
from rich.prompt import Confirm
|
|
15
|
+
|
|
16
|
+
from xiii_cli_core.client import ApiClient
|
|
17
|
+
from xiii_cli_core.config import (
|
|
18
|
+
Product,
|
|
19
|
+
ProductConfig,
|
|
20
|
+
Surface,
|
|
21
|
+
WorkspaceRef,
|
|
22
|
+
delete_token,
|
|
23
|
+
forget_workspace,
|
|
24
|
+
known_workspaces,
|
|
25
|
+
match_workspace,
|
|
26
|
+
product_config,
|
|
27
|
+
remember_workspace,
|
|
28
|
+
require_explicit_secret_endpoint,
|
|
29
|
+
resolve_workspace,
|
|
30
|
+
set_active_workspace,
|
|
31
|
+
store_token,
|
|
32
|
+
)
|
|
33
|
+
from xiii_cli_core.describe import register_describe_command
|
|
34
|
+
from xiii_cli_core.direct import (
|
|
35
|
+
HTTP_METHODS,
|
|
36
|
+
JSON_HELP,
|
|
37
|
+
register_module_commands,
|
|
38
|
+
run_raw_api,
|
|
39
|
+
)
|
|
40
|
+
from xiii_cli_core.errors import CliError, UsageError
|
|
41
|
+
from xiii_cli_core.oauth import (
|
|
42
|
+
DEFAULT_LOGIN_TIMEOUT,
|
|
43
|
+
browser_is_available,
|
|
44
|
+
run_browser_login,
|
|
45
|
+
run_device_login,
|
|
46
|
+
)
|
|
47
|
+
from xiii_cli_core.render import render_json
|
|
48
|
+
from xiii_cli_core.skill import register_skill_commands
|
|
49
|
+
from xiii_cli_core.thread import (
|
|
50
|
+
assert_expectations,
|
|
51
|
+
assistant_text,
|
|
52
|
+
latest_interrupt,
|
|
53
|
+
summarize_run,
|
|
54
|
+
write_artifacts,
|
|
55
|
+
)
|
|
56
|
+
from xiii_cli_core.tokens import get_token
|
|
57
|
+
|
|
58
|
+
console = Console()
|
|
59
|
+
error_console = Console(stderr=True)
|
|
60
|
+
JsonOption = Annotated[bool, Parameter(name="--json", help=JSON_HELP)]
|
|
61
|
+
YesOption = Annotated[
|
|
62
|
+
bool,
|
|
63
|
+
Parameter(
|
|
64
|
+
name="--yes",
|
|
65
|
+
negative=(),
|
|
66
|
+
help="Skip the confirmation prompt for non-interactive automation.",
|
|
67
|
+
),
|
|
68
|
+
]
|
|
69
|
+
DryRunOption = Annotated[
|
|
70
|
+
bool,
|
|
71
|
+
Parameter(
|
|
72
|
+
name="--dry-run",
|
|
73
|
+
negative=(),
|
|
74
|
+
help="Show the local operation without changing state.",
|
|
75
|
+
),
|
|
76
|
+
]
|
|
77
|
+
connection_options = Group("Connection options", sort_key=0)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@Parameter(name="*", group=connection_options)
|
|
81
|
+
@dataclass(frozen=True)
|
|
82
|
+
class ConnectionOptions:
|
|
83
|
+
"""Connection settings shared only by commands that call the product API."""
|
|
84
|
+
|
|
85
|
+
api_url: Annotated[
|
|
86
|
+
str | None,
|
|
87
|
+
Parameter(help="Override the product API URL for this invocation."),
|
|
88
|
+
] = None
|
|
89
|
+
config_file: Annotated[
|
|
90
|
+
Path | None,
|
|
91
|
+
Parameter(
|
|
92
|
+
name="--config",
|
|
93
|
+
help=(
|
|
94
|
+
"Use this TOML project config instead of searching for the "
|
|
95
|
+
"product's project file."
|
|
96
|
+
),
|
|
97
|
+
),
|
|
98
|
+
] = None
|
|
99
|
+
workspace: Annotated[
|
|
100
|
+
str | None,
|
|
101
|
+
Parameter(
|
|
102
|
+
name="--workspace",
|
|
103
|
+
help=(
|
|
104
|
+
"Act as this workspace (name or id) for this invocation, "
|
|
105
|
+
"overriding the one `workspace use` selected."
|
|
106
|
+
),
|
|
107
|
+
),
|
|
108
|
+
] = None
|
|
109
|
+
timeout: Annotated[
|
|
110
|
+
float | None,
|
|
111
|
+
Parameter(
|
|
112
|
+
# Not --timeout: `login --timeout` already bounds the consent wait.
|
|
113
|
+
name="--request-timeout",
|
|
114
|
+
help=(
|
|
115
|
+
"Seconds to wait for each API request (default 15, or the "
|
|
116
|
+
"<PRODUCT>_TIMEOUT environment variable)."
|
|
117
|
+
),
|
|
118
|
+
),
|
|
119
|
+
] = None
|
|
120
|
+
|
|
121
|
+
def resolve(self, product: Product, surface: Surface) -> ProductConfig:
|
|
122
|
+
return product_config(
|
|
123
|
+
product,
|
|
124
|
+
surface=surface,
|
|
125
|
+
api_url=self.api_url,
|
|
126
|
+
config_file=self.config_file,
|
|
127
|
+
workspace=self.workspace,
|
|
128
|
+
timeout=self.timeout,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
DEFAULT_CONNECTION_OPTIONS = ConnectionOptions()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def build_app(product: Product, surface: Surface) -> App:
|
|
136
|
+
app = App(
|
|
137
|
+
name=_entrypoint_name(product, surface),
|
|
138
|
+
help=_entrypoint_help(product, surface),
|
|
139
|
+
version=product.version,
|
|
140
|
+
)
|
|
141
|
+
_register_api_commands(app, product, surface)
|
|
142
|
+
module_apps = register_module_commands(
|
|
143
|
+
app,
|
|
144
|
+
product,
|
|
145
|
+
surface,
|
|
146
|
+
connection_type=ConnectionOptions,
|
|
147
|
+
default_connection=DEFAULT_CONNECTION_OPTIONS,
|
|
148
|
+
)
|
|
149
|
+
_register_workspace_selection(app, module_apps, product, surface)
|
|
150
|
+
register_describe_command(app, product)
|
|
151
|
+
register_skill_commands(app, product)
|
|
152
|
+
return app
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _entrypoint_name(product: Product, surface: Surface) -> str:
|
|
156
|
+
if surface is Surface.DEVELOPMENT:
|
|
157
|
+
return f"{product.name}-dev"
|
|
158
|
+
return product.name
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _entrypoint_help(product: Product, surface: Surface) -> str:
|
|
162
|
+
if surface is Surface.DEVELOPMENT:
|
|
163
|
+
return (
|
|
164
|
+
f"{product.display_name} development CLI, defaulting to the local backend."
|
|
165
|
+
)
|
|
166
|
+
return (
|
|
167
|
+
f"{product.display_name} command-line access, defaulting to the production API."
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _register_api_commands(app: App, product: Product, surface: Surface) -> None:
|
|
172
|
+
"""Commands that talk to the product API; shipped on both entrypoints."""
|
|
173
|
+
auth = app.command(App(name="auth", help="Manage PAT authentication."))
|
|
174
|
+
agent = app.command(
|
|
175
|
+
App(name="agent", help="Run the workspace agent from the terminal.")
|
|
176
|
+
)
|
|
177
|
+
app.register_install_completion_command(
|
|
178
|
+
help="Install shell completion for the current shell."
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
@app.command
|
|
182
|
+
def login(
|
|
183
|
+
*,
|
|
184
|
+
connection: ConnectionOptions = DEFAULT_CONNECTION_OPTIONS,
|
|
185
|
+
open_browser: bool = True,
|
|
186
|
+
device: bool | None = None,
|
|
187
|
+
timeout: float = DEFAULT_LOGIN_TIMEOUT,
|
|
188
|
+
) -> None:
|
|
189
|
+
"""Sign in through the browser consent page and store the token.
|
|
190
|
+
|
|
191
|
+
Uses the loopback flow when a browser can reach this machine and the
|
|
192
|
+
device flow (RFC 8628) when it cannot — on a remote shell the redirect
|
|
193
|
+
would land on a port only this host can see. `--device` forces the second
|
|
194
|
+
one, `--no-device` insists on the first.
|
|
195
|
+
"""
|
|
196
|
+
_config = connection.resolve(product, surface)
|
|
197
|
+
require_explicit_secret_endpoint(_config, "the browser login")
|
|
198
|
+
use_device = not browser_is_available() if device is None else device
|
|
199
|
+
if use_device:
|
|
200
|
+
result = run_device_login(
|
|
201
|
+
_config,
|
|
202
|
+
open_browser=open_browser,
|
|
203
|
+
announce=lambda authorization: console.print(
|
|
204
|
+
f"Open [cyan]{escape(authorization.verification_uri)}[/cyan] "
|
|
205
|
+
f"and enter the code [bold]{escape(authorization.user_code)}[/bold]\n"
|
|
206
|
+
"Waiting for approval…"
|
|
207
|
+
),
|
|
208
|
+
)
|
|
209
|
+
else:
|
|
210
|
+
result = run_browser_login(
|
|
211
|
+
_config,
|
|
212
|
+
open_browser=open_browser,
|
|
213
|
+
timeout_seconds=timeout,
|
|
214
|
+
announce=lambda url: console.print(
|
|
215
|
+
f"Opening the consent page:\n[cyan]{escape(url)}[/cyan]"
|
|
216
|
+
if open_browser
|
|
217
|
+
else f"Open the consent page:\n[cyan]{escape(url)}[/cyan]"
|
|
218
|
+
),
|
|
219
|
+
)
|
|
220
|
+
store_token(
|
|
221
|
+
_config,
|
|
222
|
+
result.token,
|
|
223
|
+
result.workspace_id,
|
|
224
|
+
refresh_token=result.refresh_token,
|
|
225
|
+
access_expires_at=(
|
|
226
|
+
time.time() + result.expires_in
|
|
227
|
+
if result.refresh_token is not None
|
|
228
|
+
else None
|
|
229
|
+
),
|
|
230
|
+
)
|
|
231
|
+
with ApiClient(_config, result.token) as client:
|
|
232
|
+
metadata = client.current_api_key()
|
|
233
|
+
workspace = _workspace_ref(client, result.workspace_id)
|
|
234
|
+
# Recorded after the token is stored, so the state file never advertises
|
|
235
|
+
# a workspace whose credential is not actually in the keyring.
|
|
236
|
+
remember_workspace(_config, workspace)
|
|
237
|
+
console.print(
|
|
238
|
+
f"[green]Authenticated[/green] as {escape(str(metadata['token_prefix']))} "
|
|
239
|
+
f"in {escape(workspace.name)} "
|
|
240
|
+
f"(expires {escape(str(metadata['expires_at']))})."
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
@auth.command(name="login")
|
|
244
|
+
def auth_login(
|
|
245
|
+
*, connection: ConnectionOptions = DEFAULT_CONNECTION_OPTIONS
|
|
246
|
+
) -> None:
|
|
247
|
+
"""Verify and store a PAT pasted from the app's API-keys settings."""
|
|
248
|
+
_config = connection.resolve(product, surface)
|
|
249
|
+
require_explicit_secret_endpoint(_config, "a pasted PAT")
|
|
250
|
+
token = getpass.getpass(f"{product.name} PAT: ").strip()
|
|
251
|
+
if not token:
|
|
252
|
+
raise CliError("No token provided")
|
|
253
|
+
with ApiClient(_config, token) as client:
|
|
254
|
+
metadata = client.current_api_key()
|
|
255
|
+
workspace_id = str(metadata.get("workspace_id") or "")
|
|
256
|
+
if not workspace_id:
|
|
257
|
+
raise CliError("API key status did not name a workspace")
|
|
258
|
+
workspace = _workspace_ref(client, workspace_id)
|
|
259
|
+
store_token(_config, token, workspace_id)
|
|
260
|
+
remember_workspace(_config, workspace)
|
|
261
|
+
console.print(
|
|
262
|
+
f"[green]Authenticated[/green] as {escape(str(metadata['token_prefix']))} "
|
|
263
|
+
f"in {escape(workspace.name)} "
|
|
264
|
+
f"(expires {escape(str(metadata['expires_at']))})."
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
@auth.command
|
|
268
|
+
def status(
|
|
269
|
+
*,
|
|
270
|
+
connection: ConnectionOptions = DEFAULT_CONNECTION_OPTIONS,
|
|
271
|
+
json_output: JsonOption = False,
|
|
272
|
+
) -> None:
|
|
273
|
+
"""Verify the active token and list every workspace signed in here.
|
|
274
|
+
|
|
275
|
+
Only the active workspace's token is verified against the API; the
|
|
276
|
+
others are listed from local state, so the command stays one request.
|
|
277
|
+
"""
|
|
278
|
+
_config = connection.resolve(product, surface)
|
|
279
|
+
token, source = get_token(_config)
|
|
280
|
+
active = resolve_workspace(_config)
|
|
281
|
+
with ApiClient(_config, token) as client:
|
|
282
|
+
metadata = client.current_api_key()
|
|
283
|
+
metadata["credential_source"] = source
|
|
284
|
+
metadata["base_url"] = _config.base_url
|
|
285
|
+
metadata["base_url_source"] = _config.base_url_source
|
|
286
|
+
metadata["workspace_source"] = _config.workspace_source
|
|
287
|
+
if active is not None:
|
|
288
|
+
metadata["workspace_name"] = active.name
|
|
289
|
+
metadata["workspaces"] = [
|
|
290
|
+
{
|
|
291
|
+
"id": entry.id,
|
|
292
|
+
"name": entry.name,
|
|
293
|
+
"active": active is not None and entry.id == active.id,
|
|
294
|
+
}
|
|
295
|
+
for entry in known_workspaces(_config)
|
|
296
|
+
]
|
|
297
|
+
if json_output:
|
|
298
|
+
render_json(metadata)
|
|
299
|
+
else:
|
|
300
|
+
workspace_lines = "\n".join(
|
|
301
|
+
f" {'*' if entry['active'] else ' '} "
|
|
302
|
+
f"{escape(entry['name'])} ({escape(entry['id'])})"
|
|
303
|
+
for entry in metadata["workspaces"]
|
|
304
|
+
)
|
|
305
|
+
console.print(
|
|
306
|
+
"[green]Authenticated[/green] "
|
|
307
|
+
+ escape(
|
|
308
|
+
f"{metadata['token_prefix']}\n"
|
|
309
|
+
f"Workspace: "
|
|
310
|
+
f"{metadata.get('workspace_name', metadata['workspace_id'])}"
|
|
311
|
+
f" (from {_config.workspace_source})\n"
|
|
312
|
+
f"Scopes: {', '.join(metadata['scopes'])}\n"
|
|
313
|
+
f"Expires: {metadata['expires_at']}\n"
|
|
314
|
+
f"Source: {source}\n"
|
|
315
|
+
f"API: {_config.base_url}"
|
|
316
|
+
)
|
|
317
|
+
+ (f"\nWorkspaces:\n{workspace_lines}" if workspace_lines else "")
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
@auth.command
|
|
321
|
+
def logout(
|
|
322
|
+
*,
|
|
323
|
+
connection: ConnectionOptions = DEFAULT_CONNECTION_OPTIONS,
|
|
324
|
+
all_workspaces: Annotated[
|
|
325
|
+
bool,
|
|
326
|
+
Parameter(
|
|
327
|
+
name="--all",
|
|
328
|
+
help="Sign out of every workspace, not just the active one.",
|
|
329
|
+
),
|
|
330
|
+
] = False,
|
|
331
|
+
) -> None:
|
|
332
|
+
"""Remove a saved token from the operating-system keyring.
|
|
333
|
+
|
|
334
|
+
Signs out of the active workspace only, so a second workspace stays
|
|
335
|
+
usable — that is the point of holding one token per workspace.
|
|
336
|
+
"""
|
|
337
|
+
_config = connection.resolve(product, surface)
|
|
338
|
+
if all_workspaces:
|
|
339
|
+
targets = known_workspaces(_config)
|
|
340
|
+
else:
|
|
341
|
+
active = resolve_workspace(_config)
|
|
342
|
+
targets = [active] if active is not None else []
|
|
343
|
+
if not targets:
|
|
344
|
+
console.print("No saved OS-keyring token found.")
|
|
345
|
+
return
|
|
346
|
+
removed: list[WorkspaceRef] = []
|
|
347
|
+
for workspace in targets:
|
|
348
|
+
if delete_token(_config, workspace.id):
|
|
349
|
+
removed.append(workspace)
|
|
350
|
+
# Dropped from state either way: an entry whose token is already
|
|
351
|
+
# gone is stale and would only mislead `auth status`.
|
|
352
|
+
forget_workspace(_config, workspace.id)
|
|
353
|
+
if removed:
|
|
354
|
+
names = escape(", ".join(workspace.name for workspace in removed))
|
|
355
|
+
console.print(f"[green]Token removed from OS keyring:[/green] {names}")
|
|
356
|
+
else:
|
|
357
|
+
console.print("No saved OS-keyring token found.")
|
|
358
|
+
|
|
359
|
+
@app.command
|
|
360
|
+
def api(
|
|
361
|
+
endpoint: Annotated[
|
|
362
|
+
str,
|
|
363
|
+
Parameter(
|
|
364
|
+
help="Relative app API path; absolute URLs are rejected.",
|
|
365
|
+
),
|
|
366
|
+
],
|
|
367
|
+
*,
|
|
368
|
+
method: HTTP_METHODS = "GET",
|
|
369
|
+
field: Annotated[
|
|
370
|
+
list[str] | None,
|
|
371
|
+
Parameter(
|
|
372
|
+
name="--field",
|
|
373
|
+
help="Add a typed JSON body field as key=value; repeatable.",
|
|
374
|
+
),
|
|
375
|
+
] = None,
|
|
376
|
+
raw_field: Annotated[
|
|
377
|
+
list[str] | None,
|
|
378
|
+
Parameter(
|
|
379
|
+
name="--raw-field",
|
|
380
|
+
help="Add a string JSON body field as key=value; repeatable.",
|
|
381
|
+
),
|
|
382
|
+
] = None,
|
|
383
|
+
param: Annotated[
|
|
384
|
+
list[str] | None,
|
|
385
|
+
Parameter(
|
|
386
|
+
help="Add a typed query parameter as key=value; repeatable.",
|
|
387
|
+
),
|
|
388
|
+
] = None,
|
|
389
|
+
input_file: Annotated[
|
|
390
|
+
str | None,
|
|
391
|
+
Parameter(
|
|
392
|
+
name="--input",
|
|
393
|
+
help="Read the request body from FILE; use - for stdin.",
|
|
394
|
+
),
|
|
395
|
+
] = None,
|
|
396
|
+
content_type: Annotated[
|
|
397
|
+
str,
|
|
398
|
+
Parameter(help="Content type used with a non-JSON --input body."),
|
|
399
|
+
] = "application/json",
|
|
400
|
+
output: Annotated[
|
|
401
|
+
Path | None,
|
|
402
|
+
Parameter(help="Write the raw response body to FILE."),
|
|
403
|
+
] = None,
|
|
404
|
+
overwrite: Annotated[
|
|
405
|
+
bool,
|
|
406
|
+
Parameter(negative=(), help="Replace an existing --output file."),
|
|
407
|
+
] = False,
|
|
408
|
+
yes: YesOption = False,
|
|
409
|
+
dry_run: DryRunOption = False,
|
|
410
|
+
json_output: JsonOption = False,
|
|
411
|
+
connection: ConnectionOptions = DEFAULT_CONNECTION_OPTIONS,
|
|
412
|
+
) -> None:
|
|
413
|
+
"""Call a PAT-protected app API route not yet covered by a typed command."""
|
|
414
|
+
run_raw_api(
|
|
415
|
+
endpoint=endpoint,
|
|
416
|
+
method=method,
|
|
417
|
+
fields=field or [],
|
|
418
|
+
raw_fields=raw_field or [],
|
|
419
|
+
params=param or [],
|
|
420
|
+
input_file=input_file,
|
|
421
|
+
content_type=content_type,
|
|
422
|
+
output=output,
|
|
423
|
+
overwrite=overwrite,
|
|
424
|
+
yes=yes,
|
|
425
|
+
dry_run=dry_run,
|
|
426
|
+
json_output=json_output,
|
|
427
|
+
connection=connection,
|
|
428
|
+
product=product,
|
|
429
|
+
surface=surface,
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
@agent.command(name="run")
|
|
433
|
+
def run_agent(
|
|
434
|
+
message: str,
|
|
435
|
+
*,
|
|
436
|
+
connection: ConnectionOptions = DEFAULT_CONNECTION_OPTIONS,
|
|
437
|
+
thread_id: str | None = None,
|
|
438
|
+
model: str | None = None,
|
|
439
|
+
json_output: JsonOption = False,
|
|
440
|
+
) -> None:
|
|
441
|
+
"""Run an agent turn; approve every requested write explicitly.
|
|
442
|
+
|
|
443
|
+
Human-readable mode prompts once per pending tool call and can continue
|
|
444
|
+
through chained approval rounds. JSON mode never prompts or approves: an
|
|
445
|
+
interrupted result returns the pending actions for safe automation.
|
|
446
|
+
"""
|
|
447
|
+
_config = connection.resolve(product, surface)
|
|
448
|
+
token, _source = get_token(_config)
|
|
449
|
+
client_message_id = str(uuid4())
|
|
450
|
+
payload = {
|
|
451
|
+
"message": message,
|
|
452
|
+
"client_message_id": client_message_id,
|
|
453
|
+
**({"thread_id": thread_id} if thread_id else {}),
|
|
454
|
+
**({"model": model} if model else {}),
|
|
455
|
+
}
|
|
456
|
+
events: list[dict[str, Any]] = []
|
|
457
|
+
active_thread_id = thread_id
|
|
458
|
+
first_stream = True
|
|
459
|
+
|
|
460
|
+
with ApiClient(_config, token) as client:
|
|
461
|
+
while True:
|
|
462
|
+
batch = list(
|
|
463
|
+
client.stream_agent(payload)
|
|
464
|
+
if first_stream
|
|
465
|
+
else client.resume_agent(active_thread_id or "", payload)
|
|
466
|
+
)
|
|
467
|
+
first_stream = False
|
|
468
|
+
events.extend(batch)
|
|
469
|
+
for event in batch:
|
|
470
|
+
if not json_output and event.get("type") == "MESSAGE_DELTA":
|
|
471
|
+
console.print(
|
|
472
|
+
str(event.get("delta", "")),
|
|
473
|
+
end="",
|
|
474
|
+
markup=False,
|
|
475
|
+
emoji=False,
|
|
476
|
+
highlight=False,
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
summary = summarize_run(events, client_message_id)
|
|
480
|
+
active_thread_id = summary.thread_id or active_thread_id
|
|
481
|
+
interrupt = latest_interrupt(batch)
|
|
482
|
+
if interrupt is None:
|
|
483
|
+
break
|
|
484
|
+
if not active_thread_id:
|
|
485
|
+
raise CliError("Agent approval cannot continue without a thread ID")
|
|
486
|
+
if json_output:
|
|
487
|
+
break
|
|
488
|
+
payload = _prompt_agent_decisions(interrupt)
|
|
489
|
+
|
|
490
|
+
summary = summarize_run(events, client_message_id)
|
|
491
|
+
interrupt = (
|
|
492
|
+
latest_interrupt(events) if summary.status == "interrupted" else None
|
|
493
|
+
)
|
|
494
|
+
result = {
|
|
495
|
+
"status": summary.status,
|
|
496
|
+
"terminal_type": summary.terminal_type,
|
|
497
|
+
"thread_id": summary.thread_id or active_thread_id,
|
|
498
|
+
"message": assistant_text(events),
|
|
499
|
+
"pending_actions": (
|
|
500
|
+
interrupt.get("action_requests", []) if interrupt else []
|
|
501
|
+
),
|
|
502
|
+
}
|
|
503
|
+
if summary.status in {"error", "incomplete"}:
|
|
504
|
+
raise CliError(
|
|
505
|
+
f"Agent run ended with status {summary.status} "
|
|
506
|
+
f"({summary.terminal_type or 'no terminal event'})"
|
|
507
|
+
)
|
|
508
|
+
if json_output:
|
|
509
|
+
render_json(result)
|
|
510
|
+
elif not result["message"]:
|
|
511
|
+
console.print(f"[green]{summary.status.title()}[/green]")
|
|
512
|
+
else:
|
|
513
|
+
console.print()
|
|
514
|
+
|
|
515
|
+
if surface is Surface.DEVELOPMENT:
|
|
516
|
+
_register_thread_harness(app, product, surface)
|
|
517
|
+
|
|
518
|
+
@app.command
|
|
519
|
+
def doctor(
|
|
520
|
+
*,
|
|
521
|
+
connection: ConnectionOptions = DEFAULT_CONNECTION_OPTIONS,
|
|
522
|
+
json_output: JsonOption = False,
|
|
523
|
+
) -> None:
|
|
524
|
+
"""Verify API reachability and token validity."""
|
|
525
|
+
_config = connection.resolve(product, surface)
|
|
526
|
+
token, credential_source = get_token(_config)
|
|
527
|
+
with ApiClient(_config, token) as client:
|
|
528
|
+
metadata = client.current_api_key()
|
|
529
|
+
result = {
|
|
530
|
+
"status": "ok",
|
|
531
|
+
"product": product.name,
|
|
532
|
+
"surface": surface.value,
|
|
533
|
+
"version": product.version,
|
|
534
|
+
"base_url": _config.base_url,
|
|
535
|
+
"base_url_source": _config.base_url_source,
|
|
536
|
+
"credential_source": credential_source,
|
|
537
|
+
"token_prefix": metadata.get("token_prefix"),
|
|
538
|
+
"expires_at": metadata.get("expires_at"),
|
|
539
|
+
"scopes": metadata.get("scopes", []),
|
|
540
|
+
}
|
|
541
|
+
if json_output:
|
|
542
|
+
render_json(result)
|
|
543
|
+
else:
|
|
544
|
+
console.print(
|
|
545
|
+
f"[green]Ready[/green] {product.name} {product.version}\n"
|
|
546
|
+
+ escape(
|
|
547
|
+
f"API: {_config.base_url} ({_config.base_url_source})\n"
|
|
548
|
+
f"Credential: {credential_source}"
|
|
549
|
+
)
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _workspace_ref(client: ApiClient, workspace_id: str) -> WorkspaceRef:
|
|
554
|
+
"""Name the workspace a freshly minted token is bound to.
|
|
555
|
+
|
|
556
|
+
The token response carries only the id, and `workspace use <name>` has to
|
|
557
|
+
resolve a name without a server call, so the name is looked up once at login
|
|
558
|
+
and kept in local state afterwards.
|
|
559
|
+
"""
|
|
560
|
+
for workspace in client.list_workspaces():
|
|
561
|
+
if str(workspace.get("id")) == workspace_id:
|
|
562
|
+
name = workspace.get("name")
|
|
563
|
+
if isinstance(name, str) and name:
|
|
564
|
+
return WorkspaceRef(id=workspace_id, name=name)
|
|
565
|
+
return WorkspaceRef(id=workspace_id, name=workspace_id)
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _register_workspace_selection(
|
|
569
|
+
app: App,
|
|
570
|
+
module_apps: dict[str, App],
|
|
571
|
+
product: Product,
|
|
572
|
+
surface: Surface,
|
|
573
|
+
) -> None:
|
|
574
|
+
"""Add the local workspace switch to the generated `workspace` group.
|
|
575
|
+
|
|
576
|
+
`use` has no operation in the manifest to be generated from: it changes only
|
|
577
|
+
which stored credential later commands pick up.
|
|
578
|
+
"""
|
|
579
|
+
workspace_app = module_apps.get("workspace")
|
|
580
|
+
if workspace_app is None:
|
|
581
|
+
workspace_app = app.command(
|
|
582
|
+
App(name="workspace", help="Workspace selection for this machine.")
|
|
583
|
+
)
|
|
584
|
+
|
|
585
|
+
@workspace_app.command(name="use")
|
|
586
|
+
def use_workspace(
|
|
587
|
+
selector: str,
|
|
588
|
+
/,
|
|
589
|
+
*,
|
|
590
|
+
connection: ConnectionOptions = DEFAULT_CONNECTION_OPTIONS,
|
|
591
|
+
) -> None:
|
|
592
|
+
"""Switch which workspace later commands act as, by name or id.
|
|
593
|
+
|
|
594
|
+
Purely local, like `stripe switch context` or `gh auth switch`: the
|
|
595
|
+
token for that workspace is already in the keyring, so this needs
|
|
596
|
+
neither a server call nor a re-login.
|
|
597
|
+
"""
|
|
598
|
+
_config = connection.resolve(product, surface)
|
|
599
|
+
workspace = match_workspace(_config, selector)
|
|
600
|
+
set_active_workspace(_config, workspace.id)
|
|
601
|
+
console.print(
|
|
602
|
+
f"[green]Now using[/green] {escape(workspace.name)} "
|
|
603
|
+
f"({escape(workspace.id)})."
|
|
604
|
+
)
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def _register_thread_harness(app: App, product: Product, surface: Surface) -> None:
|
|
608
|
+
"""The thread verification harness: assertions and artifacts, not a chat UI."""
|
|
609
|
+
thread = app.command(
|
|
610
|
+
App(name="thread", help="Run and verify thread streams with test artifacts.")
|
|
611
|
+
)
|
|
612
|
+
|
|
613
|
+
@thread.command(name="run")
|
|
614
|
+
def run_thread(
|
|
615
|
+
message: str,
|
|
616
|
+
*,
|
|
617
|
+
connection: ConnectionOptions = DEFAULT_CONNECTION_OPTIONS,
|
|
618
|
+
thread_id: str | None = None,
|
|
619
|
+
model: str | None = None,
|
|
620
|
+
artifact_dir: Path | None = None,
|
|
621
|
+
expect_terminal: str | None = None,
|
|
622
|
+
require_event: list[str] | None = None,
|
|
623
|
+
forbid_event: list[str] | None = None,
|
|
624
|
+
require_tool: list[str] | None = None,
|
|
625
|
+
require_persisted_interactions: bool = True,
|
|
626
|
+
json_output: JsonOption = False,
|
|
627
|
+
) -> None:
|
|
628
|
+
"""Run a live thread stream and fail when structural expectations fail."""
|
|
629
|
+
_config = connection.resolve(product, surface)
|
|
630
|
+
token, _source = get_token(_config)
|
|
631
|
+
test_run_id = str(uuid4())
|
|
632
|
+
output_dir = artifact_dir or Path("test-results/thread-runs") / test_run_id
|
|
633
|
+
payload = {
|
|
634
|
+
"message": message,
|
|
635
|
+
"client_message_id": test_run_id,
|
|
636
|
+
**({"thread_id": thread_id} if thread_id else {}),
|
|
637
|
+
**({"model": model} if model else {}),
|
|
638
|
+
}
|
|
639
|
+
events: list[dict[str, Any]] = []
|
|
640
|
+
interactions = None
|
|
641
|
+
stream_error: CliError | None = None
|
|
642
|
+
interaction_error: CliError | None = None
|
|
643
|
+
with ApiClient(_config, token) as client:
|
|
644
|
+
try:
|
|
645
|
+
events.extend(client.stream_thread(payload, test_run_id=test_run_id))
|
|
646
|
+
except CliError as exc:
|
|
647
|
+
stream_error = exc
|
|
648
|
+
summary = summarize_run(events, test_run_id)
|
|
649
|
+
if summary.thread_id:
|
|
650
|
+
try:
|
|
651
|
+
interactions = client.thread_interactions(summary.thread_id)
|
|
652
|
+
except CliError as exc:
|
|
653
|
+
interaction_error = exc
|
|
654
|
+
write_artifacts(output_dir, events, summary, interactions)
|
|
655
|
+
if stream_error:
|
|
656
|
+
raise stream_error
|
|
657
|
+
if interaction_error:
|
|
658
|
+
raise interaction_error
|
|
659
|
+
assert_expectations(
|
|
660
|
+
summary,
|
|
661
|
+
terminal_type=expect_terminal,
|
|
662
|
+
required_event_types=require_event or (),
|
|
663
|
+
forbidden_event_types=forbid_event or (),
|
|
664
|
+
required_tools=require_tool or (),
|
|
665
|
+
require_persisted_interactions=require_persisted_interactions,
|
|
666
|
+
interactions=interactions,
|
|
667
|
+
)
|
|
668
|
+
result = {**summary.to_dict(), "artifact_dir": str(output_dir.resolve())}
|
|
669
|
+
if json_output:
|
|
670
|
+
render_json(result)
|
|
671
|
+
else:
|
|
672
|
+
console.print(
|
|
673
|
+
f"[green]{summary.status.title()}[/green] "
|
|
674
|
+
f"({summary.event_count} events)\n"
|
|
675
|
+
f"Artifacts: {escape(str(output_dir.resolve()))}"
|
|
676
|
+
)
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def _prompt_agent_decisions(interrupt: dict[str, Any]) -> dict[str, Any]:
|
|
680
|
+
decisions: list[dict[str, str]] = []
|
|
681
|
+
for request in interrupt.get("action_requests", []):
|
|
682
|
+
if not isinstance(request, dict):
|
|
683
|
+
raise CliError("Agent returned an invalid approval request")
|
|
684
|
+
action_id = request.get("id")
|
|
685
|
+
action_name = request.get("name")
|
|
686
|
+
if not isinstance(action_id, str) or not isinstance(action_name, str):
|
|
687
|
+
raise CliError("Agent approval request is missing id or name")
|
|
688
|
+
console.print(
|
|
689
|
+
f"\n[bold]Pending action:[/bold] {escape(action_name)}\n"
|
|
690
|
+
f"{escape(json.dumps(request.get('args', {}), ensure_ascii=False, indent=2))}"
|
|
691
|
+
)
|
|
692
|
+
approved = Confirm.ask("Approve this action?", default=False)
|
|
693
|
+
decisions.append(
|
|
694
|
+
{
|
|
695
|
+
"type": "approve" if approved else "reject",
|
|
696
|
+
"action_request_id": action_id,
|
|
697
|
+
}
|
|
698
|
+
)
|
|
699
|
+
# Only the decisions: the server reads the pending requests, the stopped
|
|
700
|
+
# turn's steps and its time from where the run stored them.
|
|
701
|
+
return {"decisions": decisions}
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
def run(build: Callable[[], App]) -> None:
|
|
705
|
+
"""Build and run an entrypoint's app, reporting a CLI error, not a traceback.
|
|
706
|
+
|
|
707
|
+
Building is inside the guard because it already reads the product's
|
|
708
|
+
command manifest, which can fail.
|
|
709
|
+
"""
|
|
710
|
+
json_output = "--json" in sys.argv[1:]
|
|
711
|
+
try:
|
|
712
|
+
# A parse error gets its own exit code and, under --json, the same
|
|
713
|
+
# one-object stderr shape as any other failure, not a Rich panel.
|
|
714
|
+
build()(exit_on_error=False, print_error=not json_output)
|
|
715
|
+
except CycloptsError as exc:
|
|
716
|
+
error = UsageError(str(exc).strip() or type(exc).__name__)
|
|
717
|
+
if json_output:
|
|
718
|
+
_write_json_error(error)
|
|
719
|
+
raise SystemExit(error.exit_code) from exc
|
|
720
|
+
except CliError as exc:
|
|
721
|
+
if json_output:
|
|
722
|
+
_write_json_error(exc)
|
|
723
|
+
else:
|
|
724
|
+
error_console.print(f"[red]{escape(str(exc))}[/red]")
|
|
725
|
+
raise SystemExit(exc.exit_code) from exc
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def _write_json_error(error: CliError) -> None:
|
|
729
|
+
sys.stderr.write(
|
|
730
|
+
json.dumps(error.as_payload(), ensure_ascii=False, sort_keys=True, default=str)
|
|
731
|
+
+ "\n"
|
|
732
|
+
)
|