pacific-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.
@@ -0,0 +1,82 @@
1
+ """What every ``pacific`` command shares: settings, the profile store, one HTTP client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import httpx
6
+
7
+ from pacific_cli.auth.client import PacificCliApiClient
8
+ from pacific_cli.auth.config import PacificCliEnvironment, PacificCliSettings
9
+ from pacific_cli.auth.oauth import PacificCliOAuthService
10
+ from pacific_cli.auth.profiles import PacificCliProfileService
11
+ from pacific_cli.auth.types import (
12
+ PacificCliError,
13
+ PacificCliOAuthCredential,
14
+ PacificCliProfileName,
15
+ PacificCliResolvedProfile,
16
+ PacificCliStoredProfile,
17
+ )
18
+
19
+
20
+ class PacificCliRuntime:
21
+ """Built once per command by the root group and handed to each command as ``ctx.obj``."""
22
+
23
+ def __init__(
24
+ self,
25
+ settings: PacificCliSettings,
26
+ *,
27
+ environment: PacificCliEnvironment,
28
+ http: httpx.Client,
29
+ requested_profile: PacificCliProfileName | None,
30
+ ) -> None:
31
+ self.settings = settings
32
+ self.http = http
33
+ self.profiles = PacificCliProfileService(settings, environment=environment)
34
+ self.oauth = PacificCliOAuthService(http, settings=settings)
35
+ self._requested_profile = requested_profile
36
+
37
+ def resolved(self) -> PacificCliResolvedProfile:
38
+ """The profile this command runs as (``--profile``, ``PACIFIC_PROFILE``, then current)."""
39
+ return self.profiles.resolve(self._requested_profile)
40
+
41
+ def stored_profile(self) -> PacificCliStoredProfile:
42
+ """The selected profile, for commands that write its credential: PACIFIC_BASE_URL alone has nowhere to keep one."""
43
+ profile = self.resolved()
44
+ if profile.name is None:
45
+ raise PacificCliError(
46
+ "Signing in stores a credential on a profile; add one first with "
47
+ "`pacific profile add NAME --base-url URL`"
48
+ )
49
+ return PacificCliStoredProfile(
50
+ name=profile.name,
51
+ base_url=profile.base_url,
52
+ credential_from_environment=profile.credential_from_environment,
53
+ )
54
+
55
+ def client(self) -> PacificCliApiClient:
56
+ return PacificCliApiClient(
57
+ self.resolved(),
58
+ http=self.http,
59
+ profiles=self.profiles,
60
+ oauth=self.oauth,
61
+ settings=self.settings,
62
+ )
63
+
64
+ def sign_out(self, name: PacificCliProfileName) -> str:
65
+ """Forget a profile's credential, revoking a browser session at the server first.
66
+
67
+ The local credential is forgotten even when revocation fails, and the
68
+ message says so: a session left live at the server is worth knowing about.
69
+ """
70
+ stored = self.profiles.credentials().profiles.get(name)
71
+ if not isinstance(stored, PacificCliOAuthCredential):
72
+ self.profiles.clear_credential(name)
73
+ return "Signed out." if stored is not None else "Already signed out."
74
+ try:
75
+ revoked = self.oauth.revoke(stored)
76
+ except (PacificCliError, httpx.TransportError) as exc:
77
+ self.profiles.clear_credential(name)
78
+ return f"Signed out locally, but the server did not confirm revoking the session: {exc}"
79
+ self.profiles.clear_credential(name)
80
+ if not revoked:
81
+ return "Signed out locally; the server offers no revocation, so the session lasts until it expires."
82
+ return "Signed out and revoked the session."
@@ -0,0 +1,388 @@
1
+ """What the Pacific CLI keeps on disk about servers, identities and sessions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ import secrets
8
+ from datetime import datetime, timedelta
9
+ from enum import StrEnum
10
+ from pathlib import Path
11
+ from typing import Annotated, Literal, NewType, Protocol
12
+ from urllib.parse import urlsplit
13
+ from uuid import UUID
14
+
15
+ import click
16
+ from pydantic import (
17
+ AfterValidator,
18
+ BaseModel,
19
+ ConfigDict,
20
+ Field,
21
+ JsonValue,
22
+ SecretStr,
23
+ StringConstraints,
24
+ field_serializer,
25
+ )
26
+
27
+
28
+ def _normalized_base_url(value: str) -> str:
29
+ """A server's origin, with no trailing slash, so paths join onto it one way."""
30
+ candidate = value.strip()
31
+ parsed = urlsplit(candidate)
32
+ if parsed.scheme not in ("http", "https") or not parsed.netloc:
33
+ raise ValueError(
34
+ "a base URL is http(s)://host[:port], such as https://api.pacific.app"
35
+ )
36
+ if parsed.query or parsed.fragment:
37
+ raise ValueError("a base URL takes no query or fragment")
38
+ return candidate.rstrip("/")
39
+
40
+
41
+ #: Where a Pacific server answers, such as ``https://api.pacific.app``.
42
+ PacificCliBaseUrl = Annotated[str, AfterValidator(_normalized_base_url)]
43
+
44
+ #: A profile's name, as typed after ``--profile``.
45
+ PacificCliProfileName = Annotated[
46
+ str, StringConstraints(pattern=r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")
47
+ ]
48
+
49
+ #: The client id the server's OAuth broker issued this CLI at registration.
50
+ PacificCliOAuthClientId = NewType("PacificCliOAuthClientId", str)
51
+
52
+
53
+ class PacificCliError(click.ClickException):
54
+ """A failure the person running the command can act on; printed without a traceback."""
55
+
56
+
57
+ class PacificCliSessionEndedError(PacificCliError):
58
+ """The profile's browser session can no longer be renewed: it ended, was revoked,
59
+ or was signed out while the command ran. A new sign-in is the fix."""
60
+
61
+
62
+ class PacificCliCredentialKind(StrEnum):
63
+ """How a profile authenticates."""
64
+
65
+ API_KEY = "api_key"
66
+ OAUTH = "oauth"
67
+
68
+
69
+ class PacificCliApiKeyCredential(BaseModel):
70
+ """An API key minted in the Pacific app, sent as the bearer."""
71
+
72
+ model_config = ConfigDict(frozen=True, extra="forbid")
73
+
74
+ kind: Literal[PacificCliCredentialKind.API_KEY] = Field(
75
+ PacificCliCredentialKind.API_KEY, description="Always api_key"
76
+ )
77
+ api_key: SecretStr = Field(..., description="The key's raw value")
78
+
79
+ @field_serializer("api_key", when_used="json")
80
+ def _stored_secret(self, value: SecretStr) -> str:
81
+ # Written to the owner-only credentials file, the one place this model
82
+ # is serialized; SecretStr would otherwise store its mask.
83
+ return value.get_secret_value()
84
+
85
+
86
+ class PacificCliOAuthTokens(BaseModel):
87
+ """What one token response grants: the part of a session that rotates."""
88
+
89
+ model_config = ConfigDict(frozen=True, extra="forbid")
90
+
91
+ access_token: SecretStr = Field(..., description="The bearer the API takes")
92
+ refresh_token: SecretStr = Field(
93
+ ..., description="Renews the access token; rotates on every use"
94
+ )
95
+ expires_at: datetime = Field(..., description="When the access token stops working")
96
+
97
+ @field_serializer("access_token", "refresh_token", when_used="json")
98
+ def _stored_secret(self, value: SecretStr) -> str:
99
+ # As on the API key credential: serialized only into the credentials file.
100
+ return value.get_secret_value()
101
+
102
+ def expires_within(self, window: timedelta, *, now: datetime) -> bool:
103
+ """Whether the access token is gone, or will be within ``window``."""
104
+ return self.expires_at - window <= now
105
+
106
+
107
+ class PacificCliOAuthCredential(PacificCliOAuthTokens):
108
+ """A session from signing in in the browser, bound to the public API."""
109
+
110
+ kind: Literal[PacificCliCredentialKind.OAUTH] = Field(
111
+ PacificCliCredentialKind.OAUTH, description="Always oauth"
112
+ )
113
+ client_id: PacificCliOAuthClientId = Field(
114
+ ..., description="The client the broker registered for this sign-in"
115
+ )
116
+ issuer: str = Field(..., description="The authorization server, as it named itself")
117
+ token_endpoint: str = Field(..., description="Where the refresh grant is sent")
118
+ revocation_endpoint: str | None = Field(
119
+ ..., description="Where sign-out revokes the session; None if not offered"
120
+ )
121
+ resource: str = Field(
122
+ ..., description="The RFC 8707 resource the token is bound to"
123
+ )
124
+
125
+ def renewed(self, tokens: PacificCliOAuthTokens) -> PacificCliOAuthCredential:
126
+ """This session after a refresh: new tokens, the same client and server."""
127
+ return self.model_copy(
128
+ update={
129
+ "access_token": tokens.access_token,
130
+ "refresh_token": tokens.refresh_token,
131
+ "expires_at": tokens.expires_at,
132
+ }
133
+ )
134
+
135
+
136
+ PacificCliCredential = Annotated[
137
+ PacificCliApiKeyCredential | PacificCliOAuthCredential,
138
+ Field(discriminator="kind"),
139
+ ]
140
+
141
+
142
+ class PacificCliProfile(BaseModel):
143
+ """One server a person talks to; its credential is kept apart, in the credentials file."""
144
+
145
+ model_config = ConfigDict(frozen=True, extra="forbid")
146
+
147
+ base_url: PacificCliBaseUrl = Field(..., description="The server's origin")
148
+
149
+
150
+ class PacificCliConfig(BaseModel):
151
+ """``config.json``: the profiles and which one commands use by default."""
152
+
153
+ model_config = ConfigDict(frozen=True, extra="forbid")
154
+
155
+ current_profile: PacificCliProfileName | None = Field(
156
+ None, description="The profile used when none is named"
157
+ )
158
+ profiles: dict[PacificCliProfileName, PacificCliProfile] = Field(
159
+ default_factory=dict, description="Each profile by name"
160
+ )
161
+
162
+
163
+ class PacificCliCredentials(BaseModel):
164
+ """``credentials.json``, owner-only: each profile's credential by profile name."""
165
+
166
+ model_config = ConfigDict(frozen=True, extra="forbid")
167
+
168
+ profiles: dict[PacificCliProfileName, PacificCliCredential] = Field(
169
+ default_factory=dict, description="Each profile's credential"
170
+ )
171
+
172
+
173
+ class PacificCliProfileSource(StrEnum):
174
+ """Why a command runs as the profile it runs as."""
175
+
176
+ FLAG = "--profile"
177
+ ENVIRONMENT = "PACIFIC_PROFILE"
178
+ CURRENT = "current profile"
179
+ ENVIRONMENT_ONLY = "PACIFIC_BASE_URL"
180
+ #: A sign-in made for one command and revoked after it (``pacific keys``).
181
+ ONE_OFF_SIGN_IN = "one-off sign-in"
182
+
183
+
184
+ class PacificCliResolvedProfile(BaseModel):
185
+ """The server and credential one command runs with."""
186
+
187
+ model_config = ConfigDict(frozen=True, extra="forbid")
188
+
189
+ name: PacificCliProfileName | None = Field(
190
+ ..., description="The profile; None when PACIFIC_BASE_URL stands in for one"
191
+ )
192
+ source: PacificCliProfileSource = Field(..., description="What chose it")
193
+ base_url: PacificCliBaseUrl = Field(..., description="The server's origin")
194
+ credential: PacificCliCredential | None = Field(
195
+ ..., description="How it authenticates; None when signed out"
196
+ )
197
+ credential_from_environment: bool = Field(
198
+ ..., description="Whether PACIFIC_API_KEY supplied the credential"
199
+ )
200
+
201
+
202
+ class PacificCliStoredProfile(BaseModel):
203
+ """A selected profile that has a name, so a credential can be kept on it."""
204
+
205
+ model_config = ConfigDict(frozen=True, extra="forbid")
206
+
207
+ name: PacificCliProfileName = Field(..., description="The profile")
208
+ base_url: PacificCliBaseUrl = Field(..., description="The server's origin")
209
+ credential_from_environment: bool = Field(
210
+ ..., description="Whether PACIFIC_API_KEY overrides what is stored"
211
+ )
212
+
213
+
214
+ class PacificCliOAuthMetadata(BaseModel):
215
+ """A server's OAuth broker, from its RFC 8414 document: the members the CLI uses.
216
+
217
+ Endpoints are kept as the server spelled them. RFC 9207 compares the
218
+ callback's ``iss`` with ``issuer`` by string, and a URL type would add a
219
+ trailing slash the broker does not send.
220
+ """
221
+
222
+ model_config = ConfigDict(frozen=True, extra="ignore")
223
+
224
+ issuer: str = Field(..., description="The authorization server's identifier")
225
+ authorization_endpoint: str = Field(..., description="Where the browser signs in")
226
+ token_endpoint: str = Field(
227
+ ..., description="Where codes and refresh tokens are exchanged"
228
+ )
229
+ registration_endpoint: str | None = Field(
230
+ None, description="RFC 7591 client registration, if offered"
231
+ )
232
+ revocation_endpoint: str | None = Field(
233
+ None, description="RFC 7009 revocation, if offered"
234
+ )
235
+ code_challenge_methods_supported: list[str] = Field(
236
+ default_factory=list, description="PKCE methods the server takes"
237
+ )
238
+ authorization_response_iss_parameter_supported: bool = Field(
239
+ False, description="Whether the callback carries `iss` (RFC 9207)"
240
+ )
241
+
242
+
243
+ class PacificCliClientRegistration(BaseModel):
244
+ """An RFC 7591 registration request for this one sign-in's loopback redirect."""
245
+
246
+ model_config = ConfigDict(frozen=True, extra="forbid")
247
+
248
+ client_name: str = Field(..., description="Shown on the consent screen")
249
+ redirect_uris: list[str] = Field(..., description="Exactly the loopback redirect")
250
+ grant_types: list[str] = Field(..., description="The grants the CLI uses")
251
+ response_types: list[str] = Field(..., description="Always code")
252
+ token_endpoint_auth_method: str = Field(
253
+ ..., description="none: a native client holds no secret"
254
+ )
255
+
256
+
257
+ class PacificCliRegisteredClient(BaseModel):
258
+ """The registration response: the one member the CLI keeps."""
259
+
260
+ model_config = ConfigDict(frozen=True, extra="ignore")
261
+
262
+ client_id: PacificCliOAuthClientId = Field(..., description="The registered client")
263
+
264
+
265
+ class PacificCliTokenResponse(BaseModel):
266
+ """An RFC 6749 token response."""
267
+
268
+ model_config = ConfigDict(frozen=True, extra="ignore")
269
+
270
+ access_token: str = Field(..., description="The bearer")
271
+ token_type: str = Field(..., description="bearer")
272
+ expires_in: int | None = Field(None, description="Seconds the access token lasts")
273
+ refresh_token: str | None = Field(None, description="Renews the access token")
274
+ scope: str | None = Field(None, description="What was granted")
275
+
276
+
277
+ class PacificCliPkce(BaseModel):
278
+ """An RFC 7636 verifier and its S256 challenge, made fresh for each sign-in."""
279
+
280
+ model_config = ConfigDict(frozen=True, extra="forbid")
281
+
282
+ verifier: str = Field(
283
+ ..., min_length=43, max_length=128, description="Kept by the CLI"
284
+ )
285
+ challenge: str = Field(..., description="Sent in the authorization request")
286
+
287
+ @classmethod
288
+ def generate(cls) -> PacificCliPkce:
289
+ verifier = secrets.token_urlsafe(64)
290
+ digest = hashlib.sha256(verifier.encode("ascii")).digest()
291
+ return cls(
292
+ verifier=verifier,
293
+ challenge=base64.urlsafe_b64encode(digest).decode("ascii").rstrip("="),
294
+ )
295
+
296
+
297
+ class PacificCliProbe(BaseModel):
298
+ """What ``/public/v1/test-read`` says about the caller."""
299
+
300
+ model_config = ConfigDict(frozen=True, extra="ignore")
301
+
302
+ auth_type: str = Field(..., description="How the caller authenticated")
303
+ user_id: UUID = Field(..., description="The Pacific user the credential acts as")
304
+ scopes: list[str] = Field(..., description="The scopes it holds; `*` is all")
305
+
306
+
307
+ class PacificCliSignedIn(BaseModel):
308
+ """A browser sign-in the public API has accepted, and who it signed in."""
309
+
310
+ model_config = ConfigDict(frozen=True, extra="forbid")
311
+
312
+ credential: PacificCliOAuthCredential = Field(
313
+ ..., description="The session to keep"
314
+ )
315
+ probe: PacificCliProbe | None = Field(
316
+ ...,
317
+ description="Who the API says it is; None when the session cannot read "
318
+ "documents, the scope the probe route asks for",
319
+ )
320
+
321
+
322
+ class PacificCliProbeEnvelope(BaseModel):
323
+ """The probe routes answer inside the public API's ``{id, data}`` envelope."""
324
+
325
+ model_config = ConfigDict(frozen=True, extra="ignore")
326
+
327
+ data: PacificCliProbe = Field(..., description="The probe's answer")
328
+
329
+
330
+ class PacificCliLoopbackCallback(BaseModel):
331
+ """The query the browser brought back to the loopback redirect."""
332
+
333
+ model_config = ConfigDict(frozen=True, extra="ignore")
334
+
335
+ code: str | None = Field(None, description="The authorization code")
336
+ state: str | None = Field(None, description="Echo of the state the CLI sent")
337
+ iss: str | None = Field(None, description="RFC 9207 issuer of the response")
338
+ error: str | None = Field(None, description="RFC 6749 error code, on refusal")
339
+ error_description: str | None = Field(None, description="Why, on refusal")
340
+
341
+
342
+ class PacificCliOAuthErrorBody(BaseModel):
343
+ """An RFC 6749 error from the token, registration or revocation endpoint."""
344
+
345
+ model_config = ConfigDict(frozen=True, extra="ignore")
346
+
347
+ error: str = Field(..., description="The error code")
348
+ error_description: str | None = Field(None, description="What happened")
349
+
350
+
351
+ class PacificCliApiError(PacificCliError):
352
+ """The public API refused a request; ``body`` is kept so a caller can render its own shape."""
353
+
354
+ def __init__(self, message: str, *, status_code: int, body: bytes) -> None:
355
+ super().__init__(message)
356
+ self.status_code = status_code
357
+ self.body = body
358
+
359
+
360
+ class PacificCliErrorBody(BaseModel):
361
+ """The members of a public API refusal a generic message is built from.
362
+
363
+ Covers FastAPI's ``detail`` (a string, or a validation or refusal object) and
364
+ the ``error``/``message`` pair the policy routes answer with.
365
+ """
366
+
367
+ model_config = ConfigDict(frozen=True, extra="ignore")
368
+
369
+ detail: JsonValue = Field(None, description="FastAPI's error detail")
370
+ error: str | None = Field(None, description="An error code")
371
+ message: str | None = Field(None, description="What happened")
372
+
373
+
374
+ class PacificCliUploadPart(BaseModel):
375
+ """One file in a multipart request; the client opens it and streams it as it sends."""
376
+
377
+ model_config = ConfigDict(frozen=True, extra="forbid")
378
+
379
+ field: str = Field(..., description="The form field the file is sent as")
380
+ path: Path = Field(
381
+ ..., description="The file; its name is the name the server records"
382
+ )
383
+
384
+
385
+ class PacificCliBrowserOpener(Protocol):
386
+ """Shows the person the sign-in page (opens a browser, prints the link, or both)."""
387
+
388
+ def __call__(self, *, url: str) -> None: ...
pacific_cli/config.py ADDED
@@ -0,0 +1,10 @@
1
+ """Constants every part of the CLI shares."""
2
+
3
+ from __future__ import annotations
4
+
5
+ #: Where the customer public API is mounted on a Pacific server.
6
+ PACIFIC_CLI_PUBLIC_API_PREFIX = "/public/v1"
7
+
8
+ #: A read the public API answers for any credential that may read documents, with
9
+ #: who the caller is: what ``auth status`` asks and ``auth login`` checks with.
10
+ PACIFIC_CLI_PROBE_PATH = f"{PACIFIC_CLI_PUBLIC_API_PREFIX}/test-read"
@@ -0,0 +1 @@
1
+ """Uploading documents with the labels and attributes access policies match, and listing them."""
@@ -0,0 +1,171 @@
1
+ """``pacific documents``: upload with policy metadata, follow the jobs, list what you can read."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import click
9
+ from rich.console import Console
10
+ from rich.table import Table
11
+
12
+ from pacific_cli.auth.runtime import PacificCliRuntime
13
+ from pacific_cli.auth.types import PacificCliError
14
+ from pacific_cli.documents.config import PacificCliDocumentSettings
15
+ from pacific_cli.documents.service import PacificCliDocumentService
16
+ from pacific_cli.documents.types import PacificCliJobId
17
+
18
+
19
+ @click.group("documents")
20
+ def documents_group() -> None:
21
+ """Upload documents with the labels and attributes access policies match."""
22
+
23
+
24
+ @documents_group.command("upload")
25
+ @click.argument(
26
+ "files",
27
+ nargs=-1,
28
+ required=True,
29
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
30
+ )
31
+ @click.option(
32
+ "--label",
33
+ "-l",
34
+ "labels",
35
+ multiple=True,
36
+ help="A label (repeatable); policies match it as resource.metadata.labels, lower-cased",
37
+ )
38
+ @click.option(
39
+ "--attr",
40
+ "-a",
41
+ "attributes",
42
+ multiple=True,
43
+ metavar="KEY=VALUE",
44
+ help="An attribute (repeatable; a key given twice keeps both values); "
45
+ "policies match it as resource.metadata.<KEY>",
46
+ )
47
+ @click.option(
48
+ "--wait",
49
+ is_flag=True,
50
+ help="Wait until each document is searchable, and print its id",
51
+ )
52
+ @click.option("--json", "as_json", is_flag=True, help="Print JSON")
53
+ @click.pass_obj
54
+ def documents_upload(
55
+ runtime: PacificCliRuntime,
56
+ files: tuple[Path, ...],
57
+ labels: tuple[str, ...],
58
+ attributes: tuple[str, ...],
59
+ wait: bool,
60
+ as_json: bool,
61
+ ) -> None:
62
+ """Upload FILES, each carrying the same labels and attributes.
63
+
64
+ \b
65
+ pacific documents upload deck.pdf -l board -l refcode:r100 -a deal_stage=diligence --wait
66
+ """
67
+ service = PacificCliDocumentService(
68
+ runtime.client(), settings=PacificCliDocumentSettings()
69
+ )
70
+ metadata = service.metadata(labels=labels, attributes=attributes)
71
+ started = service.upload(list(files), metadata=metadata)
72
+ if not wait:
73
+ if as_json:
74
+ click.echo(
75
+ json.dumps([item.model_dump(mode="json") for item in started], indent=2)
76
+ )
77
+ return
78
+ table = Table("file", "job", box=None)
79
+ for item in started:
80
+ table.add_row(item.file_name, item.job_id)
81
+ Console().print(table)
82
+ click.echo("Follow one with: pacific documents job JOB_ID")
83
+ return
84
+ jobs = service.wait_until_searchable([item.job_id for item in started])
85
+ if as_json:
86
+ click.echo(json.dumps([job.model_dump(mode="json") for job in jobs], indent=2))
87
+ else:
88
+ table = Table("file", "document", "status", "stage", "error", box=None)
89
+ for item, job in zip(started, jobs, strict=True):
90
+ table.add_row(
91
+ item.file_name,
92
+ str(job.resource_id) if job.resource_id is not None else "-",
93
+ job.status.value,
94
+ job.stage.value if job.stage is not None else "-",
95
+ job.error or "",
96
+ )
97
+ Console().print(table)
98
+ # Every result is printed first; then a script must not carry on as though
99
+ # these documents were searchable.
100
+ stopped = [
101
+ item.file_name
102
+ for item, job in zip(started, jobs, strict=True)
103
+ if job.status.stopped_short
104
+ ]
105
+ if stopped:
106
+ raise PacificCliError(
107
+ f"{len(stopped)} of {len(jobs)} upload(s) failed or were cancelled: "
108
+ f"{', '.join(stopped)}"
109
+ )
110
+
111
+
112
+ @documents_group.command("job")
113
+ @click.argument("job_id")
114
+ @click.pass_obj
115
+ def documents_job(runtime: PacificCliRuntime, job_id: str) -> None:
116
+ """Where one ingest job is."""
117
+ service = PacificCliDocumentService(
118
+ runtime.client(), settings=PacificCliDocumentSettings()
119
+ )
120
+ click.echo(service.job(PacificCliJobId(job_id)).model_dump_json(indent=2))
121
+
122
+
123
+ @documents_group.command("list")
124
+ @click.option(
125
+ "--limit",
126
+ type=click.IntRange(min=1),
127
+ help="At most this many (default 50, or $PACIFIC_CLI_DOCUMENTS_LIST_LIMIT)",
128
+ )
129
+ @click.option(
130
+ "--all", "every", is_flag=True, help="Every one, printed a page at a time"
131
+ )
132
+ @click.option("--json", "as_json", is_flag=True, help="Print JSON")
133
+ @click.pass_obj
134
+ def documents_list(
135
+ runtime: PacificCliRuntime, limit: int | None, every: bool, as_json: bool
136
+ ) -> None:
137
+ """The documents you can read, newest first, with the labels policies match on them."""
138
+ if every and limit is not None:
139
+ raise click.UsageError("Pass --limit or --all, not both")
140
+ settings = PacificCliDocumentSettings()
141
+ service = PacificCliDocumentService(runtime.client(), settings=settings)
142
+ shown = settings.documents_list_limit if limit is None else limit
143
+ pages = service.document_pages(limit=None if every else shown)
144
+ more = False
145
+ separator = "["
146
+ for index, page in enumerate(pages):
147
+ more = page.has_more
148
+ if as_json:
149
+ # One valid array, written as the pages arrive.
150
+ for document in page.data:
151
+ click.echo(separator + document.model_dump_json(indent=2))
152
+ separator = ","
153
+ continue
154
+ table = Table(
155
+ "id", "file", "source", "labels", box=None, show_header=index == 0
156
+ )
157
+ for document in page.data:
158
+ table.add_row(
159
+ str(document.document_id),
160
+ document.file_name or "",
161
+ document.source,
162
+ ", ".join(document.metadata.labels),
163
+ )
164
+ Console().print(table)
165
+ if as_json:
166
+ click.echo("[]" if separator == "[" else "]")
167
+ if more and not every:
168
+ click.echo(
169
+ f"Showing the newest {shown}; more exist. Pass --limit N or --all.",
170
+ err=True,
171
+ )