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.
- synth_code/__init__.py +0 -0
- synth_code/account.py +551 -0
- synth_code/account_http.py +86 -0
- synth_code/account_refusal.py +80 -0
- synth_code/accounting.py +148 -0
- synth_code/activity_grouping.py +149 -0
- synth_code/agent_panels.py +127 -0
- synth_code/approvals.py +397 -0
- synth_code/blobs.py +31 -0
- synth_code/cli.py +734 -0
- synth_code/client.py +413 -0
- synth_code/composer_delivery.py +139 -0
- synth_code/conversation.py +949 -0
- synth_code/daemon.py +34 -0
- synth_code/edition.py +306 -0
- synth_code/enrollment.py +304 -0
- synth_code/file_edit_facts.py +10 -0
- synth_code/freeze.py +234 -0
- synth_code/grant.py +59 -0
- synth_code/history.py +140 -0
- synth_code/history_generated.py +219 -0
- synth_code/history_wire.py +166 -0
- synth_code/image_input.py +109 -0
- synth_code/image_preview.py +105 -0
- synth_code/legacy_history.py +161 -0
- synth_code/live_turns.py +171 -0
- synth_code/model_picker.py +311 -0
- synth_code/native/manifest.json +1 -0
- synth_code/native/synth-code-runtime +0 -0
- synth_code/native.py +95 -0
- synth_code/oauth.py +284 -0
- synth_code/operator.py +116 -0
- synth_code/pack_source.py +65 -0
- synth_code/panel_request.py +291 -0
- synth_code/panels.py +40 -0
- synth_code/plugin_host.py +459 -0
- synth_code/protocol.py +35 -0
- synth_code/provider.py +313 -0
- synth_code/provider_fault.py +173 -0
- synth_code/provider_frames.py +571 -0
- synth_code/recommendation.py +324 -0
- synth_code/report.py +72 -0
- synth_code/research_events.py +44 -0
- synth_code/research_trace.py +449 -0
- synth_code/rex_view.py +58 -0
- synth_code/runtime_refusal.py +108 -0
- synth_code/schema/budgets.json +17 -0
- synth_code/schema/history-v2.json +1002 -0
- synth_code/session.py +291 -0
- synth_code/shoal.py +564 -0
- synth_code/side_panel.py +309 -0
- synth_code/skills.py +269 -0
- synth_code/slash.py +425 -0
- synth_code/source_view.py +135 -0
- synth_code/starter.json +13 -0
- synth_code/stdio.py +75 -0
- synth_code/stream.py +142 -0
- synth_code/subscriptions.py +267 -0
- synth_code/synth_authority.py +362 -0
- synth_code/synth_extra.py +32 -0
- synth_code/terminal.py +817 -0
- synth_code/terminal_journal.py +284 -0
- synth_code/terminal_layout.py +643 -0
- synth_code/terminal_surfaces.py +470 -0
- synth_code/terminal_viewport.py +125 -0
- synth_code/tool_render.py +86 -0
- synth_code/transcript_frames.py +212 -0
- synth_code/transcript_placement.py +63 -0
- synth_code/transcript_rows.py +456 -0
- synth_code/transport.py +243 -0
- synth_code/v001_history.py +468 -0
- synth_code/view.py +854 -0
- synth_code/views/__init__.py +93 -0
- synth_code/views/charts.py +196 -0
- synth_code/views/curses_adapter.py +116 -0
- synth_code/views/engine.py +170 -0
- synth_code/views/model.py +226 -0
- synth_code/views/primitives.py +270 -0
- synth_code/views/tiling.py +124 -0
- synth_code-0.0.1.dist-info/METADATA +50 -0
- synth_code-0.0.1.dist-info/RECORD +110 -0
- synth_code-0.0.1.dist-info/WHEEL +5 -0
- synth_code-0.0.1.dist-info/entry_points.txt +6 -0
- synth_code-0.0.1.dist-info/licenses/temper/LICENSE-APACHE +190 -0
- synth_code-0.0.1.dist-info/licenses/temper/LICENSE-MIT +21 -0
- synth_code-0.0.1.dist-info/licenses/temper/SOURCE.json +433 -0
- synth_code-0.0.1.dist-info/top_level.txt +2 -0
- synth_code_plugins/_sdk/__init__.py +19 -0
- synth_code_plugins/_sdk/callback_wire.py +240 -0
- synth_code_plugins/_sdk/callbacks.py +317 -0
- synth_code_plugins/_sdk/compliance.py +51 -0
- synth_code_plugins/_sdk/contracts.py +236 -0
- synth_code_plugins/_sdk/discovery.py +75 -0
- synth_code_plugins/_sdk/job_binding.py +71 -0
- synth_code_plugins/_sdk/lifecycle.py +50 -0
- synth_code_plugins/_sdk/lifecycle_generated.py +15 -0
- synth_code_plugins/_sdk/manifest.py +269 -0
- synth_code_plugins/_sdk/pack.py +332 -0
- synth_code_plugins/_sdk/push.py +98 -0
- synth_code_plugins/_sdk/records.py +26 -0
- synth_code_plugins/_sdk/registry.py +491 -0
- synth_code_plugins/_sdk/schemas.py +210 -0
- synth_code_plugins/_sdk/sources.py +230 -0
- synth_code_plugins/_sdk/surfaces.py +54 -0
- synth_code_plugins/_sdk/tools.py +172 -0
- synth_code_plugins/_sdk/worker_memory.py +49 -0
- synth_code_plugins/core/SKILL.md +6 -0
- synth_code_plugins/core/__init__.py +21 -0
- synth_code_plugins/core/plugin.toml +44 -0
- synth_code_plugins/core/source.py +18 -0
synth_code/__init__.py
ADDED
|
File without changes
|
synth_code/account.py
ADDED
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
"""Use the public SDK's origin-bound OAuth session and credential storage."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable, Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from enum import StrEnum
|
|
8
|
+
from typing import TYPE_CHECKING, Any
|
|
9
|
+
|
|
10
|
+
from . import edition
|
|
11
|
+
from .account_http import AdapterCode, AdapterError, api
|
|
12
|
+
from .edition import beta_env
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from .synth_authority import SynthAuthority
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"PRODUCTION",
|
|
19
|
+
"SDK_REDIRECT_VARIABLES",
|
|
20
|
+
"AccountPayloadError",
|
|
21
|
+
"AccountPrincipal",
|
|
22
|
+
"AccountReceipt",
|
|
23
|
+
"account_receipt",
|
|
24
|
+
"account_status",
|
|
25
|
+
"authority",
|
|
26
|
+
"customer",
|
|
27
|
+
"lifecycle",
|
|
28
|
+
"local_status",
|
|
29
|
+
"reauthenticate",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
PRODUCTION = "https://api.usesynth.ai"
|
|
33
|
+
_VALID_ACTIONS = frozenset({"login", "logout", "status"})
|
|
34
|
+
_RETIRED_TOP_LEVEL_FIELDS = frozenset({"org_id", "plan"})
|
|
35
|
+
_PRINCIPAL_STRING_FIELDS = ("email", "user_id", "credential_kind", "principal_class")
|
|
36
|
+
_PRINCIPAL_LIST_FIELDS = ("scopes", "permissions")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
CREDENTIAL_UNAVAILABLE = "customer_credential_unavailable"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _credential_unavailable(detail: str) -> AdapterError:
|
|
43
|
+
return AdapterError(AdapterCode(CREDENTIAL_UNAVAILABLE, detail), uncertain=False)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AccountPayloadError(AdapterError):
|
|
47
|
+
"""Raised when an account or inference authority payload violates the canonical schema."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _require_non_empty_str(container: Mapping[str, Any], key: str, error_code: str) -> str:
|
|
51
|
+
value = container.get(key)
|
|
52
|
+
if not isinstance(value, str) or not value.strip():
|
|
53
|
+
raise AccountPayloadError(error_code, uncertain=False)
|
|
54
|
+
return value
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _optional_non_empty_str(
|
|
58
|
+
container: Mapping[str, Any], key: str, error_code: str
|
|
59
|
+
) -> str | None:
|
|
60
|
+
if key not in container or container[key] is None:
|
|
61
|
+
return None
|
|
62
|
+
value = container[key]
|
|
63
|
+
if not isinstance(value, str) or not value.strip():
|
|
64
|
+
raise AccountPayloadError(error_code, uncertain=False)
|
|
65
|
+
return value
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _optional_str_tuple(
|
|
69
|
+
container: Mapping[str, Any], key: str, error_code: str
|
|
70
|
+
) -> tuple[str, ...] | None:
|
|
71
|
+
if key not in container or container[key] is None:
|
|
72
|
+
return None
|
|
73
|
+
value = container[key]
|
|
74
|
+
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
|
75
|
+
raise AccountPayloadError(error_code, uncertain=False)
|
|
76
|
+
return tuple(value)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True, slots=True)
|
|
80
|
+
class AccountPrincipal:
|
|
81
|
+
org_id: str
|
|
82
|
+
email: str | None = None
|
|
83
|
+
user_id: str | None = None
|
|
84
|
+
credential_kind: str | None = None
|
|
85
|
+
principal_class: str | None = None
|
|
86
|
+
scopes: tuple[str, ...] | None = None
|
|
87
|
+
permissions: tuple[str, ...] | None = None
|
|
88
|
+
|
|
89
|
+
def __post_init__(self) -> None:
|
|
90
|
+
if not isinstance(self.org_id, str) or not self.org_id.strip():
|
|
91
|
+
raise AccountPayloadError(
|
|
92
|
+
"account_org_unconfirmed:missing_principal_org_id", uncertain=False
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
@classmethod
|
|
96
|
+
def from_payload(cls, raw: Mapping[str, Any]) -> AccountPrincipal:
|
|
97
|
+
if not isinstance(raw, Mapping):
|
|
98
|
+
raise AccountPayloadError(
|
|
99
|
+
"account_payload_invalid:missing_principal", uncertain=False
|
|
100
|
+
)
|
|
101
|
+
org_id = _require_non_empty_str(
|
|
102
|
+
raw, "org_id", "account_org_unconfirmed:missing_principal_org_id"
|
|
103
|
+
)
|
|
104
|
+
strings = {
|
|
105
|
+
field: _optional_non_empty_str(
|
|
106
|
+
raw, field, f"account_payload_invalid:invalid_principal_{field}"
|
|
107
|
+
)
|
|
108
|
+
for field in _PRINCIPAL_STRING_FIELDS
|
|
109
|
+
}
|
|
110
|
+
lists = {
|
|
111
|
+
field: _optional_str_tuple(
|
|
112
|
+
raw, field, f"account_payload_invalid:invalid_principal_{field}"
|
|
113
|
+
)
|
|
114
|
+
for field in _PRINCIPAL_LIST_FIELDS
|
|
115
|
+
}
|
|
116
|
+
return cls(
|
|
117
|
+
org_id=org_id,
|
|
118
|
+
email=strings["email"],
|
|
119
|
+
user_id=strings["user_id"],
|
|
120
|
+
credential_kind=strings["credential_kind"],
|
|
121
|
+
principal_class=strings["principal_class"],
|
|
122
|
+
scopes=lists["scopes"],
|
|
123
|
+
permissions=lists["permissions"],
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
def to_dict(self) -> dict[str, Any]:
|
|
127
|
+
result: dict[str, Any] = {"org_id": self.org_id}
|
|
128
|
+
if self.email is not None:
|
|
129
|
+
result["email"] = self.email
|
|
130
|
+
if self.user_id is not None:
|
|
131
|
+
result["user_id"] = self.user_id
|
|
132
|
+
if self.credential_kind is not None:
|
|
133
|
+
result["credential_kind"] = self.credential_kind
|
|
134
|
+
if self.principal_class is not None:
|
|
135
|
+
result["principal_class"] = self.principal_class
|
|
136
|
+
if self.scopes is not None:
|
|
137
|
+
result["scopes"] = list(self.scopes)
|
|
138
|
+
if self.permissions is not None:
|
|
139
|
+
result["permissions"] = list(self.permissions)
|
|
140
|
+
return result
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@dataclass(frozen=True, slots=True)
|
|
144
|
+
class AccountReceipt:
|
|
145
|
+
origin: str
|
|
146
|
+
org_id: str
|
|
147
|
+
organization: str
|
|
148
|
+
plan: str
|
|
149
|
+
access_tier: str | None
|
|
150
|
+
principal: AccountPrincipal
|
|
151
|
+
limits: list[Any] | None = None
|
|
152
|
+
usage: dict[str, Any] | None = None
|
|
153
|
+
|
|
154
|
+
def __post_init__(self) -> None:
|
|
155
|
+
if not isinstance(self.origin, str) or not self.origin.strip():
|
|
156
|
+
raise AccountPayloadError("account_payload_invalid:missing_origin", uncertain=False)
|
|
157
|
+
if not isinstance(self.org_id, str) or not self.org_id.strip():
|
|
158
|
+
raise AccountPayloadError("account_org_unconfirmed:missing_org_id", uncertain=False)
|
|
159
|
+
if self.principal.org_id != self.org_id:
|
|
160
|
+
raise AccountPayloadError(
|
|
161
|
+
"account_org_unconfirmed:principal_org_mismatch", uncertain=False
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
@classmethod
|
|
165
|
+
def from_payload(cls, origin: str, raw: object) -> AccountReceipt:
|
|
166
|
+
if not isinstance(raw, Mapping):
|
|
167
|
+
raise AccountPayloadError(
|
|
168
|
+
"account_payload_invalid:root_not_object", uncertain=False
|
|
169
|
+
)
|
|
170
|
+
retired = sorted(_RETIRED_TOP_LEVEL_FIELDS.intersection(raw.keys()))
|
|
171
|
+
if retired:
|
|
172
|
+
raise AccountPayloadError(
|
|
173
|
+
"account_payload_ambiguous:retired_top_level_fields:" + ",".join(retired),
|
|
174
|
+
uncertain=False,
|
|
175
|
+
)
|
|
176
|
+
org = raw.get("org")
|
|
177
|
+
if not isinstance(org, Mapping):
|
|
178
|
+
raise AccountPayloadError("account_payload_invalid:missing_org", uncertain=False)
|
|
179
|
+
principal_raw = raw.get("principal")
|
|
180
|
+
if not isinstance(principal_raw, Mapping):
|
|
181
|
+
raise AccountPayloadError(
|
|
182
|
+
"account_payload_invalid:missing_principal", uncertain=False
|
|
183
|
+
)
|
|
184
|
+
org_id = _require_non_empty_str(org, "id", "account_org_unconfirmed:missing_org_id")
|
|
185
|
+
organization = _require_non_empty_str(
|
|
186
|
+
org, "name", "account_payload_invalid:missing_org_name"
|
|
187
|
+
)
|
|
188
|
+
plan = _require_non_empty_str(org, "plan", "account_payload_invalid:missing_org_plan")
|
|
189
|
+
access_tier = _optional_non_empty_str(
|
|
190
|
+
org, "access_tier", "account_payload_invalid:invalid_access_tier"
|
|
191
|
+
)
|
|
192
|
+
principal = AccountPrincipal.from_payload(principal_raw)
|
|
193
|
+
if principal.org_id != org_id:
|
|
194
|
+
raise AccountPayloadError(
|
|
195
|
+
"account_org_unconfirmed:principal_org_mismatch", uncertain=False
|
|
196
|
+
)
|
|
197
|
+
limits = raw.get("limits")
|
|
198
|
+
if limits is not None and not isinstance(limits, list):
|
|
199
|
+
raise AccountPayloadError("account_payload_invalid:invalid_limits", uncertain=False)
|
|
200
|
+
usage = raw.get("usage")
|
|
201
|
+
if usage is not None and not isinstance(usage, Mapping):
|
|
202
|
+
raise AccountPayloadError("account_payload_invalid:invalid_usage", uncertain=False)
|
|
203
|
+
return cls(
|
|
204
|
+
origin=origin,
|
|
205
|
+
org_id=org_id,
|
|
206
|
+
organization=organization,
|
|
207
|
+
plan=plan,
|
|
208
|
+
access_tier=access_tier,
|
|
209
|
+
principal=principal,
|
|
210
|
+
limits=list(limits) if limits is not None else None,
|
|
211
|
+
usage=dict(usage) if usage is not None else None,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
def to_dict(self) -> dict[str, Any]:
|
|
215
|
+
return {
|
|
216
|
+
"origin": self.origin,
|
|
217
|
+
"org_id": self.org_id,
|
|
218
|
+
"organization": self.organization,
|
|
219
|
+
"plan": self.plan,
|
|
220
|
+
"access_tier": self.access_tier,
|
|
221
|
+
"principal": self.principal.to_dict(),
|
|
222
|
+
"limits": self.limits,
|
|
223
|
+
"usage": self.usage,
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
# Variables the Synth SDK reads to move its API origin, OAuth origin and credential file
|
|
228
|
+
# (synth_ai.auth, synth_ai.environments). Synth Code never lets the SDK read them: the beta
|
|
229
|
+
# build applies the first three explicitly (synth_authority.SynthAuthority.for_build); the
|
|
230
|
+
# public build ignores all of them and always talks to production with the default file.
|
|
231
|
+
SDK_REDIRECT_VARIABLES = (
|
|
232
|
+
"SYNTH_API_BASE_URL",
|
|
233
|
+
"SYNTH_OAUTH_BASE_URL",
|
|
234
|
+
"SYNTH_AUTH_FILE",
|
|
235
|
+
"SYNTH_LOCAL_API_BASE_URL",
|
|
236
|
+
"SYNTH_STAGING_API_BASE_URL",
|
|
237
|
+
"SYNTH_PROD_API_BASE_URL",
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def authority() -> SynthAuthority:
|
|
242
|
+
from .synth_authority import SynthAuthority
|
|
243
|
+
|
|
244
|
+
return SynthAuthority.for_build()
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def customer() -> tuple[str, str]:
|
|
248
|
+
token = beta_env("SYNTH_CODE_CUSTOMER_KEY")
|
|
249
|
+
if token is not None:
|
|
250
|
+
if not token:
|
|
251
|
+
raise AdapterError("customer_grant_required", uncertain=False)
|
|
252
|
+
if (beta_env("SYNTH_API_BASE_URL") or PRODUCTION).rstrip("/") != PRODUCTION:
|
|
253
|
+
raise AdapterError("customer_token_origin_mismatch", uncertain=False)
|
|
254
|
+
return PRODUCTION, token
|
|
255
|
+
try:
|
|
256
|
+
from synth_ai.errors import SynthError
|
|
257
|
+
except ImportError as error:
|
|
258
|
+
raise AdapterError("customer_sdk_unavailable", uncertain=False) from error
|
|
259
|
+
from .synth_authority import AuthorityRefused
|
|
260
|
+
|
|
261
|
+
try:
|
|
262
|
+
base, token = authority().credentials()
|
|
263
|
+
except AuthorityRefused as error:
|
|
264
|
+
raise _credential_unavailable(error.code.value) from error
|
|
265
|
+
except SynthError as error:
|
|
266
|
+
raise _credential_unavailable("sdk") from error
|
|
267
|
+
except OSError as error:
|
|
268
|
+
raise _credential_unavailable("io") from error
|
|
269
|
+
except ValueError as error:
|
|
270
|
+
raise _credential_unavailable("invalid") from error
|
|
271
|
+
if not token:
|
|
272
|
+
raise AdapterError("customer_grant_required", uncertain=False)
|
|
273
|
+
return base, token
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def account_receipt(base: str, token: str) -> dict[str, Any]:
|
|
277
|
+
raw, _ = api(base + "/v1/account", token)
|
|
278
|
+
receipt = AccountReceipt.from_payload(base, raw)
|
|
279
|
+
expected = beta_env("SYNTH_CODE_ORG")
|
|
280
|
+
if expected and receipt.org_id != expected:
|
|
281
|
+
raise AdapterError("account_org_mismatch", uncertain=False)
|
|
282
|
+
return receipt.to_dict()
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def local_status() -> dict[str, Any]:
|
|
287
|
+
"""SDK sign-in state and the local Inkling inference credential, without network calls."""
|
|
288
|
+
import time
|
|
289
|
+
|
|
290
|
+
from . import enrollment
|
|
291
|
+
from .grant import available
|
|
292
|
+
|
|
293
|
+
try:
|
|
294
|
+
sdk = authority()
|
|
295
|
+
except ImportError as error:
|
|
296
|
+
raise AdapterError("customer_sdk_unavailable", uncertain=False) from error
|
|
297
|
+
auth = sdk.status()
|
|
298
|
+
result: dict[str, Any] = {
|
|
299
|
+
"authenticated": auth.authenticated,
|
|
300
|
+
"origin": auth.base_url,
|
|
301
|
+
"credential_source": str(auth.source),
|
|
302
|
+
"expires_at": auth.expires_at,
|
|
303
|
+
"inference_credential_present": available(),
|
|
304
|
+
}
|
|
305
|
+
result["inference_authorization"] = (
|
|
306
|
+
"preissued" if result["inference_credential_present"] else "no_customer_inference_grant"
|
|
307
|
+
)
|
|
308
|
+
if auth.authenticated and not result["inference_credential_present"]:
|
|
309
|
+
lease, meta = enrollment.own_record()
|
|
310
|
+
if lease is not None:
|
|
311
|
+
if lease.expires_at <= time.time():
|
|
312
|
+
result.update(
|
|
313
|
+
inference_credential_present=False,
|
|
314
|
+
inference_authorization="managed_expired",
|
|
315
|
+
inference_expires_at=lease.expires_at,
|
|
316
|
+
)
|
|
317
|
+
else:
|
|
318
|
+
result.update(
|
|
319
|
+
inference_credential_present=True,
|
|
320
|
+
inference_authorization="managed_unverified",
|
|
321
|
+
inference_expires_at=lease.expires_at,
|
|
322
|
+
inference_ceiling_micros=meta.get("ceiling_micros"),
|
|
323
|
+
)
|
|
324
|
+
return result
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def account_status() -> dict[str, Any]:
|
|
328
|
+
"""Single-agent account status: local credentials plus the ``/v1/account`` receipt.
|
|
329
|
+
|
|
330
|
+
Unlike the beta's hosted status it reads no Swarms routing catalog or billing views.
|
|
331
|
+
"""
|
|
332
|
+
result = local_status()
|
|
333
|
+
if not result["authenticated"] and not beta_env("SYNTH_CODE_CUSTOMER_KEY"):
|
|
334
|
+
return result
|
|
335
|
+
receipt = account_receipt(*customer())
|
|
336
|
+
result.update(authenticated=True, account=receipt)
|
|
337
|
+
return result
|
|
338
|
+
|
|
339
|
+
def reauthenticate(device: bool | None = None) -> str:
|
|
340
|
+
"""Renew the SDK session without changing inference enrollment.
|
|
341
|
+
|
|
342
|
+
``device=None`` signs in through the browser when one can open and falls back
|
|
343
|
+
to the RFC 8628 device flow (the CLI's ``login --device``) when none can.
|
|
344
|
+
"""
|
|
345
|
+
from . import oauth
|
|
346
|
+
from .enrollment import changing_credentials
|
|
347
|
+
from .synth_authority import AuthorityRefused, sdk_error
|
|
348
|
+
|
|
349
|
+
SynthError = sdk_error("login")
|
|
350
|
+
|
|
351
|
+
if beta_env("SYNTH_CODE_CUSTOMER_KEY"):
|
|
352
|
+
return (
|
|
353
|
+
"Synth uses SYNTH_CODE_CUSTOMER_KEY · update or unset it to change accounts"
|
|
354
|
+
)
|
|
355
|
+
try:
|
|
356
|
+
with changing_credentials():
|
|
357
|
+
sdk = authority()
|
|
358
|
+
if device is None:
|
|
359
|
+
device = not oauth.browser_available()
|
|
360
|
+
if device:
|
|
361
|
+
oauth.login_device(sdk, show=oauth.show_device_code)
|
|
362
|
+
else:
|
|
363
|
+
oauth.login_pkce(sdk)
|
|
364
|
+
account_receipt(*customer())
|
|
365
|
+
except (SynthError, AuthorityRefused, AdapterError) as error:
|
|
366
|
+
raise RuntimeError(f"Synth account sign-in failed: {_refusal_code(error)}") from error
|
|
367
|
+
return "Synth account verified"
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _refusal_code(error: Exception) -> str:
|
|
371
|
+
"""The stable code of an authority or adapter refusal; ``sdk_error`` for untyped SDK errors."""
|
|
372
|
+
from .synth_authority import AuthorityRefused
|
|
373
|
+
|
|
374
|
+
if isinstance(error, AuthorityRefused):
|
|
375
|
+
return error.code.value
|
|
376
|
+
if isinstance(error, AdapterError):
|
|
377
|
+
return error.code
|
|
378
|
+
return "sdk_error"
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
class IndexAccess(StrEnum):
|
|
382
|
+
VERIFIED = "verified"
|
|
383
|
+
NO_ACCOUNT = "no_account"
|
|
384
|
+
ACCOUNT_UNVERIFIED = "account_unverified"
|
|
385
|
+
SCOPES_UNREPORTED = "scopes_unreported"
|
|
386
|
+
SCOPE_NOT_GRANTED = "scope_not_granted"
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def index_access(
|
|
390
|
+
receipt: Mapping[str, Any] | AdapterError | None, required: Iterable[str]
|
|
391
|
+
) -> dict[str, Any]:
|
|
392
|
+
"""Index access from the account receipt.
|
|
393
|
+
|
|
394
|
+
No account, an account whose verification failed, an account that did not report its
|
|
395
|
+
scopes, and an account missing scopes are four different states.
|
|
396
|
+
"""
|
|
397
|
+
if receipt is None:
|
|
398
|
+
return {"index_access": IndexAccess.NO_ACCOUNT.value}
|
|
399
|
+
if isinstance(receipt, AdapterError):
|
|
400
|
+
return {"index_access": IndexAccess.ACCOUNT_UNVERIFIED.value, "index_cause": str(receipt)}
|
|
401
|
+
scopes = receipt["principal"].get("scopes")
|
|
402
|
+
if scopes is None:
|
|
403
|
+
return {"index_access": IndexAccess.SCOPES_UNREPORTED.value}
|
|
404
|
+
missing = sorted(set(required) - set(scopes))
|
|
405
|
+
if missing:
|
|
406
|
+
return {"index_access": IndexAccess.SCOPE_NOT_GRANTED.value, "index_missing_scopes": missing}
|
|
407
|
+
return {"index_access": IndexAccess.VERIFIED.value}
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def lifecycle(
|
|
411
|
+
action: str,
|
|
412
|
+
device: bool = False,
|
|
413
|
+
*,
|
|
414
|
+
account_only: bool = False,
|
|
415
|
+
ceiling_micros: int = 50000,
|
|
416
|
+
allow_paid: bool = False,
|
|
417
|
+
renew: bool = False,
|
|
418
|
+
with_index: bool = False,
|
|
419
|
+
) -> dict[str, Any]:
|
|
420
|
+
if action not in _VALID_ACTIONS:
|
|
421
|
+
raise ValueError(f"unknown_account_action:{action}")
|
|
422
|
+
if with_index and not edition.feature_available(edition.Feature.INDEX):
|
|
423
|
+
raise edition.EditionUnavailable(edition.Feature.INDEX)
|
|
424
|
+
from .synth_authority import AuthorityRefused, sdk_error
|
|
425
|
+
|
|
426
|
+
SynthError = sdk_error(action if action != "status" else "account")
|
|
427
|
+
|
|
428
|
+
try:
|
|
429
|
+
from .enrollment import changing_credentials
|
|
430
|
+
|
|
431
|
+
with changing_credentials(create=action == "login"):
|
|
432
|
+
return _lifecycle(
|
|
433
|
+
action, device, account_only, ceiling_micros, allow_paid, renew, with_index
|
|
434
|
+
)
|
|
435
|
+
except (SynthError, AuthorityRefused) as error:
|
|
436
|
+
raise RuntimeError(f"Synth account request failed: {_refusal_code(error)}") from error
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _lifecycle(
|
|
440
|
+
action: str,
|
|
441
|
+
device: bool,
|
|
442
|
+
account_only: bool,
|
|
443
|
+
ceiling_micros: int,
|
|
444
|
+
allow_paid: bool,
|
|
445
|
+
renew: bool,
|
|
446
|
+
with_index: bool,
|
|
447
|
+
) -> dict[str, Any]:
|
|
448
|
+
from . import enrollment
|
|
449
|
+
|
|
450
|
+
if action == "login" and (
|
|
451
|
+
type(ceiling_micros) is not int
|
|
452
|
+
or not 1 <= ceiling_micros <= 1000000
|
|
453
|
+
or (account_only and allow_paid)
|
|
454
|
+
):
|
|
455
|
+
raise ValueError("invalid_inference_consent")
|
|
456
|
+
removed = None
|
|
457
|
+
sdk = authority()
|
|
458
|
+
if action == "login" and with_index and beta_env("SYNTH_CODE_CUSTOMER_KEY"):
|
|
459
|
+
raise ValueError("index_consent_requires_interactive_signin")
|
|
460
|
+
if action == "login" and (renew or with_index or sdk.status().source != "oauth"):
|
|
461
|
+
from . import oauth
|
|
462
|
+
|
|
463
|
+
# Index permissions are requested only on explicit opt-in, never by default.
|
|
464
|
+
options = (
|
|
465
|
+
{"scopes": oauth.SYNTH_CODE_OAUTH_SCOPES + oauth.INDEX_OAUTH_SCOPES}
|
|
466
|
+
if with_index
|
|
467
|
+
else {}
|
|
468
|
+
)
|
|
469
|
+
if device:
|
|
470
|
+
oauth.login_device(sdk, show=oauth.show_device_code, **options)
|
|
471
|
+
else:
|
|
472
|
+
oauth.login_pkce(sdk, **options)
|
|
473
|
+
elif action == "logout":
|
|
474
|
+
# Revoke the parent checkout key server-side while the OAuth grant is still
|
|
475
|
+
# active so even a copied local Shoal session lease is invalidated immediately.
|
|
476
|
+
if sdk.status().base_url == PRODUCTION:
|
|
477
|
+
logout_base = logout_bearer = None
|
|
478
|
+
if sdk.status().source == "oauth" and not beta_env(
|
|
479
|
+
"SYNTH_CODE_CUSTOMER_KEY"
|
|
480
|
+
):
|
|
481
|
+
try:
|
|
482
|
+
logout_base, logout_bearer = customer()
|
|
483
|
+
except AdapterError:
|
|
484
|
+
logout_base = logout_bearer = None
|
|
485
|
+
removed = enrollment.forget(base=logout_base, bearer=logout_bearer)
|
|
486
|
+
sdk.logout()
|
|
487
|
+
status = sdk.status().model_dump(mode="json")
|
|
488
|
+
if beta_env("SYNTH_CODE_CUSTOMER_KEY"):
|
|
489
|
+
status.update(authenticated=True, source="customer_environment")
|
|
490
|
+
if action == "logout":
|
|
491
|
+
status["account_state"] = "logged_out"
|
|
492
|
+
status["inference_grant"] = "logged_out"
|
|
493
|
+
if removed:
|
|
494
|
+
status["inference_logout"] = removed
|
|
495
|
+
return status
|
|
496
|
+
account: dict[str, Any] | AdapterError | None = None
|
|
497
|
+
if not status["authenticated"]:
|
|
498
|
+
status["account_state"] = "unauthenticated"
|
|
499
|
+
else:
|
|
500
|
+
try:
|
|
501
|
+
account = status["account"] = account_receipt(*customer())
|
|
502
|
+
status["account_state"] = "verified"
|
|
503
|
+
except AdapterError as error:
|
|
504
|
+
account = error
|
|
505
|
+
status["account_state"] = str(error)
|
|
506
|
+
if with_index:
|
|
507
|
+
from .oauth import INDEX_OAUTH_SCOPES
|
|
508
|
+
|
|
509
|
+
status.update(index_access(account, INDEX_OAUTH_SCOPES))
|
|
510
|
+
explicit = bool(
|
|
511
|
+
beta_env("SYNTH_CODE_INFERENCE_SESSION")
|
|
512
|
+
or beta_env("SYNTH_CODE_INFERENCE_GRANT_FILE")
|
|
513
|
+
)
|
|
514
|
+
if explicit:
|
|
515
|
+
status["inference_grant"] = "configured_unverified"
|
|
516
|
+
elif not status["authenticated"]:
|
|
517
|
+
status["inference_grant"] = "unauthenticated"
|
|
518
|
+
elif action == "login" and account_only:
|
|
519
|
+
if status["base_url"] == PRODUCTION:
|
|
520
|
+
account_base = account_bearer = None
|
|
521
|
+
if sdk.status().source == "oauth" and not beta_env(
|
|
522
|
+
"SYNTH_CODE_CUSTOMER_KEY"
|
|
523
|
+
):
|
|
524
|
+
try:
|
|
525
|
+
account_base, account_bearer = customer()
|
|
526
|
+
except AdapterError:
|
|
527
|
+
account_base = account_bearer = None
|
|
528
|
+
enrollment.forget(base=account_base, bearer=account_bearer)
|
|
529
|
+
status["inference_grant"] = "account_only"
|
|
530
|
+
elif status["account_state"] != "verified":
|
|
531
|
+
status["inference_grant"] = "account_unverified"
|
|
532
|
+
else:
|
|
533
|
+
try:
|
|
534
|
+
if action == "login":
|
|
535
|
+
lease = enrollment.enroll(ceiling_micros, allow_paid, renew=renew)
|
|
536
|
+
else:
|
|
537
|
+
lease = enrollment.active()[1]
|
|
538
|
+
status.update(inference_grant="verified", inference=lease)
|
|
539
|
+
except AdapterError as error:
|
|
540
|
+
status["inference_grant"] = str(error)
|
|
541
|
+
except OSError as error:
|
|
542
|
+
raise AdapterError(
|
|
543
|
+
f"inference_transport_error:{type(error).__name__}",
|
|
544
|
+
uncertain=action == "login",
|
|
545
|
+
) from error
|
|
546
|
+
except (ValueError, TypeError, KeyError) as error:
|
|
547
|
+
raise AccountPayloadError(
|
|
548
|
+
f"inference_authority_corrupt:{type(error).__name__}",
|
|
549
|
+
uncertain=action == "login",
|
|
550
|
+
) from error
|
|
551
|
+
return status
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Bounded JSON calls to the account and inference authorities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from urllib import error, request
|
|
8
|
+
|
|
9
|
+
from .shoal import opener
|
|
10
|
+
|
|
11
|
+
INKLING = "inkling-2-mini"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
SERVICE_HTTP = "service_http"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True, slots=True)
|
|
18
|
+
class AdapterCode:
|
|
19
|
+
"""A refusal code split into its stable base, optional detail and HTTP status.
|
|
20
|
+
|
|
21
|
+
The wire form is ``base[_status][:detail]``: ``service_http_401``,
|
|
22
|
+
``customer_credential_unavailable:sdk``. Classifiers match ``base`` and
|
|
23
|
+
``status``; ``detail`` only narrows the diagnosis.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
base: str
|
|
27
|
+
detail: str | None = None
|
|
28
|
+
status: int | None = None
|
|
29
|
+
|
|
30
|
+
def __post_init__(self):
|
|
31
|
+
if not self.base or ":" in self.base:
|
|
32
|
+
raise ValueError(f"invalid adapter code base: {self.base!r}")
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def parse(cls, wire: str) -> AdapterCode:
|
|
36
|
+
base, sep, detail = wire.partition(":")
|
|
37
|
+
head, _, tail = base.rpartition("_")
|
|
38
|
+
if head == SERVICE_HTTP and tail.isdigit():
|
|
39
|
+
return cls(head, detail if sep else None, int(tail))
|
|
40
|
+
return cls(base, detail if sep else None)
|
|
41
|
+
|
|
42
|
+
def __str__(self) -> str:
|
|
43
|
+
wire = self.base if self.status is None else f"{self.base}_{self.status}"
|
|
44
|
+
return wire if self.detail is None else f"{wire}:{self.detail}"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class AdapterError(RuntimeError):
|
|
48
|
+
"""An account/inference authority refusal; ``kind`` is the structured code."""
|
|
49
|
+
|
|
50
|
+
def __init__(self, code: str | AdapterCode, *, uncertain):
|
|
51
|
+
self.kind = code if isinstance(code, AdapterCode) else AdapterCode.parse(code)
|
|
52
|
+
self.code = str(self.kind)
|
|
53
|
+
self.uncertain = uncertain
|
|
54
|
+
super().__init__(self.code)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def api(url, token, *, payload=None, key=None, method=None):
|
|
58
|
+
mutating = payload is not None or (
|
|
59
|
+
method is not None and method not in ("GET", "HEAD")
|
|
60
|
+
)
|
|
61
|
+
headers = {"Authorization": "Bearer " + token}
|
|
62
|
+
if payload is not None:
|
|
63
|
+
headers["Content-Type"] = "application/json"
|
|
64
|
+
if key:
|
|
65
|
+
headers["Idempotency-Key"] = key
|
|
66
|
+
req = request.Request(
|
|
67
|
+
url,
|
|
68
|
+
headers=headers,
|
|
69
|
+
data=json.dumps(payload).encode() if payload is not None else None,
|
|
70
|
+
method=method,
|
|
71
|
+
)
|
|
72
|
+
try:
|
|
73
|
+
with opener().open(req, timeout=20) as response:
|
|
74
|
+
data = response.read(131073)
|
|
75
|
+
if len(data) > 131072:
|
|
76
|
+
raise AdapterError("service_response_limit", uncertain=mutating)
|
|
77
|
+
if not data and response.status == 204:
|
|
78
|
+
return {}, response.headers
|
|
79
|
+
return json.loads(data), response.headers
|
|
80
|
+
except error.HTTPError as exc:
|
|
81
|
+
raise AdapterError(
|
|
82
|
+
AdapterCode(SERVICE_HTTP, status=exc.code),
|
|
83
|
+
uncertain=mutating and exc.code >= 500,
|
|
84
|
+
) from exc
|
|
85
|
+
except (TimeoutError, error.URLError) as exc:
|
|
86
|
+
raise AdapterError("service_unreachable", uncertain=mutating) from exc
|