pyt3client 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.
- pyt3client/__init__.py +60 -0
- pyt3client/auth.py +270 -0
- pyt3client/cli/__init__.py +10 -0
- pyt3client/cli/app.py +866 -0
- pyt3client/client.py +290 -0
- pyt3client/credentials.py +119 -0
- pyt3client/errors.py +89 -0
- pyt3client/log.py +25 -0
- pyt3client/mcp.py +341 -0
- pyt3client/models/__init__.py +7 -0
- pyt3client/models/_base.py +23 -0
- pyt3client/models/auth.py +113 -0
- pyt3client/models/environment.py +50 -0
- pyt3client/models/tools.py +2827 -0
- pyt3client/py.typed +0 -0
- pyt3client/tool.py +33 -0
- pyt3client-0.1.0.dist-info/METADATA +178 -0
- pyt3client-0.1.0.dist-info/RECORD +21 -0
- pyt3client-0.1.0.dist-info/WHEEL +4 -0
- pyt3client-0.1.0.dist-info/entry_points.txt +3 -0
- pyt3client-0.1.0.dist-info/licenses/LICENSE +22 -0
pyt3client/cli/app.py
ADDED
|
@@ -0,0 +1,866 @@
|
|
|
1
|
+
"""The `pyt3` command: drive a (possibly remote) T3 Code environment from a shell.
|
|
2
|
+
|
|
3
|
+
T3 Code's own `t3` CLI only works on the machine that runs the server (it
|
|
4
|
+
reads the local data directory). `pyt3` signs in to any environment's `/mcp`
|
|
5
|
+
once (`pyt3 login`) and then works from anywhere that can reach it.
|
|
6
|
+
|
|
7
|
+
Exit codes follow upstream `t3 thread ... --wait`: 0 when the run completed,
|
|
8
|
+
1 when it failed, was cancelled or interrupted (or on any error), 2 when the
|
|
9
|
+
agent waits for an answer or approval, and 3 when `--timeout` ran out first.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
import sys
|
|
20
|
+
from typing import TYPE_CHECKING, Annotated, Literal, NoReturn
|
|
21
|
+
|
|
22
|
+
import httpx
|
|
23
|
+
from pydantic import BaseModel, JsonValue
|
|
24
|
+
import typer
|
|
25
|
+
|
|
26
|
+
from pyt3client import credentials as store
|
|
27
|
+
from pyt3client.auth import fetch_descriptor, pair
|
|
28
|
+
from pyt3client.client import T3Client
|
|
29
|
+
from pyt3client.errors import (
|
|
30
|
+
T3AuthError,
|
|
31
|
+
T3Error,
|
|
32
|
+
T3HttpError,
|
|
33
|
+
T3McpError,
|
|
34
|
+
T3ProtocolError,
|
|
35
|
+
T3ToolError,
|
|
36
|
+
)
|
|
37
|
+
from pyt3client.models.tools import (
|
|
38
|
+
ORCHESTRATOR_CAPABILITIES,
|
|
39
|
+
PENDING_REQUEST,
|
|
40
|
+
PROJECT_LIST,
|
|
41
|
+
THREAD_INTERRUPT,
|
|
42
|
+
THREAD_LAUNCH,
|
|
43
|
+
THREAD_LIST,
|
|
44
|
+
THREAD_READ,
|
|
45
|
+
THREAD_SEARCH,
|
|
46
|
+
THREAD_SEND,
|
|
47
|
+
ModelSelection,
|
|
48
|
+
PendingRequestInput,
|
|
49
|
+
ProjectListInput,
|
|
50
|
+
ProviderOptionSelection,
|
|
51
|
+
ThreadInterruptInput,
|
|
52
|
+
ThreadLaunchInput,
|
|
53
|
+
ThreadListInput,
|
|
54
|
+
ThreadReadInput,
|
|
55
|
+
ThreadSearchInput,
|
|
56
|
+
ThreadSendInput,
|
|
57
|
+
WorkspaceStrategy,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
if TYPE_CHECKING:
|
|
62
|
+
from collections.abc import Awaitable, Callable
|
|
63
|
+
|
|
64
|
+
from pyt3client.models.auth import InteractionMode, McpAccess, RuntimeMode, T3Credentials
|
|
65
|
+
from pyt3client.models.tools import Item, Project, ThreadReadOutput, ThreadWaitOutput
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
EXIT_OK = 0
|
|
69
|
+
EXIT_FAILED = 1
|
|
70
|
+
EXIT_WAITING = 2
|
|
71
|
+
EXIT_TIMEOUT = 3
|
|
72
|
+
|
|
73
|
+
LOGIN_HINT = "Run `pyt3 login <url> <pairing-code>` again."
|
|
74
|
+
# `t3_thread_read` pages from the oldest item for outside clients; reading
|
|
75
|
+
# before the largest position T3 accepts (a JS safe integer) gives the newest page.
|
|
76
|
+
_NEWEST = 9_007_199_254_740_991
|
|
77
|
+
|
|
78
|
+
type ThreadStatus = Literal[
|
|
79
|
+
"idle",
|
|
80
|
+
"preparing",
|
|
81
|
+
"queued",
|
|
82
|
+
"starting",
|
|
83
|
+
"running",
|
|
84
|
+
"waiting",
|
|
85
|
+
"completed",
|
|
86
|
+
"interrupted",
|
|
87
|
+
"failed",
|
|
88
|
+
"cancelled",
|
|
89
|
+
"rolled_back",
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class Runtime:
|
|
95
|
+
"""Per-invocation state; tests pass one as `obj=` to inject an httpx transport."""
|
|
96
|
+
|
|
97
|
+
transport: httpx.AsyncBaseTransport | None = None
|
|
98
|
+
env: str | None = None
|
|
99
|
+
|
|
100
|
+
def http_client(self) -> httpx.AsyncClient:
|
|
101
|
+
return httpx.AsyncClient(transport=self.transport, timeout=60)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
app = typer.Typer(
|
|
105
|
+
name="pyt3",
|
|
106
|
+
help="Drive T3 Code environments (local or remote) over their MCP endpoint.",
|
|
107
|
+
no_args_is_help=True,
|
|
108
|
+
add_completion=False,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
JsonFlag = Annotated[bool, typer.Option("--json", help="Print JSON instead of text.")]
|
|
112
|
+
TimeoutOption = Annotated[
|
|
113
|
+
float | None, typer.Option("--timeout", help="Stop waiting after this many seconds (exit 3).")
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@app.callback()
|
|
118
|
+
def main(
|
|
119
|
+
ctx: typer.Context,
|
|
120
|
+
env: Annotated[
|
|
121
|
+
str | None,
|
|
122
|
+
typer.Option("--env", envvar="PYT3_ENV", help="Saved environment alias (see `pyt3 envs`)."),
|
|
123
|
+
] = None,
|
|
124
|
+
) -> None:
|
|
125
|
+
"""Drive T3 Code environments (local or remote) over their MCP endpoint."""
|
|
126
|
+
runtime = ctx.obj if isinstance(ctx.obj, Runtime) else Runtime()
|
|
127
|
+
runtime.env = env
|
|
128
|
+
ctx.obj = runtime
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _runtime(ctx: typer.Context) -> Runtime:
|
|
132
|
+
root = ctx.find_root()
|
|
133
|
+
if isinstance(root.obj, Runtime):
|
|
134
|
+
return root.obj
|
|
135
|
+
runtime = Runtime()
|
|
136
|
+
root.obj = runtime
|
|
137
|
+
return runtime
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# --- output helpers --------------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _echo_json(value: BaseModel | JsonValue) -> None:
|
|
144
|
+
data = value.model_dump(mode="json", by_alias=True) if isinstance(value, BaseModel) else value
|
|
145
|
+
typer.echo(json.dumps(data, indent=2, ensure_ascii=False))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _dump(model: BaseModel) -> JsonValue:
|
|
149
|
+
return model.model_dump(mode="json", by_alias=True)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _fail(message: str, *, hint: str | None = None, code: int = EXIT_FAILED) -> NoReturn:
|
|
153
|
+
typer.echo(f"error: {message}", err=True)
|
|
154
|
+
if hint:
|
|
155
|
+
typer.echo(f"hint: {hint}", err=True)
|
|
156
|
+
raise typer.Exit(code)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _read_message(message: str) -> str:
|
|
160
|
+
"""The message argument, or stdin when it is `-`."""
|
|
161
|
+
text = sys.stdin.read() if message == "-" else message
|
|
162
|
+
if not text.strip():
|
|
163
|
+
_fail("the message is empty")
|
|
164
|
+
return text
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _wait_exit_code(result: ThreadWaitOutput) -> int:
|
|
168
|
+
if result.timed_out:
|
|
169
|
+
return EXIT_TIMEOUT
|
|
170
|
+
return _status_exit_code(result.status)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _status_exit_code(status: ThreadStatus) -> int:
|
|
174
|
+
match status:
|
|
175
|
+
case "completed" | "idle":
|
|
176
|
+
return EXIT_OK
|
|
177
|
+
case "waiting":
|
|
178
|
+
return EXIT_WAITING
|
|
179
|
+
case "failed" | "cancelled" | "interrupted" | "rolled_back":
|
|
180
|
+
return EXIT_FAILED
|
|
181
|
+
case "preparing" | "queued" | "starting" | "running":
|
|
182
|
+
# A wait only returns these when it timed out, which is handled above.
|
|
183
|
+
return EXIT_TIMEOUT
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _item_line(item: Item) -> str:
|
|
187
|
+
role = item.type.removesuffix("_message")
|
|
188
|
+
text = item.text if item.text is not None else (item.title or "")
|
|
189
|
+
suffix = " …" if item.text_truncated else ""
|
|
190
|
+
return f"[{role}] {text.strip()}{suffix}"
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _option_value(value: str | bool) -> str:
|
|
194
|
+
"""An option value as `--option` takes it (`true` / `false` for switches)."""
|
|
195
|
+
match value:
|
|
196
|
+
case bool():
|
|
197
|
+
return "true" if value else "false"
|
|
198
|
+
case str():
|
|
199
|
+
return value
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _parse_option(raw: str) -> ProviderOptionSelection:
|
|
203
|
+
key, sep, value = raw.partition("=")
|
|
204
|
+
if not sep or not key.strip():
|
|
205
|
+
msg = f"--option takes id=value, got {raw!r}"
|
|
206
|
+
raise typer.BadParameter(msg)
|
|
207
|
+
match value.strip().lower():
|
|
208
|
+
case "true":
|
|
209
|
+
return ProviderOptionSelection(id=key.strip(), value=True)
|
|
210
|
+
case "false":
|
|
211
|
+
return ProviderOptionSelection(id=key.strip(), value=False)
|
|
212
|
+
case _:
|
|
213
|
+
return ProviderOptionSelection(id=key.strip(), value=value.strip())
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
# --- running against an environment ---------------------------------------------
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _credentials(runtime: Runtime) -> tuple[str, T3Credentials]:
|
|
220
|
+
try:
|
|
221
|
+
alias, credentials = store.select(store.load(), runtime.env)
|
|
222
|
+
except store.StoreError as error:
|
|
223
|
+
_fail(str(error))
|
|
224
|
+
if store.is_expired(credentials):
|
|
225
|
+
_fail(
|
|
226
|
+
f"the sign-in for {alias!r} expired on {credentials.expires_at:%Y-%m-%d}",
|
|
227
|
+
hint=LOGIN_HINT,
|
|
228
|
+
)
|
|
229
|
+
return alias, credentials
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _run(ctx: typer.Context, operation: Callable[[T3Client], Awaitable[int]]) -> NoReturn:
|
|
233
|
+
"""Run `operation` against the selected environment and exit with its code."""
|
|
234
|
+
runtime = _runtime(ctx)
|
|
235
|
+
alias, credentials = _credentials(runtime)
|
|
236
|
+
|
|
237
|
+
async def go() -> int:
|
|
238
|
+
async with (
|
|
239
|
+
runtime.http_client() as http,
|
|
240
|
+
T3Client.from_credentials(credentials, http_client=http) as t3,
|
|
241
|
+
):
|
|
242
|
+
return await operation(t3)
|
|
243
|
+
|
|
244
|
+
try:
|
|
245
|
+
code = asyncio.run(go())
|
|
246
|
+
except T3ToolError as error:
|
|
247
|
+
hint = LOGIN_HINT if error.code == "capability_denied" else None
|
|
248
|
+
_fail(f"{error.code}: {error.message}", hint=hint)
|
|
249
|
+
except T3AuthError as error:
|
|
250
|
+
_fail(f"auth: {error}", hint=LOGIN_HINT)
|
|
251
|
+
except T3McpError as error:
|
|
252
|
+
_fail(f"request: {error.message}")
|
|
253
|
+
except T3HttpError as error:
|
|
254
|
+
_fail(f"http {error.status}: {error}")
|
|
255
|
+
except T3ProtocolError as error:
|
|
256
|
+
_fail(f"protocol: {error}")
|
|
257
|
+
except T3Error as error:
|
|
258
|
+
_fail(str(error))
|
|
259
|
+
except httpx.HTTPError as error:
|
|
260
|
+
_fail(f"cannot reach {alias!r} at {credentials.base_url}: {error}")
|
|
261
|
+
raise typer.Exit(code)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
async def _all_projects(t3: T3Client) -> list[Project]:
|
|
265
|
+
projects: list[Project] = []
|
|
266
|
+
cursor: int | None = None
|
|
267
|
+
while True:
|
|
268
|
+
params = ProjectListInput(limit=100) if cursor is None else ProjectListInput(cursor=cursor)
|
|
269
|
+
page = await t3.call(PROJECT_LIST, params)
|
|
270
|
+
projects.extend(page.projects)
|
|
271
|
+
if page.next_cursor is None:
|
|
272
|
+
return projects
|
|
273
|
+
cursor = page.next_cursor.root
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
async def _resolve_project(t3: T3Client, reference: str) -> str:
|
|
277
|
+
"""A project id, or the project whose folder contains the path `reference`.
|
|
278
|
+
|
|
279
|
+
Relative paths resolve against this shell's directory, which only makes
|
|
280
|
+
sense when the environment runs on this machine; pass an absolute path
|
|
281
|
+
on the server's filesystem for a remote one.
|
|
282
|
+
"""
|
|
283
|
+
projects = await _all_projects(t3)
|
|
284
|
+
if any(project.id == reference for project in projects):
|
|
285
|
+
return reference
|
|
286
|
+
path = Path(os.path.abspath(reference)) # noqa: PTH100 - must not follow symlinks
|
|
287
|
+
containing = [
|
|
288
|
+
project
|
|
289
|
+
for project in projects
|
|
290
|
+
if path == Path(project.workspace_root) or Path(project.workspace_root) in path.parents
|
|
291
|
+
]
|
|
292
|
+
if not containing:
|
|
293
|
+
msg = f"no project with id {reference!r} or containing {path}"
|
|
294
|
+
raise T3ToolError(THREAD_LAUNCH.name, "invalid_request", msg)
|
|
295
|
+
return max(containing, key=lambda project: len(project.workspace_root)).id
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
async def _read_newest(
|
|
299
|
+
t3: T3Client,
|
|
300
|
+
thread_id: str,
|
|
301
|
+
*,
|
|
302
|
+
limit: int,
|
|
303
|
+
activity: bool = False,
|
|
304
|
+
) -> ThreadReadOutput:
|
|
305
|
+
view: Literal["messages", "activity"] = "activity" if activity else "messages"
|
|
306
|
+
return await t3.call(
|
|
307
|
+
THREAD_READ,
|
|
308
|
+
ThreadReadInput(thread_id=thread_id, view=view, before_position=_NEWEST, limit=limit),
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
async def _reply(t3: T3Client, thread_id: str, run_id: str | None) -> str | None:
|
|
313
|
+
"""The run's last assistant message, falling back to the thread's last one."""
|
|
314
|
+
read = await _read_newest(t3, thread_id, limit=20)
|
|
315
|
+
replies = [item for item in read.items if item.type == "assistant_message" and item.text]
|
|
316
|
+
own = [item for item in replies if run_id is not None and item.run_id == run_id]
|
|
317
|
+
chosen = (own or replies)[-1:] or None
|
|
318
|
+
return chosen[0].text if chosen else None
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
async def _wait_and_report(
|
|
322
|
+
t3: T3Client,
|
|
323
|
+
thread_id: str,
|
|
324
|
+
run_id: str | None,
|
|
325
|
+
*,
|
|
326
|
+
timeout: float | None,
|
|
327
|
+
as_json: bool,
|
|
328
|
+
launched: BaseModel,
|
|
329
|
+
) -> int:
|
|
330
|
+
result = await t3.wait_for_thread(thread_id, run_id=run_id, timeout=timeout)
|
|
331
|
+
reply = await _reply(
|
|
332
|
+
t3, thread_id, (result.result_run.run_id if result.result_run else None) or result.run_id
|
|
333
|
+
)
|
|
334
|
+
code = _wait_exit_code(result)
|
|
335
|
+
if as_json:
|
|
336
|
+
_echo_json({"thread": _dump(launched), "wait": _dump(result), "reply": reply})
|
|
337
|
+
return code
|
|
338
|
+
if reply:
|
|
339
|
+
typer.echo(reply.strip())
|
|
340
|
+
if code != EXIT_OK:
|
|
341
|
+
state = "timed out" if result.timed_out else result.status
|
|
342
|
+
typer.echo(f"{thread_id}: {state}", err=True)
|
|
343
|
+
return code
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
# --- environments -----------------------------------------------------------------
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
@app.command()
|
|
350
|
+
def login(
|
|
351
|
+
ctx: typer.Context,
|
|
352
|
+
url: Annotated[str, typer.Argument(help="Environment address, e.g. https://host:3773.")],
|
|
353
|
+
pairing_code: Annotated[str, typer.Argument(help="Code from `t3 auth pairing create`.")],
|
|
354
|
+
access: Annotated[
|
|
355
|
+
Literal["read-only", "approval-required", "auto-accept-edits", "auto", "full-access"],
|
|
356
|
+
typer.Option(help="What this CLI may do. App approval codes (AUTO-…) set their own."),
|
|
357
|
+
] = "auto",
|
|
358
|
+
name: Annotated[
|
|
359
|
+
str | None, typer.Option("--name", help="Alias to save it as (default: its label).")
|
|
360
|
+
] = None,
|
|
361
|
+
client_name: Annotated[
|
|
362
|
+
str, typer.Option(help="Label the environment shows for this sign-in.")
|
|
363
|
+
] = "pyt3",
|
|
364
|
+
as_json: JsonFlag = False,
|
|
365
|
+
) -> None:
|
|
366
|
+
"""Sign in with a one-time pairing code and save the token."""
|
|
367
|
+
runtime = _runtime(ctx)
|
|
368
|
+
level: McpAccess = access
|
|
369
|
+
|
|
370
|
+
async def go() -> tuple[str, T3Credentials]:
|
|
371
|
+
async with runtime.http_client() as http:
|
|
372
|
+
credentials = await pair(
|
|
373
|
+
url, pairing_code, access=level, client_name=client_name, http_client=http
|
|
374
|
+
)
|
|
375
|
+
descriptor = await fetch_descriptor(credentials.base_url, http_client=http)
|
|
376
|
+
return name or store.default_alias(descriptor.label, credentials.base_url), credentials
|
|
377
|
+
|
|
378
|
+
try:
|
|
379
|
+
alias, credentials = asyncio.run(go())
|
|
380
|
+
environments = store.load()
|
|
381
|
+
except T3AuthError as error:
|
|
382
|
+
_fail(f"auth: {error}")
|
|
383
|
+
except (T3Error, httpx.HTTPError) as error:
|
|
384
|
+
_fail(f"cannot sign in at {url}: {error}")
|
|
385
|
+
except store.StoreError as error:
|
|
386
|
+
_fail(str(error))
|
|
387
|
+
environments[alias] = credentials
|
|
388
|
+
path = store.save(environments)
|
|
389
|
+
if as_json:
|
|
390
|
+
_echo_json({"alias": alias, "path": str(path)} | _env_summary(credentials))
|
|
391
|
+
return
|
|
392
|
+
typer.echo(
|
|
393
|
+
f"Signed in to {alias} ({credentials.base_url}) as {credentials.access},"
|
|
394
|
+
f" valid until {credentials.expires_at:%Y-%m-%d}."
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
@app.command()
|
|
399
|
+
def logout(
|
|
400
|
+
ctx: typer.Context,
|
|
401
|
+
alias: Annotated[
|
|
402
|
+
str | None, typer.Argument(help="Environment to forget (default: --env or the only one).")
|
|
403
|
+
] = None,
|
|
404
|
+
) -> None:
|
|
405
|
+
"""Forget a saved sign-in. Revoke it in T3 Code under Settings -> Sharing & access."""
|
|
406
|
+
runtime = _runtime(ctx)
|
|
407
|
+
try:
|
|
408
|
+
environments = store.load()
|
|
409
|
+
chosen, _ = store.select(environments, alias or runtime.env)
|
|
410
|
+
except store.StoreError as error:
|
|
411
|
+
_fail(str(error))
|
|
412
|
+
del environments[chosen]
|
|
413
|
+
store.save(environments)
|
|
414
|
+
typer.echo(f"Forgot {chosen}. The token stays valid until revoked in T3 Code.")
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _env_summary(credentials: T3Credentials) -> dict[str, JsonValue]:
|
|
418
|
+
return {
|
|
419
|
+
"url": credentials.base_url,
|
|
420
|
+
"environmentId": credentials.environment_id,
|
|
421
|
+
"access": credentials.access,
|
|
422
|
+
"expiresAt": credentials.expires_at.isoformat(),
|
|
423
|
+
"expired": store.is_expired(credentials),
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
@app.command()
|
|
428
|
+
def envs(as_json: JsonFlag = False) -> None:
|
|
429
|
+
"""List saved environments (never prints tokens)."""
|
|
430
|
+
try:
|
|
431
|
+
environments = store.load()
|
|
432
|
+
except store.StoreError as error:
|
|
433
|
+
_fail(str(error))
|
|
434
|
+
if as_json:
|
|
435
|
+
_echo_json({alias: _env_summary(creds) for alias, creds in environments.items()})
|
|
436
|
+
return
|
|
437
|
+
if not environments:
|
|
438
|
+
typer.echo("No environment saved. Run `pyt3 login <url> <pairing-code>`.")
|
|
439
|
+
return
|
|
440
|
+
for alias, credentials in sorted(environments.items()):
|
|
441
|
+
state = (
|
|
442
|
+
"EXPIRED"
|
|
443
|
+
if store.is_expired(credentials)
|
|
444
|
+
else f"until {credentials.expires_at:%Y-%m-%d}"
|
|
445
|
+
)
|
|
446
|
+
typer.echo(
|
|
447
|
+
f"{alias}\t{credentials.base_url}\t{credentials.access}\t{state}"
|
|
448
|
+
f"\t{credentials.environment_id}"
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
# --- reading ----------------------------------------------------------------------------
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
@app.command()
|
|
456
|
+
def models(ctx: typer.Context, as_json: JsonFlag = False) -> None:
|
|
457
|
+
"""List providers and their models."""
|
|
458
|
+
|
|
459
|
+
async def go(t3: T3Client) -> int:
|
|
460
|
+
capabilities = await t3.call(ORCHESTRATOR_CAPABILITIES)
|
|
461
|
+
if as_json:
|
|
462
|
+
_echo_json(capabilities)
|
|
463
|
+
return EXIT_OK
|
|
464
|
+
for provider in capabilities.providers:
|
|
465
|
+
state = "can run" if provider.can_run_child_task else "unavailable"
|
|
466
|
+
label = f" ({provider.display_name})" if provider.display_name else ""
|
|
467
|
+
typer.echo(f"{provider.provider_instance_id}{label} [{state}]")
|
|
468
|
+
for constraint in provider.constraints:
|
|
469
|
+
typer.echo(f" ! {constraint}")
|
|
470
|
+
for model in provider.models:
|
|
471
|
+
options = ", ".join(
|
|
472
|
+
f"{option.id}={'|'.join(_option_value(value) for value in option.values)}"
|
|
473
|
+
for option in model.options or []
|
|
474
|
+
)
|
|
475
|
+
typer.echo(f" {model.id}" + (f" ({options})" if options else ""))
|
|
476
|
+
if provider.omitted_models:
|
|
477
|
+
typer.echo(f" … {provider.omitted_models.root} more")
|
|
478
|
+
return EXIT_OK
|
|
479
|
+
|
|
480
|
+
_run(ctx, go)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
@app.command()
|
|
484
|
+
def projects(ctx: typer.Context, as_json: JsonFlag = False) -> None:
|
|
485
|
+
"""List projects."""
|
|
486
|
+
|
|
487
|
+
async def go(t3: T3Client) -> int:
|
|
488
|
+
found = await _all_projects(t3)
|
|
489
|
+
if as_json:
|
|
490
|
+
_echo_json([_dump(project) for project in found])
|
|
491
|
+
return EXIT_OK
|
|
492
|
+
for project in found:
|
|
493
|
+
typer.echo(f"{project.id}\t{project.title}\t{project.workspace_root}")
|
|
494
|
+
return EXIT_OK
|
|
495
|
+
|
|
496
|
+
_run(ctx, go)
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
@app.command()
|
|
500
|
+
def threads(
|
|
501
|
+
ctx: typer.Context,
|
|
502
|
+
project: Annotated[
|
|
503
|
+
str | None, typer.Option(help="Project id or folder (default: all projects).")
|
|
504
|
+
] = None,
|
|
505
|
+
all_threads: Annotated[bool, typer.Option("--all", help="Include subagent threads.")] = False,
|
|
506
|
+
status: Annotated[
|
|
507
|
+
list[ThreadStatus] | None, typer.Option(help="Only threads in this status (repeatable).")
|
|
508
|
+
] = None,
|
|
509
|
+
search: Annotated[
|
|
510
|
+
str | None, typer.Option(help="Search titles, branches, PRs and messages instead.")
|
|
511
|
+
] = None,
|
|
512
|
+
limit: Annotated[int, typer.Option(min=1, max=100)] = 50,
|
|
513
|
+
as_json: JsonFlag = False,
|
|
514
|
+
) -> None:
|
|
515
|
+
"""List threads, newest first, or search them."""
|
|
516
|
+
|
|
517
|
+
async def go(t3: T3Client) -> int:
|
|
518
|
+
project_id = await _resolve_project(t3, project) if project else None
|
|
519
|
+
if search is not None:
|
|
520
|
+
found = await t3.call(
|
|
521
|
+
THREAD_SEARCH,
|
|
522
|
+
ThreadSearchInput(query=search, limit=min(limit, 50))
|
|
523
|
+
if project_id is None
|
|
524
|
+
else ThreadSearchInput(query=search, limit=min(limit, 50), project_id=project_id),
|
|
525
|
+
)
|
|
526
|
+
if as_json:
|
|
527
|
+
_echo_json(found)
|
|
528
|
+
return EXIT_OK
|
|
529
|
+
for match in found.matches:
|
|
530
|
+
snippet = f" {match.snippet.root}" if match.snippet else ""
|
|
531
|
+
typer.echo(f"{match.thread_id}\t{match.title}\t[{match.source}]{snippet}")
|
|
532
|
+
return EXIT_OK
|
|
533
|
+
params = ThreadListInput(limit=limit)
|
|
534
|
+
if project_id is None:
|
|
535
|
+
params.all_projects = True
|
|
536
|
+
else:
|
|
537
|
+
params.project_id = project_id
|
|
538
|
+
if all_threads:
|
|
539
|
+
params.include_subagents = True
|
|
540
|
+
if status:
|
|
541
|
+
params.statuses = list(status)
|
|
542
|
+
listed = await t3.call(THREAD_LIST, params)
|
|
543
|
+
if as_json:
|
|
544
|
+
_echo_json(listed)
|
|
545
|
+
return EXIT_OK
|
|
546
|
+
for thread in listed.threads:
|
|
547
|
+
typer.echo(
|
|
548
|
+
f"{thread.thread_id}\t{thread.status}\t{thread.title}"
|
|
549
|
+
f"\t{thread.provider_instance_id}/{thread.model}"
|
|
550
|
+
)
|
|
551
|
+
if listed.total > len(listed.threads):
|
|
552
|
+
typer.echo(f"… {listed.total - len(listed.threads)} more (raise --limit)", err=True)
|
|
553
|
+
return EXIT_OK
|
|
554
|
+
|
|
555
|
+
_run(ctx, go)
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
@app.command()
|
|
559
|
+
def show(
|
|
560
|
+
ctx: typer.Context,
|
|
561
|
+
thread: Annotated[str, typer.Argument(help="Thread id.")],
|
|
562
|
+
activity: Annotated[
|
|
563
|
+
bool, typer.Option(help="Include tool calls, reasoning and runtime requests.")
|
|
564
|
+
] = False,
|
|
565
|
+
limit: Annotated[int, typer.Option(min=1, max=100, help="Latest items to show.")] = 10,
|
|
566
|
+
as_json: JsonFlag = False,
|
|
567
|
+
) -> None:
|
|
568
|
+
"""Show a thread's state and its latest messages."""
|
|
569
|
+
|
|
570
|
+
async def go(t3: T3Client) -> int:
|
|
571
|
+
read = await _read_newest(t3, thread, limit=limit, activity=activity)
|
|
572
|
+
if as_json:
|
|
573
|
+
_echo_json(read)
|
|
574
|
+
return EXIT_OK
|
|
575
|
+
state = read.thread
|
|
576
|
+
typer.echo(f"{state.title} [{state.status}] {state.provider_instance_id}/{state.model}")
|
|
577
|
+
typer.echo(f"{state.thread_id} {state.runtime_mode}/{state.interaction_mode}")
|
|
578
|
+
if state.link:
|
|
579
|
+
typer.echo(state.link)
|
|
580
|
+
typer.echo("")
|
|
581
|
+
for item in read.items:
|
|
582
|
+
typer.echo(_item_line(item))
|
|
583
|
+
return EXIT_OK
|
|
584
|
+
|
|
585
|
+
_run(ctx, go)
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
# --- acting -------------------------------------------------------------------------
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
@app.command()
|
|
592
|
+
def start(
|
|
593
|
+
ctx: typer.Context,
|
|
594
|
+
project: Annotated[str, typer.Argument(help="Project id, or a folder inside a project.")],
|
|
595
|
+
message: Annotated[str, typer.Argument(help="First prompt; `-` reads stdin.")],
|
|
596
|
+
title: Annotated[
|
|
597
|
+
str | None, typer.Option(help="Thread title (default: the message's first line).")
|
|
598
|
+
] = None,
|
|
599
|
+
provider: Annotated[
|
|
600
|
+
str | None, typer.Option(help="Provider instance id (see `pyt3 models`).")
|
|
601
|
+
] = None,
|
|
602
|
+
model: Annotated[str | None, typer.Option(help="Model slug of that provider.")] = None,
|
|
603
|
+
option: Annotated[
|
|
604
|
+
list[str] | None, typer.Option(help="Model option id=value (repeatable).")
|
|
605
|
+
] = None,
|
|
606
|
+
mode: Annotated[
|
|
607
|
+
Literal["approval-required", "auto-accept-edits", "auto", "full-access"] | None,
|
|
608
|
+
typer.Option(help="Runtime mode (default: the project's)."),
|
|
609
|
+
] = None,
|
|
610
|
+
plan: Annotated[bool, typer.Option(help="Start in plan mode.")] = False,
|
|
611
|
+
worktree: Annotated[
|
|
612
|
+
str | None, typer.Option(help="Run in a new worktree from this branch, tag or commit.")
|
|
613
|
+
] = None,
|
|
614
|
+
branch: Annotated[str | None, typer.Option(help="Branch name for the new worktree.")] = None,
|
|
615
|
+
wait: Annotated[bool, typer.Option(help="Wait for the run and print the reply.")] = False,
|
|
616
|
+
timeout: TimeoutOption = None,
|
|
617
|
+
as_json: JsonFlag = False,
|
|
618
|
+
) -> None:
|
|
619
|
+
"""Start a thread and print its id (or, with --wait, the agent's reply)."""
|
|
620
|
+
if (provider is None) != (model is None):
|
|
621
|
+
_fail("pass --provider and --model together")
|
|
622
|
+
if option and provider is None:
|
|
623
|
+
_fail("--option needs --provider and --model")
|
|
624
|
+
if branch is not None and worktree is None:
|
|
625
|
+
_fail("--branch needs --worktree")
|
|
626
|
+
text = _read_message(message)
|
|
627
|
+
runtime_mode: RuntimeMode | None = mode
|
|
628
|
+
interaction: InteractionMode | None = "plan" if plan else None
|
|
629
|
+
|
|
630
|
+
async def go(t3: T3Client) -> int:
|
|
631
|
+
params = ThreadLaunchInput(
|
|
632
|
+
project_id=await _resolve_project(t3, project),
|
|
633
|
+
title=title or text.strip().splitlines()[0][:120],
|
|
634
|
+
message=text,
|
|
635
|
+
)
|
|
636
|
+
if provider is not None and model is not None:
|
|
637
|
+
selection = ModelSelection(instance_id=provider, model=model)
|
|
638
|
+
if option:
|
|
639
|
+
selection.options = [_parse_option(raw) for raw in option]
|
|
640
|
+
params.model_selection = selection
|
|
641
|
+
if runtime_mode is not None:
|
|
642
|
+
params.runtime_mode = runtime_mode
|
|
643
|
+
if interaction is not None:
|
|
644
|
+
params.interaction_mode = interaction
|
|
645
|
+
if worktree is not None:
|
|
646
|
+
strategy = WorkspaceStrategy(type="worktree", base_ref=worktree)
|
|
647
|
+
if branch is not None:
|
|
648
|
+
strategy.branch = branch
|
|
649
|
+
params.workspace_strategy = strategy
|
|
650
|
+
launched = await t3.call(THREAD_LAUNCH, params)
|
|
651
|
+
if wait:
|
|
652
|
+
return await _wait_and_report(
|
|
653
|
+
t3,
|
|
654
|
+
launched.thread_id,
|
|
655
|
+
launched.run_id,
|
|
656
|
+
timeout=timeout,
|
|
657
|
+
as_json=as_json,
|
|
658
|
+
launched=launched,
|
|
659
|
+
)
|
|
660
|
+
if as_json:
|
|
661
|
+
_echo_json(launched)
|
|
662
|
+
else:
|
|
663
|
+
typer.echo(launched.thread_id)
|
|
664
|
+
return EXIT_OK
|
|
665
|
+
|
|
666
|
+
_run(ctx, go)
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
@app.command()
|
|
670
|
+
def send(
|
|
671
|
+
ctx: typer.Context,
|
|
672
|
+
thread: Annotated[str, typer.Argument(help="Thread id.")],
|
|
673
|
+
message: Annotated[str, typer.Argument(help="Message; `-` reads stdin.")],
|
|
674
|
+
mode: Annotated[
|
|
675
|
+
Literal["auto", "queue", "steer", "restart"] | None,
|
|
676
|
+
typer.Option(
|
|
677
|
+
help="auto (default): start an idle thread, steer or queue a busy one;"
|
|
678
|
+
" queue: run after active work; steer: into the running turn;"
|
|
679
|
+
" restart: interrupt and restart with this message."
|
|
680
|
+
),
|
|
681
|
+
] = None,
|
|
682
|
+
wait: Annotated[bool, typer.Option(help="Wait for the run and print the reply.")] = False,
|
|
683
|
+
timeout: TimeoutOption = None,
|
|
684
|
+
as_json: JsonFlag = False,
|
|
685
|
+
) -> None:
|
|
686
|
+
"""Send a message to a thread."""
|
|
687
|
+
text = _read_message(message)
|
|
688
|
+
|
|
689
|
+
async def go(t3: T3Client) -> int:
|
|
690
|
+
params = ThreadSendInput(thread_id=thread, message=text)
|
|
691
|
+
if mode is not None:
|
|
692
|
+
params.mode = mode
|
|
693
|
+
sent = await t3.call(THREAD_SEND, params)
|
|
694
|
+
if wait:
|
|
695
|
+
return await _wait_and_report(
|
|
696
|
+
t3, thread, sent.run_id, timeout=timeout, as_json=as_json, launched=sent
|
|
697
|
+
)
|
|
698
|
+
if as_json:
|
|
699
|
+
_echo_json(sent)
|
|
700
|
+
else:
|
|
701
|
+
typer.echo(f"{sent.run_id}\t{sent.status}")
|
|
702
|
+
return EXIT_OK
|
|
703
|
+
|
|
704
|
+
_run(ctx, go)
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
@app.command(name="wait")
|
|
708
|
+
def wait_command(
|
|
709
|
+
ctx: typer.Context,
|
|
710
|
+
thread: Annotated[str, typer.Argument(help="Thread id.")],
|
|
711
|
+
run: Annotated[str | None, typer.Option(help="Run to wait for (default: the latest).")] = None,
|
|
712
|
+
timeout: TimeoutOption = None,
|
|
713
|
+
as_json: JsonFlag = False,
|
|
714
|
+
) -> None:
|
|
715
|
+
"""Wait until a thread's run ends; the exit code tells how it ended."""
|
|
716
|
+
|
|
717
|
+
async def go(t3: T3Client) -> int:
|
|
718
|
+
result = await t3.wait_for_thread(thread, run_id=run, timeout=timeout)
|
|
719
|
+
if as_json:
|
|
720
|
+
_echo_json(result)
|
|
721
|
+
else:
|
|
722
|
+
state = "timed out" if result.timed_out else result.status
|
|
723
|
+
typer.echo(f"{result.run_id or '-'}\t{state}")
|
|
724
|
+
return _wait_exit_code(result)
|
|
725
|
+
|
|
726
|
+
_run(ctx, go)
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
@app.command()
|
|
730
|
+
def interrupt(
|
|
731
|
+
ctx: typer.Context,
|
|
732
|
+
thread: Annotated[str, typer.Argument(help="Thread id.")],
|
|
733
|
+
run: Annotated[
|
|
734
|
+
str | None, typer.Option(help="Run to interrupt (default: the newest running).")
|
|
735
|
+
] = None,
|
|
736
|
+
reason: Annotated[str | None, typer.Option(help="Why; shown in the thread.")] = None,
|
|
737
|
+
as_json: JsonFlag = False,
|
|
738
|
+
) -> None:
|
|
739
|
+
"""Interrupt a thread's running turn."""
|
|
740
|
+
|
|
741
|
+
async def go(t3: T3Client) -> int:
|
|
742
|
+
params = ThreadInterruptInput(thread_id=thread)
|
|
743
|
+
if run is not None:
|
|
744
|
+
params.run_id = run
|
|
745
|
+
if reason is not None:
|
|
746
|
+
params.reason = reason
|
|
747
|
+
result = await t3.call(THREAD_INTERRUPT, params)
|
|
748
|
+
if as_json:
|
|
749
|
+
_echo_json(result)
|
|
750
|
+
else:
|
|
751
|
+
typer.echo(f"{result.run_id or '-'}\t{result.status}")
|
|
752
|
+
return EXIT_OK
|
|
753
|
+
|
|
754
|
+
_run(ctx, go)
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
@app.command()
|
|
758
|
+
def pending(
|
|
759
|
+
ctx: typer.Context,
|
|
760
|
+
thread: Annotated[str, typer.Argument(help="Thread id.")],
|
|
761
|
+
as_json: JsonFlag = False,
|
|
762
|
+
) -> None:
|
|
763
|
+
"""List the questions a thread's agent waits on (approvals are not listed)."""
|
|
764
|
+
|
|
765
|
+
async def go(t3: T3Client) -> int:
|
|
766
|
+
listed = await t3.call(
|
|
767
|
+
PENDING_REQUEST, PendingRequestInput(action="list", thread_id=thread)
|
|
768
|
+
)
|
|
769
|
+
request_ids = _string_list(listed.root, "requestIds")
|
|
770
|
+
requests: list[JsonValue] = []
|
|
771
|
+
for request_id in request_ids:
|
|
772
|
+
read = await t3.call(
|
|
773
|
+
PENDING_REQUEST,
|
|
774
|
+
PendingRequestInput(action="read", thread_id=thread, request_id=request_id),
|
|
775
|
+
)
|
|
776
|
+
requests.append(read.root)
|
|
777
|
+
if as_json:
|
|
778
|
+
_echo_json(requests)
|
|
779
|
+
return EXIT_OK
|
|
780
|
+
if not requests:
|
|
781
|
+
typer.echo("No pending questions.")
|
|
782
|
+
for request in requests:
|
|
783
|
+
_print_request(request)
|
|
784
|
+
return EXIT_OK
|
|
785
|
+
|
|
786
|
+
_run(ctx, go)
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
@app.command()
|
|
790
|
+
def answer(
|
|
791
|
+
ctx: typer.Context,
|
|
792
|
+
thread: Annotated[str, typer.Argument(help="Thread id.")],
|
|
793
|
+
request_id: Annotated[str, typer.Argument(help="Request id from `pyt3 pending`.")],
|
|
794
|
+
answers: Annotated[
|
|
795
|
+
list[str],
|
|
796
|
+
typer.Argument(
|
|
797
|
+
help="question-id=answer, where the answer is an option value or label, or free"
|
|
798
|
+
" text. Repeat a question id to select several options."
|
|
799
|
+
),
|
|
800
|
+
],
|
|
801
|
+
as_json: JsonFlag = False,
|
|
802
|
+
) -> None:
|
|
803
|
+
"""Answer an agent's pending question. Cannot approve permission requests."""
|
|
804
|
+
parsed: dict[str, JsonValue] = {}
|
|
805
|
+
for raw in answers:
|
|
806
|
+
question_id, sep, value = raw.partition("=")
|
|
807
|
+
if not sep or not question_id.strip():
|
|
808
|
+
_fail(f"answers take question-id=answer, got {raw!r}")
|
|
809
|
+
key = question_id.strip()
|
|
810
|
+
match parsed.get(key):
|
|
811
|
+
case None:
|
|
812
|
+
parsed[key] = value
|
|
813
|
+
case list() as values:
|
|
814
|
+
values.append(value)
|
|
815
|
+
case previous:
|
|
816
|
+
parsed[key] = [previous, value]
|
|
817
|
+
|
|
818
|
+
async def go(t3: T3Client) -> int:
|
|
819
|
+
result = await t3.call(
|
|
820
|
+
PENDING_REQUEST,
|
|
821
|
+
PendingRequestInput(
|
|
822
|
+
action="respond", thread_id=thread, request_id=request_id, answers=parsed
|
|
823
|
+
),
|
|
824
|
+
)
|
|
825
|
+
if as_json:
|
|
826
|
+
_echo_json(result)
|
|
827
|
+
else:
|
|
828
|
+
typer.echo("Answered.")
|
|
829
|
+
return EXIT_OK
|
|
830
|
+
|
|
831
|
+
_run(ctx, go)
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
def _string_list(value: JsonValue, key: str) -> list[str]:
|
|
835
|
+
"""`value[key]` as a list of strings; pending-request results have no schema."""
|
|
836
|
+
if isinstance(value, dict):
|
|
837
|
+
items = value.get(key)
|
|
838
|
+
if isinstance(items, list):
|
|
839
|
+
return [item for item in items if isinstance(item, str)]
|
|
840
|
+
return []
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
def _print_request(request: JsonValue) -> None:
|
|
844
|
+
"""Print a `t3_pending_request` read result: request id plus its questions.
|
|
845
|
+
|
|
846
|
+
Questions follow upstream `UserInputQuestion`
|
|
847
|
+
(packages/contracts/src/providerRuntime.ts): id, header, question, options
|
|
848
|
+
of {label, description, value?}, multiSelect, allowCustomAnswer.
|
|
849
|
+
"""
|
|
850
|
+
if not isinstance(request, dict):
|
|
851
|
+
typer.echo(json.dumps(request))
|
|
852
|
+
return
|
|
853
|
+
typer.echo(f"request {request.get('requestId')}")
|
|
854
|
+
questions = request.get("questions")
|
|
855
|
+
for question in questions if isinstance(questions, list) else []:
|
|
856
|
+
if not isinstance(question, dict):
|
|
857
|
+
continue
|
|
858
|
+
multi = " (several allowed)" if question.get("multiSelect") is True else ""
|
|
859
|
+
typer.echo(f" {question.get('id')}: {question.get('question')}{multi}")
|
|
860
|
+
options = question.get("options")
|
|
861
|
+
for option in options if isinstance(options, list) else []:
|
|
862
|
+
if isinstance(option, dict):
|
|
863
|
+
value = option.get("value")
|
|
864
|
+
shown = f"{option.get('label')}" + (f" = {value}" if isinstance(value, str) else "")
|
|
865
|
+
description = option.get("description")
|
|
866
|
+
typer.echo(f" - {shown}" + (f": {description}" if description else ""))
|