synth-code 0.0.1__py3-none-macosx_15_0_arm64.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.
Files changed (110) hide show
  1. synth_code/__init__.py +0 -0
  2. synth_code/account.py +551 -0
  3. synth_code/account_http.py +86 -0
  4. synth_code/account_refusal.py +80 -0
  5. synth_code/accounting.py +148 -0
  6. synth_code/activity_grouping.py +149 -0
  7. synth_code/agent_panels.py +127 -0
  8. synth_code/approvals.py +397 -0
  9. synth_code/blobs.py +31 -0
  10. synth_code/cli.py +734 -0
  11. synth_code/client.py +413 -0
  12. synth_code/composer_delivery.py +139 -0
  13. synth_code/conversation.py +949 -0
  14. synth_code/daemon.py +34 -0
  15. synth_code/edition.py +306 -0
  16. synth_code/enrollment.py +304 -0
  17. synth_code/file_edit_facts.py +10 -0
  18. synth_code/freeze.py +234 -0
  19. synth_code/grant.py +59 -0
  20. synth_code/history.py +140 -0
  21. synth_code/history_generated.py +219 -0
  22. synth_code/history_wire.py +166 -0
  23. synth_code/image_input.py +109 -0
  24. synth_code/image_preview.py +105 -0
  25. synth_code/legacy_history.py +161 -0
  26. synth_code/live_turns.py +171 -0
  27. synth_code/model_picker.py +311 -0
  28. synth_code/native/manifest.json +1 -0
  29. synth_code/native/synth-code-runtime +0 -0
  30. synth_code/native.py +95 -0
  31. synth_code/oauth.py +284 -0
  32. synth_code/operator.py +116 -0
  33. synth_code/pack_source.py +65 -0
  34. synth_code/panel_request.py +291 -0
  35. synth_code/panels.py +40 -0
  36. synth_code/plugin_host.py +459 -0
  37. synth_code/protocol.py +35 -0
  38. synth_code/provider.py +313 -0
  39. synth_code/provider_fault.py +173 -0
  40. synth_code/provider_frames.py +571 -0
  41. synth_code/recommendation.py +324 -0
  42. synth_code/report.py +72 -0
  43. synth_code/research_events.py +44 -0
  44. synth_code/research_trace.py +449 -0
  45. synth_code/rex_view.py +58 -0
  46. synth_code/runtime_refusal.py +108 -0
  47. synth_code/schema/budgets.json +17 -0
  48. synth_code/schema/history-v2.json +1002 -0
  49. synth_code/session.py +291 -0
  50. synth_code/shoal.py +564 -0
  51. synth_code/side_panel.py +309 -0
  52. synth_code/skills.py +269 -0
  53. synth_code/slash.py +425 -0
  54. synth_code/source_view.py +135 -0
  55. synth_code/starter.json +13 -0
  56. synth_code/stdio.py +75 -0
  57. synth_code/stream.py +142 -0
  58. synth_code/subscriptions.py +267 -0
  59. synth_code/synth_authority.py +362 -0
  60. synth_code/synth_extra.py +32 -0
  61. synth_code/terminal.py +817 -0
  62. synth_code/terminal_journal.py +284 -0
  63. synth_code/terminal_layout.py +643 -0
  64. synth_code/terminal_surfaces.py +470 -0
  65. synth_code/terminal_viewport.py +125 -0
  66. synth_code/tool_render.py +86 -0
  67. synth_code/transcript_frames.py +212 -0
  68. synth_code/transcript_placement.py +63 -0
  69. synth_code/transcript_rows.py +456 -0
  70. synth_code/transport.py +243 -0
  71. synth_code/v001_history.py +468 -0
  72. synth_code/view.py +854 -0
  73. synth_code/views/__init__.py +93 -0
  74. synth_code/views/charts.py +196 -0
  75. synth_code/views/curses_adapter.py +116 -0
  76. synth_code/views/engine.py +170 -0
  77. synth_code/views/model.py +226 -0
  78. synth_code/views/primitives.py +270 -0
  79. synth_code/views/tiling.py +124 -0
  80. synth_code-0.0.1.dist-info/METADATA +50 -0
  81. synth_code-0.0.1.dist-info/RECORD +110 -0
  82. synth_code-0.0.1.dist-info/WHEEL +5 -0
  83. synth_code-0.0.1.dist-info/entry_points.txt +6 -0
  84. synth_code-0.0.1.dist-info/licenses/temper/LICENSE-APACHE +190 -0
  85. synth_code-0.0.1.dist-info/licenses/temper/LICENSE-MIT +21 -0
  86. synth_code-0.0.1.dist-info/licenses/temper/SOURCE.json +433 -0
  87. synth_code-0.0.1.dist-info/top_level.txt +2 -0
  88. synth_code_plugins/_sdk/__init__.py +19 -0
  89. synth_code_plugins/_sdk/callback_wire.py +240 -0
  90. synth_code_plugins/_sdk/callbacks.py +317 -0
  91. synth_code_plugins/_sdk/compliance.py +51 -0
  92. synth_code_plugins/_sdk/contracts.py +236 -0
  93. synth_code_plugins/_sdk/discovery.py +75 -0
  94. synth_code_plugins/_sdk/job_binding.py +71 -0
  95. synth_code_plugins/_sdk/lifecycle.py +50 -0
  96. synth_code_plugins/_sdk/lifecycle_generated.py +15 -0
  97. synth_code_plugins/_sdk/manifest.py +269 -0
  98. synth_code_plugins/_sdk/pack.py +332 -0
  99. synth_code_plugins/_sdk/push.py +98 -0
  100. synth_code_plugins/_sdk/records.py +26 -0
  101. synth_code_plugins/_sdk/registry.py +491 -0
  102. synth_code_plugins/_sdk/schemas.py +210 -0
  103. synth_code_plugins/_sdk/sources.py +230 -0
  104. synth_code_plugins/_sdk/surfaces.py +54 -0
  105. synth_code_plugins/_sdk/tools.py +172 -0
  106. synth_code_plugins/_sdk/worker_memory.py +49 -0
  107. synth_code_plugins/core/SKILL.md +6 -0
  108. synth_code_plugins/core/__init__.py +21 -0
  109. synth_code_plugins/core/plugin.toml +44 -0
  110. synth_code_plugins/core/source.py +18 -0
