nulara 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.
nulara/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ from importlib.metadata import version
2
+ from importlib.resources import files
3
+
4
+ from nulara.core.config import Product, Surface
5
+ from nulara.core.main import build_app, run
6
+
7
+ PRODUCT = Product(
8
+ name="nulara",
9
+ display_name="Nulara",
10
+ api_url="https://api.nulara.de/v1/app",
11
+ oauth_client_id="nulara-cli",
12
+ manifest=files(__name__).joinpath("spec.json"),
13
+ version=version("nulara"),
14
+ )
15
+
16
+
17
+ def main() -> None:
18
+ run(lambda: build_app(PRODUCT, Surface.CUSTOMER))
19
+
20
+
21
+ __all__ = ["PRODUCT", "main"]
@@ -0,0 +1 @@
1
+ """The product-neutral CLI core: an entrypoint hands it a `config.Product`."""
nulara/core/client.py ADDED
@@ -0,0 +1,423 @@
1
+ import json as json_module
2
+ import os
3
+ import tempfile
4
+ from collections.abc import Iterable, Iterator, Mapping
5
+ from contextlib import suppress
6
+ from dataclasses import dataclass
7
+ from email.message import Message
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import httpx
12
+
13
+ from nulara.core.config import ProductConfig
14
+ from nulara.core.errors import (
15
+ ApiError,
16
+ AuthenticationError,
17
+ AuthorizationError,
18
+ CliError,
19
+ ThreadProtocolError,
20
+ )
21
+ from nulara.core.thread import parse_sse
22
+
23
+ MAX_BUFFERED_RESPONSE_BYTES = 10 * 1024 * 1024
24
+ MAX_ERROR_RESPONSE_BYTES = 64 * 1024
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class ApiResult:
29
+ status_code: int
30
+ content_type: str
31
+ content: bytes
32
+ headers: Mapping[str, str]
33
+
34
+ def payload(self) -> Any:
35
+ if not self.content:
36
+ return None
37
+ if self.content_type == "application/json" or self.content_type.endswith(
38
+ "+json"
39
+ ):
40
+ try:
41
+ return json_module.loads(self.content)
42
+ except ValueError as exc:
43
+ raise CliError("API returned invalid JSON") from exc
44
+ if self.content_type.startswith("text/"):
45
+ return self.content.decode("utf-8", errors="replace")
46
+ return self.content
47
+
48
+ @property
49
+ def is_binary(self) -> bool:
50
+ return bool(self.content_type) and not (
51
+ self.content_type == "application/json"
52
+ or self.content_type.endswith("+json")
53
+ or self.content_type.startswith("text/")
54
+ )
55
+
56
+ @property
57
+ def filename(self) -> str | None:
58
+ return _response_filename(self.headers)
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class ApiDownloadResult:
63
+ status_code: int
64
+ content_type: str
65
+ headers: Mapping[str, str]
66
+ bytes_written: int
67
+ output: Path
68
+
69
+ @property
70
+ def filename(self) -> str | None:
71
+ return _response_filename(self.headers)
72
+
73
+
74
+ class ApiClient:
75
+ def __init__(
76
+ self,
77
+ config: ProductConfig,
78
+ token: str,
79
+ *,
80
+ transport: httpx.BaseTransport | None = None,
81
+ ):
82
+ self._client = httpx.Client(
83
+ base_url=config.base_url,
84
+ headers={
85
+ "Authorization": f"Bearer {token}",
86
+ "Accept": "application/json",
87
+ "User-Agent": config.user_agent,
88
+ },
89
+ timeout=httpx.Timeout(15.0, connect=5.0),
90
+ transport=transport,
91
+ )
92
+
93
+ def __enter__(self):
94
+ self._client.__enter__()
95
+ return self
96
+
97
+ def __exit__(self, exc_type, exc, traceback) -> None:
98
+ self._client.__exit__(exc_type, exc, traceback)
99
+
100
+ def request(
101
+ self,
102
+ method: str,
103
+ path: str,
104
+ *,
105
+ params: Mapping[str, Any] | list[tuple[str, Any]] | None = None,
106
+ json: Any = None,
107
+ data: Mapping[str, Any] | None = None,
108
+ files: Mapping[str, Any] | list[tuple[str, Any]] | None = None,
109
+ headers: Mapping[str, str] | None = None,
110
+ content: bytes | Iterable[bytes] | None = None,
111
+ redact_values: Iterable[str] = (),
112
+ ) -> Any:
113
+ return self.request_result(
114
+ method,
115
+ path,
116
+ params=params,
117
+ json=json,
118
+ data=data,
119
+ files=files,
120
+ headers=headers,
121
+ content=content,
122
+ redact_values=redact_values,
123
+ ).payload()
124
+
125
+ def request_result(
126
+ self,
127
+ method: str,
128
+ path: str,
129
+ *,
130
+ params: Mapping[str, Any] | list[tuple[str, Any]] | None = None,
131
+ json: Any = None,
132
+ data: Mapping[str, Any] | None = None,
133
+ files: Mapping[str, Any] | list[tuple[str, Any]] | None = None,
134
+ headers: Mapping[str, str] | None = None,
135
+ content: bytes | Iterable[bytes] | None = None,
136
+ redact_values: Iterable[str] = (),
137
+ ) -> ApiResult:
138
+ try:
139
+ with self._client.stream(
140
+ method,
141
+ path,
142
+ params=params,
143
+ json=json,
144
+ data=data,
145
+ files=files,
146
+ headers=headers,
147
+ content=content,
148
+ ) as response:
149
+ if response.is_error:
150
+ _raise_for_response(response, redact_values=redact_values)
151
+ content_type = _content_type(response)
152
+ response_headers = dict(response.headers)
153
+ if _is_binary_content_type(content_type):
154
+ return ApiResult(
155
+ status_code=response.status_code,
156
+ content_type=content_type,
157
+ content=b"",
158
+ headers=response_headers,
159
+ )
160
+ buffered = bytearray()
161
+ for chunk in response.iter_bytes():
162
+ buffered.extend(chunk)
163
+ if len(buffered) > MAX_BUFFERED_RESPONSE_BYTES:
164
+ raise CliError(
165
+ "API response exceeds the in-memory output limit; "
166
+ "use --output to stream it to a file"
167
+ )
168
+ return ApiResult(
169
+ status_code=response.status_code,
170
+ content_type=content_type,
171
+ content=bytes(buffered),
172
+ headers=response_headers,
173
+ )
174
+ except httpx.RequestError as exc:
175
+ raise CliError(f"Request failed: {exc}") from exc
176
+
177
+ def request_to_file(
178
+ self,
179
+ method: str,
180
+ path: str,
181
+ output: Path,
182
+ *,
183
+ overwrite: bool = False,
184
+ params: Mapping[str, Any] | list[tuple[str, Any]] | None = None,
185
+ json: Any = None,
186
+ data: Mapping[str, Any] | None = None,
187
+ files: Mapping[str, Any] | list[tuple[str, Any]] | None = None,
188
+ headers: Mapping[str, str] | None = None,
189
+ content: bytes | Iterable[bytes] | None = None,
190
+ redact_values: Iterable[str] = (),
191
+ ) -> ApiDownloadResult:
192
+ temporary: Path | None = None
193
+ try:
194
+ with self._client.stream(
195
+ method,
196
+ path,
197
+ params=params,
198
+ json=json,
199
+ data=data,
200
+ files=files,
201
+ headers=headers,
202
+ content=content,
203
+ ) as response:
204
+ if response.is_error:
205
+ _raise_for_response(response, redact_values=redact_values)
206
+ descriptor, temporary_name = tempfile.mkstemp(
207
+ prefix=f".{output.name}.",
208
+ suffix=".part",
209
+ dir=output.parent,
210
+ )
211
+ temporary = Path(temporary_name)
212
+ bytes_written = 0
213
+ with os.fdopen(descriptor, "wb") as target:
214
+ for chunk in response.iter_bytes():
215
+ target.write(chunk)
216
+ bytes_written += len(chunk)
217
+ target.flush()
218
+ os.fsync(target.fileno())
219
+ if overwrite:
220
+ os.replace(temporary, output)
221
+ else:
222
+ os.link(temporary, output)
223
+ temporary.unlink()
224
+ temporary = None
225
+ return ApiDownloadResult(
226
+ status_code=response.status_code,
227
+ content_type=_content_type(response),
228
+ headers=dict(response.headers),
229
+ bytes_written=bytes_written,
230
+ output=output,
231
+ )
232
+ except FileExistsError as exc:
233
+ raise CliError(
234
+ f"Output file already exists: {output}; pass --overwrite to replace it"
235
+ ) from exc
236
+ except httpx.RequestError as exc:
237
+ raise CliError(f"Request failed: {exc}") from exc
238
+ except OSError as exc:
239
+ raise CliError(f"Could not write output file {output}: {exc}") from exc
240
+ finally:
241
+ if temporary is not None:
242
+ with suppress(OSError):
243
+ temporary.unlink(missing_ok=True)
244
+
245
+ def current_api_key(self) -> dict[str, Any]:
246
+ result = self.request("GET", "/me/api-keys/current")
247
+ if not isinstance(result, dict):
248
+ raise CliError("Unexpected API key status response")
249
+ return result
250
+
251
+ def list_workspaces(self) -> list[dict[str, Any]]:
252
+ """Workspaces the token's user belongs to, used to name the local slot."""
253
+ result = self.request("GET", "/workspace")
254
+ if not isinstance(result, list):
255
+ raise CliError("Unexpected workspace list response")
256
+ return [entry for entry in result if isinstance(entry, dict)]
257
+
258
+ def stream_thread(
259
+ self, payload: Mapping[str, Any], *, test_run_id: str
260
+ ) -> Iterator[dict[str, Any]]:
261
+ yield from self._stream_sse(
262
+ "/threads/chat",
263
+ payload,
264
+ headers={"X-Test-Run-ID": test_run_id},
265
+ )
266
+
267
+ def stream_agent(self, payload: Mapping[str, Any]) -> Iterator[dict[str, Any]]:
268
+ """Start a customer-facing agent turn without test-only headers."""
269
+ yield from self._stream_sse("/threads/chat", payload)
270
+
271
+ def resume_agent(
272
+ self, thread_id: str, payload: Mapping[str, Any]
273
+ ) -> Iterator[dict[str, Any]]:
274
+ """Resume one interrupted turn with explicit human decisions."""
275
+ yield from self._stream_sse(f"/threads/{thread_id}/resume", payload)
276
+
277
+ def _stream_sse(
278
+ self,
279
+ path: str,
280
+ payload: Mapping[str, Any],
281
+ *,
282
+ headers: Mapping[str, str] | None = None,
283
+ ) -> Iterator[dict[str, Any]]:
284
+ stream_headers = {"Accept": "text/event-stream", **(headers or {})}
285
+ try:
286
+ with self._client.stream(
287
+ "POST",
288
+ path,
289
+ json=payload,
290
+ headers=stream_headers,
291
+ timeout=httpx.Timeout(300.0, connect=5.0),
292
+ ) as response:
293
+ if response.is_error:
294
+ _raise_for_response(response)
295
+ content_type = response.headers.get("content-type", "")
296
+ if content_type.split(";", 1)[0].strip().lower() != "text/event-stream":
297
+ raise ThreadProtocolError(
298
+ f"Expected text/event-stream, received {content_type or 'no content type'}"
299
+ )
300
+ yield from parse_sse(response.iter_lines())
301
+ except httpx.RequestError as exc:
302
+ raise CliError(f"Request failed: {exc}") from exc
303
+
304
+ def thread_interactions(self, thread_id: str) -> dict[str, Any]:
305
+ result = self.request("GET", f"/threads/{thread_id}/interactions")
306
+ if not isinstance(result, dict):
307
+ raise CliError("Unexpected thread interactions response")
308
+ return result
309
+
310
+ def operation_catalog(self) -> dict[str, Any]:
311
+ result = self.request("GET", "/agent-operations")
312
+ if not isinstance(result, dict):
313
+ raise CliError("Unexpected operation catalog response")
314
+ return result
315
+
316
+
317
+ def _response_detail(
318
+ response: httpx.Response,
319
+ content: bytes,
320
+ *,
321
+ truncated: bool,
322
+ redact_values: Iterable[str],
323
+ ) -> str:
324
+ try:
325
+ payload = json_module.loads(content)
326
+ except (UnicodeDecodeError, ValueError):
327
+ rendered = content.decode("utf-8", errors="replace")
328
+ else:
329
+ detail = payload.get("detail") if isinstance(payload, dict) else payload
330
+ rendered = str(_redact_error_inputs(detail))
331
+ rendered = _redact_text(rendered, redact_values)[:200]
332
+ if truncated:
333
+ rendered = f"{rendered}…"
334
+ return rendered or response.reason_phrase
335
+
336
+
337
+ def _redact_error_inputs(value: Any) -> Any:
338
+ if isinstance(value, list):
339
+ return [_redact_error_inputs(item) for item in value]
340
+ if isinstance(value, dict):
341
+ return {
342
+ key: (
343
+ "<redacted>"
344
+ if str(key).lower() == "input"
345
+ else _redact_error_inputs(item)
346
+ )
347
+ for key, item in value.items()
348
+ }
349
+ return value
350
+
351
+
352
+ def _redact_text(value: str, redact_values: Iterable[str]) -> str:
353
+ rendered = value
354
+ candidates = sorted(
355
+ {candidate for candidate in redact_values if candidate},
356
+ key=len,
357
+ reverse=True,
358
+ )
359
+ for candidate in candidates:
360
+ rendered = rendered.replace(candidate, "<redacted>")
361
+ return rendered
362
+
363
+
364
+ def _read_error_content(response: httpx.Response) -> tuple[bytes, bool]:
365
+ content = bytearray()
366
+ for chunk in response.iter_bytes():
367
+ remaining = MAX_ERROR_RESPONSE_BYTES + 1 - len(content)
368
+ content.extend(chunk[:remaining])
369
+ if len(content) > MAX_ERROR_RESPONSE_BYTES:
370
+ return bytes(content[:MAX_ERROR_RESPONSE_BYTES]), True
371
+ return bytes(content), False
372
+
373
+
374
+ def _raise_for_response(
375
+ response: httpx.Response, *, redact_values: Iterable[str] = ()
376
+ ) -> None:
377
+ content, truncated = _read_error_content(response)
378
+ detail = _response_detail(
379
+ response,
380
+ content,
381
+ truncated=truncated,
382
+ redact_values=redact_values,
383
+ )
384
+ if response.status_code == 401:
385
+ raise AuthenticationError(
386
+ f"API rejected authentication ({response.status_code}: {detail})",
387
+ status_code=response.status_code,
388
+ detail=detail,
389
+ )
390
+ if response.status_code == 403:
391
+ raise AuthorizationError(
392
+ f"API denied this operation ({response.status_code}: {detail})",
393
+ status_code=response.status_code,
394
+ detail=detail,
395
+ )
396
+ if response.is_error:
397
+ raise ApiError(
398
+ f"API request failed ({response.status_code}: {detail})",
399
+ status_code=response.status_code,
400
+ detail=detail,
401
+ )
402
+
403
+
404
+ def _content_type(response: httpx.Response) -> str:
405
+ return response.headers.get("content-type", "").split(";", 1)[0].strip().lower()
406
+
407
+
408
+ def _is_binary_content_type(content_type: str) -> bool:
409
+ return bool(content_type) and not (
410
+ content_type == "application/json"
411
+ or content_type.endswith("+json")
412
+ or content_type.startswith("text/")
413
+ )
414
+
415
+
416
+ def _response_filename(headers: Mapping[str, str]) -> str | None:
417
+ disposition = headers.get("content-disposition")
418
+ if not disposition:
419
+ return None
420
+ message = Message()
421
+ message["content-disposition"] = disposition
422
+ filename = message.get_filename()
423
+ return Path(filename).name if filename else None