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
synth_code/daemon.py ADDED
@@ -0,0 +1,34 @@
1
+ """Resolve the verified packaged executable and its matching adapter interpreter.
2
+
3
+ ``synth-code-daemon [--source-runtime PATH] STATE TARGET``. A checkout without a
4
+ wheel names its runtime explicitly with ``--source-runtime``; otherwise only the
5
+ manifest-verified ``synth_code/native/synth-code-runtime`` is executed.
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from .native import NativeRuntime, NativeRuntimeRefused, installed_runtime, source_runtime
13
+ from .panel_request import STATE_ENV
14
+
15
+ SOURCE_RUNTIME_FLAG = "--source-runtime"
16
+
17
+
18
+ def select_runtime(arguments: list[str]) -> tuple[NativeRuntime, list[str]]:
19
+ if arguments[:1] == [SOURCE_RUNTIME_FLAG]:
20
+ if len(arguments) < 2:
21
+ raise NativeRuntimeRefused("native_runtime_missing", Path(SOURCE_RUNTIME_FLAG))
22
+ return source_runtime(Path(arguments[1])), arguments[2:]
23
+ return installed_runtime(), arguments
24
+
25
+
26
+ def main():
27
+ try:
28
+ runtime, arguments = select_runtime(sys.argv[1:])
29
+ except NativeRuntimeRefused as refusal:
30
+ raise SystemExit(str(refusal)) from refusal
31
+ if len(arguments) == 2:
32
+ os.environ[STATE_ENV] = str(Path(arguments[0]).resolve(strict=True))
33
+ os.environ["SYNTH_CODE_PROVIDER_PYTHON"] = sys.executable
34
+ os.execv(runtime.path, [str(runtime.path), *arguments])
synth_code/edition.py ADDED
@@ -0,0 +1,306 @@
1
+ """The runtime edition the attached terminal presents.
2
+
3
+ The Rust runtime announces its edition in the ``initialize`` reply. A runtime that predates
4
+ the field is the full beta edition, so an absent field keeps today's behaviour. A present
5
+ but unknown value is refused: the terminal never guesses which surfaces a runtime offers.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import re
12
+ from enum import StrEnum
13
+ from importlib import import_module
14
+ from importlib.util import find_spec
15
+ from types import ModuleType
16
+
17
+ __all__ = [
18
+ "BETA_ENV_SWITCHES",
19
+ "BUILD_EDITION",
20
+ "EDITION_FIELD",
21
+ "FEATURE_MODULES",
22
+ "FEATURE_SKILL_ACTIONS",
23
+ "PUBLIC_HIDDEN_COMMANDS",
24
+ "Edition",
25
+ "EditionUnavailable",
26
+ "AutoApproveUnavailable",
27
+ "auto_approve_available",
28
+ "EditionUnknown",
29
+ "Feature",
30
+ "QUALIFY_TWIN_MARKER",
31
+ "QUALIFY_TWIN_MARKER_VALUE",
32
+ "QUALIFY_TWIN_SHOAL_ORIGIN",
33
+ "QualificationTwinRefused",
34
+ "command_available",
35
+ "edition_from_initialize",
36
+ "feature_available",
37
+ "beta_env",
38
+ "qualification_shoal_origin",
39
+ "require_feature",
40
+ "require_skill_action",
41
+ "side_agents_available",
42
+ ]
43
+
44
+ EDITION_FIELD = "edition"
45
+
46
+
47
+ class Edition(StrEnum):
48
+ BETA = "beta"
49
+ PUBLIC = "public"
50
+
51
+
52
+ # The edition this Python tree was built as. The public export rewrites this one line
53
+ # (export/public-manifest.toml [[rewrite]]); every beta-only switch below keys off it.
54
+ BUILD_EDITION = Edition.PUBLIC
55
+
56
+ # Test and internal environment switches. The beta build honours them; the public build
57
+ # never reads them. The one plaintext origin either build accepts is the qualification
58
+ # twin below: loopback 127.0.0.1 only, and only with the harness's explicit marker.
59
+ BETA_ENV_SWITCHES = frozenset(
60
+ {
61
+ "SYNTH_CODE_FIXTURE",
62
+ "SYNTH_CODE_SHOAL_ORIGIN",
63
+ "SYNTH_CODE_INFERENCE_SESSION",
64
+ "SYNTH_CODE_INFERENCE_GRANT_FILE",
65
+ "SYNTH_CODE_INFERENCE_CHECKPOINT",
66
+ "SYNTH_CODE_CUSTOMER_KEY",
67
+ "SYNTH_CODE_ORG",
68
+ # Synth SDK origin and credential-file overrides (synth_authority.for_build).
69
+ "SYNTH_API_BASE_URL",
70
+ "SYNTH_OAUTH_BASE_URL",
71
+ "SYNTH_AUTH_FILE",
72
+ }
73
+ )
74
+
75
+
76
+ def beta_env(name: str, default: str | None = None) -> str | None:
77
+ """Read a beta-only switch; the public build ignores it and returns ``default``."""
78
+ if name not in BETA_ENV_SWITCHES:
79
+ raise KeyError(f"beta_env_unknown_switch: {name}")
80
+ if BUILD_EDITION is not Edition.BETA:
81
+ return default
82
+ return os.environ.get(name, default)
83
+
84
+
85
+ # Qualification twin (TEMPER_TOOL_LOOP.md §9): scripts/qualify.py points the installed public
86
+ # wheel at a loopback Shoal. The provider runs under `python -I`, so the seam is two plain
87
+ # environment variables the runtime passes through; both must be set, the marker to its one
88
+ # exact value. The origin is exactly http://127.0.0.1:<port>; the token is "fixture-only".
89
+ QUALIFY_TWIN_MARKER = "SYNTH_QUALIFY_TWIN"
90
+ QUALIFY_TWIN_MARKER_VALUE = "loopback-shoal-v1"
91
+ QUALIFY_TWIN_SHOAL_ORIGIN = "SYNTH_QUALIFY_SHOAL_ORIGIN"
92
+ _LOOPBACK_ORIGIN = re.compile(r"http://127\.0\.0\.1:([1-9][0-9]{0,4})")
93
+
94
+
95
+ class QualificationTwinRefused(ValueError):
96
+ """The qualification-twin Shoal origin is set but the seam's conditions do not hold.
97
+
98
+ The message names the failed check only, never the configured value: a refused origin
99
+ may carry userinfo.
100
+ """
101
+
102
+ code = "qualification_twin_refused"
103
+ stage = "shoal_origin"
104
+
105
+ def __init__(self, failed_check: str) -> None:
106
+ self.failed_check = failed_check
107
+ super().__init__(
108
+ f"{self.code} service=synth-code stage={self.stage} failed_check={failed_check}: "
109
+ f"{QUALIFY_TWIN_SHOAL_ORIGIN} is set but the qualification twin is not enabled"
110
+ )
111
+
112
+
113
+ def qualification_shoal_origin() -> str | None:
114
+ """The loopback Shoal origin the qualify harness set, or ``None`` when it set none.
115
+
116
+ Absent origin: ``None``, so production resolution is unchanged. Present origin: it is
117
+ honoured only with the exact marker and only as ``http://127.0.0.1:<1..65535>``; anything
118
+ else refuses typed and never falls through to production.
119
+ """
120
+ origin = os.environ.get(QUALIFY_TWIN_SHOAL_ORIGIN)
121
+ if origin is None:
122
+ return None
123
+ if os.environ.get(QUALIFY_TWIN_MARKER) != QUALIFY_TWIN_MARKER_VALUE:
124
+ raise QualificationTwinRefused("qualification_marker")
125
+ match = _LOOPBACK_ORIGIN.fullmatch(origin)
126
+ if match is None or int(match.group(1)) > 65535:
127
+ raise QualificationTwinRefused("loopback_http_origin")
128
+ return origin
129
+
130
+
131
+ class EditionUnknown(ValueError):
132
+ """The runtime's initialize reply names an edition this terminal does not know."""
133
+
134
+ code = "edition_unknown"
135
+ stage = "initialize"
136
+ failed_check = "edition_in_known_set"
137
+
138
+ def __init__(self, actual: object) -> None:
139
+ self.actual = actual
140
+ self.expected = tuple(edition.value for edition in Edition)
141
+ super().__init__(
142
+ f"{self.code}: runtime edition {actual!r} is not one of {', '.join(self.expected)}"
143
+ )
144
+
145
+
146
+ class Feature(StrEnum):
147
+ """Beta-only surfaces whose modules the public export omits."""
148
+
149
+ RESEARCH = "research"
150
+ CAMPAIGN = "campaign"
151
+ ITERATION = "iteration"
152
+ HOSTED_SERVICES = "hosted_services"
153
+ HOSTED_ARTIFACTS = "hosted_artifacts"
154
+ INDEX = "index"
155
+ MULTI_AGENT = "multi_agent"
156
+ PLUGINS = "plugins"
157
+
158
+
159
+ # The only place the terminal names a module the public export excludes. Every use goes
160
+ # through require_feature, so the export refuses with a typed error, never ImportError.
161
+ FEATURE_MODULES: dict[Feature, str] = {
162
+ Feature.RESEARCH: f"{__package__}.research_cli",
163
+ Feature.CAMPAIGN: f"{__package__}.campaign",
164
+ Feature.ITERATION: f"{__package__}.iteration",
165
+ Feature.HOSTED_SERVICES: f"{__package__}.services",
166
+ Feature.HOSTED_ARTIFACTS: f"{__package__}.artifacts",
167
+ Feature.INDEX: f"{__package__}.index",
168
+ # Delegated and side agents: the subagents pack is their surface (spawn, close, the
169
+ # subagent-delegation guide); the public export omits it (§7 decision 2).
170
+ Feature.MULTI_AGENT: "synth_code_plugins.subagents",
171
+ # Plugin packs (the runtime's EditionFeature::Plugins; skill pins are documents of the
172
+ # `skills` pack). The public runtime enables no pack; the beta-only hillclimb pack
173
+ # stands for the set the export omits.
174
+ Feature.PLUGINS: "synth_code_plugins.hillclimb",
175
+ }
176
+
177
+
178
+ class EditionUnavailable(RuntimeError):
179
+ """This edition does not ship the feature the caller asked for."""
180
+
181
+ code = "edition_unavailable"
182
+ stage = "feature_gate"
183
+ failed_check = "feature_module_shipped"
184
+
185
+ def __init__(self, feature: Feature) -> None:
186
+ self.feature = feature
187
+ self.module = FEATURE_MODULES[feature]
188
+ super().__init__(
189
+ f"{self.code}: {feature.value} is not part of this Synth Code edition"
190
+ )
191
+
192
+
193
+ def feature_available(feature: Feature) -> bool:
194
+ """True only in the beta build, and only where the feature's module ships.
195
+
196
+ The public wheel is the beta tree with ``BUILD_EDITION`` rewritten (scripts/package.py),
197
+ so a beta-only module can be present on disk there; its presence never enables it.
198
+ """
199
+ if BUILD_EDITION is not Edition.BETA:
200
+ return False
201
+ return find_spec(FEATURE_MODULES[feature]) is not None
202
+
203
+
204
+ def require_feature(feature: Feature) -> ModuleType:
205
+ """Import the feature's module, or refuse typed when this edition omits it.
206
+
207
+ Only absence maps to the refusal: a failure inside a shipped module still raises.
208
+ """
209
+ if not feature_available(feature):
210
+ raise EditionUnavailable(feature)
211
+ return import_module(FEATURE_MODULES[feature])
212
+
213
+
214
+ # Commands whose runtime surfaces the single-agent public edition refuses: delegated and
215
+ # side agents, research and experiment views, and notebook publication.
216
+ PUBLIC_HIDDEN_COMMANDS = frozenset(
217
+ {
218
+ "subagents",
219
+ "sideagents",
220
+ "yolo",
221
+ "mcp",
222
+ "sidebar",
223
+ "agents",
224
+ "grade",
225
+ "constraint",
226
+ "explain",
227
+ "recommend",
228
+ "preference",
229
+ "choose",
230
+ "study",
231
+ "trial",
232
+ "panel",
233
+ "publish",
234
+ }
235
+ )
236
+
237
+
238
+ # CLI commands that exist only where their feature is available. Elsewhere the CLI does
239
+ # not register them, so help never names them, and an invocation refuses typed
240
+ # (edition_unavailable) before any of the feature's modules is imported.
241
+ FEATURE_COMMANDS: dict[str, Feature] = {
242
+ "swarm-start": Feature.HOSTED_SERVICES,
243
+ "publish": Feature.HOSTED_ARTIFACTS,
244
+ "artifact": Feature.HOSTED_ARTIFACTS,
245
+ "share": Feature.HOSTED_ARTIFACTS,
246
+ "unshare": Feature.HOSTED_ARTIFACTS,
247
+ "swarm-file": Feature.HOSTED_SERVICES,
248
+ "swarm-result": Feature.HOSTED_SERVICES,
249
+ "index": Feature.INDEX,
250
+ "iterate": Feature.ITERATION,
251
+ "spawn": Feature.MULTI_AGENT,
252
+ "close": Feature.MULTI_AGENT,
253
+ }
254
+
255
+ # `skill` actions that exist only where their feature is available: help and completions
256
+ # omit them elsewhere, and an invocation refuses typed (edition_unavailable) before the
257
+ # runtime is asked.
258
+ FEATURE_SKILL_ACTIONS: dict[str, Feature] = {
259
+ "pin": Feature.PLUGINS,
260
+ "unpin": Feature.PLUGINS,
261
+ }
262
+
263
+
264
+ def require_skill_action(verb: str) -> None:
265
+ """Refuse typed when this edition omits the feature a `skill` action needs."""
266
+ feature = FEATURE_SKILL_ACTIONS.get(verb)
267
+ if feature is not None and not feature_available(feature):
268
+ raise EditionUnavailable(feature)
269
+
270
+
271
+ def edition_from_initialize(metadata: dict) -> Edition:
272
+ """Read the edition capability from an initialize reply; absent means beta."""
273
+ if EDITION_FIELD not in metadata:
274
+ return Edition.BETA
275
+ value = metadata[EDITION_FIELD]
276
+ if not isinstance(value, str):
277
+ raise EditionUnknown(value)
278
+ try:
279
+ return Edition(value)
280
+ except ValueError as error:
281
+ raise EditionUnknown(value) from error
282
+
283
+
284
+ class AutoApproveUnavailable(ValueError):
285
+ """Public v0.0.1 has no auto-approve: every write needs an owner decision."""
286
+
287
+ code = "edition_unavailable"
288
+ stage = "feature_gate"
289
+
290
+ def __init__(self) -> None:
291
+ super().__init__(
292
+ f"{self.code}: auto-approve (YOLO) is not part of this Synth Code edition"
293
+ )
294
+
295
+
296
+ def auto_approve_available(edition: Edition) -> bool:
297
+ return edition is not Edition.PUBLIC
298
+
299
+
300
+ def command_available(name: str, edition: Edition) -> bool:
301
+ return edition is not Edition.PUBLIC or name not in PUBLIC_HIDDEN_COMMANDS
302
+
303
+
304
+ def side_agents_available(edition: Edition) -> bool:
305
+ """Side-agent and subagent panels (F2/F3, panel requests) exist only in beta."""
306
+ return edition is not Edition.PUBLIC
@@ -0,0 +1,304 @@
1
+ """Bind explicit browser consent to one expiring Shoal budget in the public SDK store."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import fcntl
7
+ import json
8
+ import os
9
+ import stat
10
+ import time
11
+ import uuid
12
+ from datetime import datetime
13
+ from decimal import Decimal, InvalidOperation
14
+
15
+ from . import account
16
+ from .account_http import INKLING, SERVICE_HTTP, AdapterCode, AdapterError, api
17
+ from .edition import beta_env
18
+
19
+ SHOAL = "https://shoal.usesynth.ai"
20
+ MARKER = "synth-code-shoal-v1/"
21
+ DEFAULT_CAP = 50000
22
+
23
+
24
+ def refuse(code):
25
+ raise AdapterError(code, uncertain=False)
26
+
27
+
28
+ @contextlib.contextmanager
29
+ def changing_credentials(*, create=True):
30
+ path = account.authority().token_path()
31
+ if not create and not path.exists():
32
+ yield
33
+ return
34
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
35
+ fd = os.open(
36
+ str(path) + ".synth-code.lock", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600
37
+ )
38
+ try:
39
+ info = os.fstat(fd)
40
+ if (
41
+ not stat.S_ISREG(info.st_mode)
42
+ or info.st_uid != os.getuid()
43
+ or info.st_mode & 0o077
44
+ ):
45
+ refuse("unsafe_credential_lock")
46
+ fcntl.flock(fd, fcntl.LOCK_EX)
47
+ yield
48
+ finally:
49
+ os.close(fd)
50
+
51
+
52
+ def scoped_identity():
53
+ sdk = account.authority()
54
+ if sdk.status().source != "oauth" or beta_env("SYNTH_CODE_CUSTOMER_KEY"):
55
+ refuse("interactive_account_grant_required")
56
+ base = sdk.status().base_url
57
+ if base != account.PRODUCTION or sdk.oauth_base(base) != sdk.DEFAULT_OAUTH_BASE_URL:
58
+ refuse("inference_origin_unpaired")
59
+ credential_origin, bearer = account.customer()
60
+ # The stored credential must belong to the origin the SDK reported, or the
61
+ # inference lease would bind one account's grant to another's origin.
62
+ if credential_origin != base:
63
+ refuse("inference_origin_unpaired")
64
+ facts, _ = api(base + "/v1/hillclimb/auth/whoami", bearer)
65
+ if (
66
+ facts.get("credential_kind") != "oauth"
67
+ or facts.get("credential_purpose") != "oauth"
68
+ or "swarms:run" not in facts.get("scopes", [])
69
+ ):
70
+ refuse("inference_consent_required")
71
+ org = facts.get("org_id")
72
+ if not all(
73
+ isinstance(facts.get(k), str) and facts[k]
74
+ for k in ("org_id", "user_id", "credential_id")
75
+ ):
76
+ refuse("inference_principal_unconfirmed")
77
+ if beta_env("SYNTH_CODE_ORG", org) != org:
78
+ refuse("account_org_mismatch")
79
+ binding = {k: facts[k] for k in ("org_id", "user_id", "credential_id")}
80
+ return base, bearer, {"origin": base, **binding}
81
+
82
+
83
+ def seconds(value):
84
+ d = datetime.fromisoformat(value)
85
+ if d.tzinfo is None:
86
+ refuse("inference_time_unconfirmed")
87
+ return d.timestamp()
88
+
89
+
90
+ def money(obj):
91
+ if not isinstance(obj, dict) or obj.get("currency") != "USD":
92
+ refuse("inference_funding_unknown")
93
+ try:
94
+ amount = Decimal(obj["amount"])
95
+ if not amount.is_finite():
96
+ refuse("inference_funding_unknown")
97
+ return amount * 1000000
98
+ except (KeyError, InvalidOperation, TypeError, ValueError):
99
+ refuse("inference_funding_unknown")
100
+
101
+
102
+ def check_funding(base, bearer, binding, cap, paid, *, reserved):
103
+ funds, _ = api(base + "/v1/billing/balance", bearer)
104
+ if funds.get("org_id") != binding["org_id"]:
105
+ refuse("funding_org_mismatch")
106
+ if not reserved and money(funds.get("available")) < cap:
107
+ refuse("shoal_allowance_exhausted")
108
+ if paid:
109
+ return
110
+ allowance = funds.get("included_allowance")
111
+ if (
112
+ funds.get("plan") != "free"
113
+ or funds.get("payg_credits_active") is not False
114
+ or not isinstance(allowance, dict)
115
+ or any(
116
+ money(funds.get(k)) != 0
117
+ for k in (
118
+ "purchased_credits",
119
+ "promotional_credits",
120
+ "operator_credits",
121
+ "debt",
122
+ )
123
+ )
124
+ ):
125
+ refuse("included_funding_unconfirmed")
126
+ # A hold already created for this lease counts in the organization's held amount.
127
+ # Refuse near rollover so the admitted lease cannot span funding cycles.
128
+ headroom = money(allowance.get("remaining")) - money(funds.get("held"))
129
+ if headroom < (0 if reserved else cap) or money(allowance.get("remaining")) <= 0:
130
+ refuse("shoal_allowance_exhausted")
131
+ if seconds(allowance["reset_at"]) <= time.time() + (60 if reserved else 3660):
132
+ refuse("included_allowance_reset_pending")
133
+
134
+
135
+ def own_record():
136
+ record = account.authority().read_tokens().get(SHOAL)
137
+ if record is None:
138
+ return None, {}
139
+ marker = record.client_id or ""
140
+ if not marker.startswith(MARKER):
141
+ refuse("shoal_credential_slot_occupied")
142
+ return record, json.loads(marker[len(MARKER) :])
143
+
144
+
145
+ def canonical_key_uuid(raw_key_id):
146
+ if not isinstance(raw_key_id, str) or not raw_key_id:
147
+ return None
148
+ try:
149
+ parsed = uuid.UUID(raw_key_id)
150
+ except ValueError:
151
+ return None
152
+ return str(parsed) if str(parsed) == raw_key_id.lower() else None
153
+
154
+
155
+ def revoke_parent_key(base, bearer, raw_key_id):
156
+ key_uuid = canonical_key_uuid(raw_key_id)
157
+ if not base or not bearer or not key_uuid:
158
+ return "expires_independently"
159
+ try:
160
+ api(
161
+ f"{base.rstrip('/')}/v1/hillclimb/auth/checkout-key/{key_uuid}",
162
+ bearer,
163
+ method="DELETE",
164
+ )
165
+ return "revoked"
166
+ except AdapterError as error:
167
+ if error.uncertain:
168
+ return "uncertain"
169
+ return "expires_independently"
170
+
171
+
172
+ def forget(*, base=None, bearer=None):
173
+ sdk = account.authority()
174
+ records = sdk.read_tokens()
175
+ record = records.get(SHOAL)
176
+ if record and (record.client_id or "").startswith(MARKER):
177
+ meta = json.loads(record.client_id[len(MARKER) :])
178
+ del records[SHOAL]
179
+ sdk.save_tokens(records)
180
+ revocation = revoke_parent_key(base, bearer, meta.get("parent_key_id"))
181
+ return {
182
+ "local": "removed",
183
+ "remote_expires_at": record.expires_at,
184
+ "remote_revocation": revocation,
185
+ }
186
+ return {"local": "absent"}
187
+
188
+
189
+ def enroll(cap, paid, *, renew=False):
190
+ if type(cap) is not int or not 1 <= cap <= 1000000:
191
+ refuse("invalid_inference_ceiling")
192
+ base, bearer, binding = scoped_identity()
193
+ record, old = own_record()
194
+ if (
195
+ not renew
196
+ and record is not None
197
+ and record.expires_at > time.time()
198
+ and old.get("binding") == binding
199
+ ):
200
+ if old["ceiling_micros"] != cap or old["paid_opt_in"] != paid:
201
+ refuse("inference_consent_conflict")
202
+ try:
203
+ return active()[1]
204
+ except AdapterError as error:
205
+ if not (
206
+ error.kind.base == "shoal_session_expired"
207
+ or (error.kind.base == SERVICE_HTTP and error.kind.status in (401, 403))
208
+ ):
209
+ raise
210
+ check_funding(base, bearer, binding, cap, paid, reserved=False)
211
+ if old.get("parent_key_id"):
212
+ revoke_parent_key(base, bearer, old["parent_key_id"])
213
+ # Each fresh lease issuance uses a unique single-use request_id so re-enrollment
214
+ # after a 1-hour Shoal expiry or logout succeeds within a 30-day OAuth grant.
215
+ request_id = uuid.uuid4()
216
+ try:
217
+ parent, _ = api(
218
+ base + "/v1/hillclimb/auth/checkout-key",
219
+ bearer,
220
+ key=str(request_id),
221
+ payload={
222
+ "label": "Synth Code Inkling",
223
+ "request_id": str(request_id),
224
+ "ttl_days": 1,
225
+ },
226
+ )
227
+ except AdapterError as error:
228
+ # A definite 404 means this deployment has no checkout route, not a lost key.
229
+ if error.kind == AdapterCode(SERVICE_HTTP, status=404) and not error.uncertain:
230
+ raise AdapterError("inference_checkout_unavailable", uncertain=False) from error
231
+ raise
232
+ if (
233
+ parent.get("purpose") != "automation"
234
+ or "swarms:run" not in parent.get("scopes", [])
235
+ or any(parent.get(k) != binding[k] for k in ("org_id", "user_id"))
236
+ or not parent.get("api_key")
237
+ or not parent.get("key_id")
238
+ ):
239
+ refuse("checkout_authority_mismatch")
240
+ lease, _ = api(
241
+ SHOAL + "/v1/sessions",
242
+ parent.pop("api_key"),
243
+ payload={"request_id": request_id.hex, "ceiling_micros": cap},
244
+ )
245
+ expiry = seconds(lease["expires_at"])
246
+ if (
247
+ lease.get("ceiling_micros") != cap
248
+ or not lease.get("budget_scope_id")
249
+ or not isinstance(lease.get("session_token"), str)
250
+ or not lease["session_token"]
251
+ or not time.time() < expiry <= time.time() + 3660
252
+ ):
253
+ refuse("shoal_lease_unconfirmed")
254
+ meta = {
255
+ "binding": binding,
256
+ "budget_scope_id": lease["budget_scope_id"],
257
+ "ceiling_micros": cap,
258
+ "expires_at": lease["expires_at"],
259
+ "paid_opt_in": paid,
260
+ "parent_key_id": parent["key_id"],
261
+ }
262
+ sdk = account.authority()
263
+ records = sdk.read_tokens()
264
+ if records.get(SHOAL) != record:
265
+ refuse("shoal_credential_changed")
266
+ records[SHOAL] = {
267
+ "client_id": MARKER + json.dumps(meta, sort_keys=True),
268
+ "access_token": lease["session_token"],
269
+ "expires_at": expiry,
270
+ }
271
+ sdk.save_tokens(records)
272
+ return active()[1]
273
+
274
+
275
+ def active():
276
+ record, meta = own_record()
277
+ if record is None:
278
+ refuse("shoal_inference_grant_required")
279
+ if record.expires_at <= time.time():
280
+ refuse("shoal_session_expired")
281
+ base, bearer, binding = scoped_identity()
282
+ if meta.get("binding") != binding:
283
+ refuse("inference_principal_changed")
284
+ cap = meta["ceiling_micros"]
285
+ check_funding(base, bearer, binding, cap, meta["paid_opt_in"], reserved=True)
286
+ budget, _ = api(SHOAL + "/v1/session-budget", record.access_token)
287
+ if (
288
+ budget.get("currency") != "USD"
289
+ or budget.get("root_budget_scope_id") != meta["budget_scope_id"]
290
+ or budget.get("ceiling_micros") != cap
291
+ or type(budget.get("remaining_micros")) is not int
292
+ ):
293
+ refuse("shoal_session_budget_mismatch")
294
+ if not 0 < budget["remaining_micros"] <= cap:
295
+ refuse("shoal_allowance_exhausted")
296
+ models, _ = api(SHOAL + "/v1/models", record.access_token)
297
+ if not any(m.get("id") == INKLING for m in models.get("data", [])):
298
+ refuse("inkling_unavailable")
299
+ return record.access_token, {
300
+ **meta,
301
+ "remaining_micros": budget["remaining_micros"],
302
+ "settled_micros": budget.get("settled_micros"),
303
+ "model": INKLING,
304
+ }
@@ -0,0 +1,10 @@
1
+ """Distinguish file generation from its separate approval and delivery effect."""
2
+
3
+ from .protocol import Event
4
+
5
+
6
+ def is_file_edit(event: Event) -> bool:
7
+ return (
8
+ event["kind"] in {"effect.proposed", "effect.refused"}
9
+ and event["payload"].get("kind") == "file_edit"
10
+ )