@@ -0,0 +1,362 @@
1
+ """The Synth sign-in authority: SDK OAuth operations bound to explicit origins and a file.
2
+
3
+ The ``synth_ai.auth`` module resolves its API origin, OAuth origin and credential file from
4
+ ``SYNTH_API_BASE_URL``, ``SYNTH_OAUTH_BASE_URL`` and ``SYNTH_AUTH_FILE``. Only part of its
5
+ surface accepts them as arguments, so Synth Code never lets the SDK read them:
6
+
7
+ - Pure SDK helpers that take every input explicitly (``discover``, ``endpoint``,
8
+ ``callback_result``) are called directly.
9
+ - SDK gap: ``token_path``, ``read_tokens``, ``save_tokens`` and ``oauth_base`` take no
10
+ path or origin argument, and ``credentials``/``status`` call them internally. Those are
11
+ implemented here against :attr:`SynthAuthority.credential_file` and
12
+ :attr:`SynthAuthority.oauth_override`, with the SDK's own record models and validation.
13
+
14
+ The public build always uses production and ``~/.config/synth/credentials.json``. The
15
+ beta build honours the three overrides through ``edition.beta_env``. The process
16
+ environment is only read, never modified.
17
+
18
+ ``synth_ai`` belongs to the optional ``synth`` extra, so this module imports it only inside
19
+ the functions that use it: a base install imports this module, and ``AuthorityRefused``,
20
+ without the extra.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ import tempfile
28
+ import time
29
+ from collections.abc import Mapping
30
+ from dataclasses import dataclass
31
+ from pathlib import Path
32
+ from enum import StrEnum
33
+ from functools import cache
34
+ from types import ModuleType
35
+ from typing import TYPE_CHECKING
36
+
37
+ import httpx
38
+ from pydantic import JsonValue, TypeAdapter, ValidationError
39
+
40
+ from .edition import beta_env
41
+ from .synth_extra import SynthExtraMissing
42
+
43
+ if TYPE_CHECKING:
44
+ from synth_ai._auth_models import AuthStatus, CredentialRecord, OAuthMetadata
45
+
46
+ __all__ = [
47
+ "AuthorityRefusal",
48
+ "AuthorityRefused",
49
+ "default_credential_file",
50
+ "sdk_error",
51
+ "SynthAuthority",
52
+ ]
53
+
54
+
55
+ class AuthorityRefusal(StrEnum):
56
+ """Why the sign-in authority refused; stable codes callers surface verbatim."""
57
+
58
+ CREDENTIAL_FILE_UNREADABLE = "credential_file_unreadable"
59
+ CREDENTIAL_FILE_INVALID = "credential_file_invalid"
60
+ CREDENTIAL_FILE_PERMISSIONS = "credential_file_permissions"
61
+ TOKEN_NOT_REFRESHABLE = "token_not_refreshable"
62
+ TOKEN_REFRESH_REJECTED = "token_refresh_rejected"
63
+ TOKEN_REFRESH_UNAVAILABLE = "token_refresh_unavailable"
64
+ TOKEN_REFRESH_INVALID = "token_refresh_invalid"
65
+
66
+
67
+ class AuthorityRefused(Exception):
68
+ """A typed sign-in authority refusal. ``cause`` never carries token values.
69
+
70
+ Not a ``SynthError``: that class lives in the optional extra. Callers catch both.
71
+ """
72
+
73
+ def __init__(
74
+ self, code: AuthorityRefusal, *, stage: str, status: int | None = None, cause: str
75
+ ) -> None:
76
+ super().__init__(f"{code.value} at {stage}" + (f" (HTTP {status})" if status else "") + f": {cause}")
77
+ self.code = code
78
+ self.stage = stage
79
+ self.status = status
80
+ self.cause = cause
81
+
82
+
83
+ def sdk_error(command: str) -> type[Exception]:
84
+ """The SDK's ``SynthError`` class, or refuse typed when the ``synth`` extra is absent.
85
+
86
+ Only absence maps to the refusal: a failure inside an installed SDK still raises.
87
+ """
88
+ try:
89
+ from synth_ai.errors import SynthError
90
+ except ModuleNotFoundError as error:
91
+ if error.name is None or error.name.split(".")[0] != "synth_ai":
92
+ raise
93
+ raise SynthExtraMissing(command) from error
94
+ return SynthError
95
+
96
+
97
+ def _sdk() -> ModuleType:
98
+ from synth_ai import auth
99
+
100
+ return auth
101
+
102
+
103
+ @cache
104
+ def _records() -> TypeAdapter[dict[str, CredentialRecord]]:
105
+ from synth_ai._auth_models import CredentialRecord
106
+
107
+ return TypeAdapter(dict[str, CredentialRecord])
108
+
109
+
110
+ def default_credential_file() -> Path:
111
+ """Resolved per call: ``HOME`` may change within a process."""
112
+ return Path.home() / ".config" / "synth" / "credentials.json"
113
+
114
+
115
+ def _origin(raw: str) -> str:
116
+ from synth_ai._validation import validate_http_origin
117
+ from synth_ai.errors import SynthError
118
+
119
+ try:
120
+ return validate_http_origin(raw, allow_http_loopback=True)
121
+ except ValueError as error:
122
+ raise SynthError(str(error)) from error
123
+
124
+
125
+ @dataclass(frozen=True, slots=True)
126
+ class SynthAuthority:
127
+ """SDK sign-in operations against one explicit API origin and credential file."""
128
+
129
+ api_base: str
130
+ credential_file: Path
131
+ oauth_override: str | None = None
132
+
133
+ @property
134
+ def DEFAULT_BASE_URL(self) -> str: # noqa: N802 - mirrors the SDK constant
135
+ return _sdk().DEFAULT_BASE_URL
136
+
137
+ @property
138
+ def DEFAULT_OAUTH_BASE_URL(self) -> str: # noqa: N802
139
+ return _sdk().DEFAULT_OAUTH_BASE_URL
140
+
141
+ @property
142
+ def DEVICE_CLIENT_ID(self) -> str: # noqa: N802
143
+ return _sdk().DEVICE_CLIENT_ID
144
+
145
+ @property
146
+ def DEVICE_GRANT_TYPE(self) -> str: # noqa: N802
147
+ return _sdk().DEVICE_GRANT_TYPE
148
+
149
+ @classmethod
150
+ def production(cls) -> SynthAuthority:
151
+ return cls(api_base=_sdk().DEFAULT_BASE_URL, credential_file=default_credential_file())
152
+
153
+ @classmethod
154
+ def for_build(cls) -> SynthAuthority:
155
+ """Production; the beta build applies its explicit origin and file overrides."""
156
+ api_base = beta_env("SYNTH_API_BASE_URL") or _sdk().DEFAULT_BASE_URL
157
+ credential_file = beta_env("SYNTH_AUTH_FILE")
158
+ oauth_override = beta_env("SYNTH_OAUTH_BASE_URL") or None
159
+ return cls(
160
+ api_base=_origin(api_base),
161
+ credential_file=Path(credential_file).expanduser()
162
+ if credential_file
163
+ else default_credential_file(),
164
+ oauth_override=_origin(oauth_override) if oauth_override else None,
165
+ )
166
+
167
+ # Pure SDK helpers: every input is an argument.
168
+ @staticmethod
169
+ def discover(client: httpx.Client, base: str) -> OAuthMetadata:
170
+ return _sdk().discover(client, base)
171
+
172
+ @staticmethod
173
+ def endpoint(metadata: OAuthMetadata | Mapping[str, JsonValue], name: str, base: str) -> str:
174
+ return _sdk().endpoint(metadata, name, base)
175
+
176
+ @staticmethod
177
+ def callback_result(location: str, *, state: str, issuer: str) -> dict[str, str] | None:
178
+ return _sdk().callback_result(location, state=state, issuer=issuer)
179
+
180
+ # SDK gap: these SDK functions read the process environment and take no argument.
181
+ def token_path(self) -> Path:
182
+ return self.credential_file
183
+
184
+ def oauth_base(self, base: str) -> str:
185
+ """The OAuth origin for an API base (production signs in on the MCP host)."""
186
+ if self.oauth_override is not None:
187
+ return self.oauth_override
188
+ return self.DEFAULT_OAUTH_BASE_URL if base == self.DEFAULT_BASE_URL else base
189
+
190
+ def read_tokens(self) -> dict[str, CredentialRecord]:
191
+ path = self.credential_file
192
+ if not path.exists():
193
+ return {}
194
+ if path.stat().st_mode & 0o077:
195
+ raise AuthorityRefused(
196
+ AuthorityRefusal.CREDENTIAL_FILE_PERMISSIONS,
197
+ stage="credential_file.read",
198
+ cause="credential file must have permissions 0600",
199
+ )
200
+ try:
201
+ text = path.read_text()
202
+ except OSError as error:
203
+ raise AuthorityRefused(
204
+ AuthorityRefusal.CREDENTIAL_FILE_UNREADABLE,
205
+ stage="credential_file.read",
206
+ cause=type(error).__name__,
207
+ ) from error
208
+ try:
209
+ value = json.loads(text)
210
+ if not isinstance(value, dict):
211
+ raise ValueError("expected object")
212
+ return _records().validate_python(value, strict=True)
213
+ except ValueError as error:
214
+ # Never echo the content: it holds tokens. Only the error class.
215
+ raise AuthorityRefused(
216
+ AuthorityRefusal.CREDENTIAL_FILE_INVALID,
217
+ stage="credential_file.parse",
218
+ cause=type(error).__name__,
219
+ ) from None
220
+
221
+ def save_tokens(self, records: Mapping[str, CredentialRecord | dict[str, JsonValue]]) -> None:
222
+ validated = _records().validate_python(dict(records), strict=True)
223
+ path = self.credential_file
224
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
225
+ descriptor, name = tempfile.mkstemp(prefix=".credentials-", dir=path.parent)
226
+ try:
227
+ with os.fdopen(descriptor, "w") as stream:
228
+ json.dump(
229
+ {key: record.model_dump(exclude_none=True) for key, record in validated.items()},
230
+ stream,
231
+ )
232
+ stream.flush()
233
+ os.fsync(stream.fileno())
234
+ os.replace(name, path)
235
+ finally:
236
+ if os.path.exists(name):
237
+ os.unlink(name)
238
+
239
+ def _base(self, base_url: str | None) -> str:
240
+ return _origin(base_url) if base_url is not None else self.api_base
241
+
242
+ def logout(self, base_url: str | None = None) -> None:
243
+ """``synth_ai.auth.logout`` bound to this origin and file: revoke, then forget."""
244
+ from synth_ai.errors import SynthError
245
+
246
+ base = self._base(base_url)
247
+ records = self.read_tokens()
248
+ record = records.get(base)
249
+ if record is None:
250
+ return
251
+ oauth = self.oauth_base(base)
252
+ with httpx.Client(timeout=30, follow_redirects=False) as client:
253
+ metadata = self.discover(client, oauth)
254
+ try:
255
+ response = client.post(
256
+ self.endpoint(metadata, "revocation_endpoint", oauth),
257
+ data={
258
+ "token": record.refresh_token or record.access_token,
259
+ "client_id": record.client_id,
260
+ },
261
+ )
262
+ except httpx.TransportError as error:
263
+ raise SynthError("OAuth logout request failed") from error
264
+ if not response.is_success:
265
+ raise SynthError(f"OAuth revocation refused: HTTP {response.status_code}")
266
+ records.pop(base)
267
+ self.save_tokens(records)
268
+
269
+ def status(self, base_url: str | None = None) -> AuthStatus:
270
+ from synth_ai._auth_models import AuthStatus, CredentialSource
271
+
272
+ base = self._base(base_url)
273
+ record = self.read_tokens().get(base)
274
+ # SYNTH_API_KEY is a credential, not a redirect; both builds honour it as the SDK does.
275
+ environment = bool(os.getenv("SYNTH_API_KEY"))
276
+ return AuthStatus(
277
+ base_url=base,
278
+ authenticated=environment or record is not None,
279
+ source=CredentialSource.ENVIRONMENT
280
+ if environment
281
+ else CredentialSource.OAUTH
282
+ if record is not None
283
+ else CredentialSource.NONE,
284
+ expires_at=record.expires_at if record is not None else None,
285
+ )
286
+
287
+ def credentials(self, base_url: str | None = None) -> tuple[str, str | None]:
288
+ """The bearer for ``base_url``, refreshing a stored OAuth token near expiry."""
289
+ base = self._base(base_url)
290
+ key = os.getenv("SYNTH_API_KEY")
291
+ if key:
292
+ return base, key
293
+ record = self.read_tokens().get(base)
294
+ if record is None:
295
+ return base, None
296
+ if record.expires_at <= time.time() + 30:
297
+ record = self._refresh(base, record)
298
+ return base, record.access_token
299
+
300
+ def _refresh(self, base: str, record: CredentialRecord) -> CredentialRecord:
301
+ from synth_ai._auth_models import CredentialRecord, OAuthToken
302
+
303
+ sdk = _sdk()
304
+ if record.client_id is None or record.refresh_token is None:
305
+ raise AuthorityRefused(
306
+ AuthorityRefusal.TOKEN_NOT_REFRESHABLE,
307
+ stage="token_refresh",
308
+ cause="stored credential has no refresh token; sign in again",
309
+ )
310
+ oauth = self.oauth_base(base)
311
+ with httpx.Client(timeout=30, follow_redirects=False) as client:
312
+ metadata = sdk.discover(client, oauth)
313
+ try:
314
+ response = client.post(
315
+ sdk.endpoint(metadata, "token_endpoint", oauth),
316
+ data={
317
+ "grant_type": "refresh_token",
318
+ "client_id": record.client_id,
319
+ "refresh_token": record.refresh_token,
320
+ "resource": oauth + "/mcp",
321
+ },
322
+ )
323
+ except httpx.TransportError as error:
324
+ raise AuthorityRefused(
325
+ AuthorityRefusal.TOKEN_REFRESH_UNAVAILABLE,
326
+ stage="token_refresh",
327
+ cause=type(error).__name__,
328
+ ) from error
329
+ if not response.is_success:
330
+ status = response.status_code
331
+ if 400 <= status < 500:
332
+ raise AuthorityRefused(
333
+ AuthorityRefusal.TOKEN_REFRESH_REJECTED,
334
+ stage="token_refresh",
335
+ status=status,
336
+ cause="refresh token refused; sign in again",
337
+ )
338
+ raise AuthorityRefused(
339
+ AuthorityRefusal.TOKEN_REFRESH_UNAVAILABLE,
340
+ stage="token_refresh",
341
+ status=status,
342
+ cause="token endpoint unavailable",
343
+ )
344
+ try:
345
+ token = OAuthToken.model_validate_json(response.content)
346
+ except ValidationError:
347
+ raise AuthorityRefused(
348
+ AuthorityRefusal.TOKEN_REFRESH_INVALID,
349
+ stage="token_refresh",
350
+ status=response.status_code,
351
+ cause="token response failed validation",
352
+ ) from None
353
+ refreshed = CredentialRecord(
354
+ access_token=token.access_token,
355
+ refresh_token=token.refresh_token or record.refresh_token,
356
+ client_id=record.client_id,
357
+ expires_at=time.time() + token.expires_in,
358
+ )
359
+ records = self.read_tokens()
360
+ records[base] = refreshed
361
+ self.save_tokens(records)
362
+ return refreshed
@@ -0,0 +1,32 @@
1
+ """The typed refusal for a surface that needs the optional ``synth`` extra on a base install."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TypedDict
6
+
7
+ __all__ = ["SynthExtraMissing", "SynthExtraPayload"]
8
+
9
+
10
+ class SynthExtraPayload(TypedDict):
11
+ code: str
12
+ command: str
13
+ extra: str
14
+ detail: str
15
+
16
+
17
+ class SynthExtraMissing(ImportError):
18
+ """``synth_ai`` (the ``synth`` extra) is not installed.
19
+
20
+ An ``ImportError`` so callers that already treat an absent SDK as unavailable keep
21
+ doing so; the CLI renders :meth:`payload` as ``{"error": {...}}`` with exit 2.
22
+ """
23
+
24
+ code = "synth_extra_missing"
25
+ extra = "synth"
26
+
27
+ def __init__(self, command: str) -> None:
28
+ self.command = command
29
+ super().__init__(f"{command}: Install synth-code[synth] to use this command.", name="synth_ai")
30
+
31
+ def payload(self) -> SynthExtraPayload:
32
+ return {"code": self.code, "command": self.command, "extra": self.extra, "detail": self.msg}