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,269 @@
1
+ """Strict TOML loader. Entrypoints are names supplied by the fixture host."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import tomllib
7
+ from collections.abc import Callable
8
+ from enum import StrEnum
9
+ from typing import TypeVar, cast
10
+
11
+ from .contracts import (
12
+ MAX_PAYLOAD_BYTES,
13
+ SYNTH_API,
14
+ Activation,
15
+ ApprovalTier,
16
+ ContractError,
17
+ CursorSpec,
18
+ Density,
19
+ EntrypointSpec,
20
+ Manifest,
21
+ PanelSpec,
22
+ Permission,
23
+ PrimitiveKind,
24
+ Refusal,
25
+ RefusalCode,
26
+ SourceBounds,
27
+ SourceSpec,
28
+ ToolSpec,
29
+ ToolVerb,
30
+ Transport,
31
+ ViewSpec,
32
+ )
33
+
34
+ __all__ = ("load_manifest",)
35
+
36
+ _IDENTIFIER = re.compile(r"[a-z][a-z0-9_-]{0,63}")
37
+ _VERSION = re.compile(r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)")
38
+ _MAX_MANIFEST_CHARS = 64 * 1024
39
+ _MAX_DECLARATIONS = 64
40
+ T = TypeVar("T")
41
+ E = TypeVar("E", bound=StrEnum)
42
+
43
+
44
+ class _ManifestReader:
45
+ def __init__(self) -> None:
46
+ self.plugin = "<unknown>"
47
+
48
+ def fail(self, field: str, detail: str) -> ContractError:
49
+ return ContractError(Refusal(RefusalCode.MANIFEST_INVALID, self.plugin, field, detail))
50
+
51
+ def table(
52
+ self, value: object, field: str, required: str, optional: str = ""
53
+ ) -> dict[str, object]:
54
+ if not isinstance(value, dict):
55
+ raise self.fail(field, "expected a TOML table")
56
+ result = cast(dict[str, object], value)
57
+ missing = set(required.split()) - result.keys()
58
+ unknown = result.keys() - set((required + " " + optional).split())
59
+ if missing or unknown:
60
+ raise self.fail(
61
+ field, f"missing fields {sorted(missing)}, unknown fields {sorted(unknown)}"
62
+ )
63
+ return result
64
+
65
+ def identifier(self, value: object, field: str) -> str:
66
+ if not isinstance(value, str) or _IDENTIFIER.fullmatch(value) is None:
67
+ raise self.fail(field, "expected a lowercase identifier (1–64 characters)")
68
+ return value
69
+
70
+ def integer(self, value: object, field: str, maximum: int) -> int:
71
+ if type(value) is not int or not 1 <= value <= maximum:
72
+ raise self.fail(field, f"expected an integer in 1..{maximum}")
73
+ return value
74
+
75
+ def choice(self, value: object, field: str, enum: type[E]) -> E:
76
+ if not isinstance(value, str):
77
+ raise self.fail(field, "expected a string enum")
78
+ try:
79
+ return enum(value)
80
+ except ValueError as error:
81
+ raise self.fail(field, f"unknown {enum.__name__} {value!r}") from error
82
+
83
+ def items(self, value: object, field: str, parse: Callable[[object, str], T]) -> tuple[T, ...]:
84
+ if not isinstance(value, list):
85
+ raise self.fail(field, "expected an array")
86
+ if len(value) > _MAX_DECLARATIONS:
87
+ raise self.fail(field, f"array exceeds {_MAX_DECLARATIONS} entries")
88
+ return tuple(parse(item, f"{field}[{index}]") for index, item in enumerate(value))
89
+
90
+ def unique(self, values: tuple[T, ...], field: str) -> tuple[T, ...]:
91
+ if len(values) != len(set(values)):
92
+ raise self.fail(field, "duplicate entries")
93
+ return values
94
+
95
+ def identifiers(self, value: object, field: str) -> tuple[str, ...]:
96
+ return self.unique(self.items(value, field, self.identifier), field)
97
+
98
+ def source(self, value: object, field: str) -> SourceSpec:
99
+ source = self.table(value, field, "id dialect dialect_version schema_ref transport bounds")
100
+ mode = self.choice(source["transport"], field + ".transport", Transport)
101
+ required = "max_payload_bytes"
102
+ if mode is Transport.OFFSET_APPEND:
103
+ required += " max_tail_bytes"
104
+ bounds = self.table(source["bounds"], field + ".bounds", required)
105
+ max_tail_bytes = None
106
+ if mode is Transport.OFFSET_APPEND:
107
+ max_tail_bytes = self.integer(
108
+ bounds["max_tail_bytes"], field + ".bounds.max_tail_bytes", MAX_PAYLOAD_BYTES
109
+ )
110
+ return SourceSpec(
111
+ self.identifier(source["id"], field + ".id"),
112
+ self.identifier(source["dialect"], field + ".dialect"),
113
+ self.integer(source["dialect_version"], field + ".dialect_version", 2**31 - 1),
114
+ self.identifier(source["schema_ref"], field + ".schema_ref"),
115
+ mode,
116
+ SourceBounds(
117
+ self.integer(
118
+ bounds["max_payload_bytes"],
119
+ field + ".bounds.max_payload_bytes",
120
+ MAX_PAYLOAD_BYTES,
121
+ ),
122
+ max_tail_bytes,
123
+ ),
124
+ )
125
+
126
+ def panel(self, value: object, field: str) -> PanelSpec:
127
+ panel = self.table(value, field, "id sources")
128
+ sources = self.identifiers(panel["sources"], field + ".sources")
129
+ if not sources:
130
+ raise self.fail(field + ".sources", "panel must bind at least one source")
131
+ return PanelSpec(self.identifier(panel["id"], field + ".id"), sources)
132
+
133
+ def cursor(self, value: object, field: str) -> CursorSpec:
134
+ cursor = self.table(value, field, "id schema_ref")
135
+ return CursorSpec(
136
+ self.identifier(cursor["id"], field + ".id"),
137
+ self.identifier(cursor["schema_ref"], field + ".schema_ref"),
138
+ )
139
+
140
+ def view(self, value: object, field: str) -> ViewSpec:
141
+ view = self.table(value, field, "id panel density primitive", "emits consumes")
142
+ return ViewSpec(
143
+ self.identifier(view["id"], field + ".id"),
144
+ self.identifier(view["panel"], field + ".panel"),
145
+ self.choice(view["density"], field + ".density", Density),
146
+ self.choice(view["primitive"], field + ".primitive", PrimitiveKind),
147
+ self.identifiers(view.get("emits", []), field + ".emits"),
148
+ self.identifiers(view.get("consumes", []), field + ".consumes"),
149
+ )
150
+
151
+ def verb(self, value: object, field: str) -> ToolVerb:
152
+ verb = self.table(value, field, "id approval input_schema_ref output_schema_ref")
153
+ return ToolVerb(
154
+ self.identifier(verb["id"], field + ".id"),
155
+ self.choice(verb["approval"], field + ".approval", ApprovalTier),
156
+ self.identifier(verb["input_schema_ref"], field + ".input_schema_ref"),
157
+ self.identifier(verb["output_schema_ref"], field + ".output_schema_ref"),
158
+ )
159
+
160
+
161
+ def load_manifest(toml: str) -> Manifest:
162
+ """Parse a fixture plugin manifest, refusing unknown fields and closed-enum values."""
163
+ reader = _ManifestReader()
164
+ if len(toml) > _MAX_MANIFEST_CHARS:
165
+ raise reader.fail("plugin.toml", f"manifest exceeds {_MAX_MANIFEST_CHARS} characters")
166
+ try:
167
+ document = tomllib.loads(toml)
168
+ except tomllib.TOMLDecodeError as error:
169
+ raise reader.fail("plugin.toml", str(error)) from error
170
+
171
+ reader.plugin = reader.identifier(document.get("id"), "id")
172
+ data = reader.table(
173
+ document,
174
+ "plugin.toml",
175
+ "id version synth_api activation permissions entrypoints",
176
+ "sources panels cursors views tool",
177
+ )
178
+ version = data["version"]
179
+ if not isinstance(version, str) or _VERSION.fullmatch(version) is None:
180
+ raise reader.fail("version", "expected a numeric major.minor.patch version")
181
+ synth_api = reader.integer(data["synth_api"], "synth_api", 2**31 - 1)
182
+ if synth_api != SYNTH_API:
183
+ raise ContractError(
184
+ Refusal(
185
+ RefusalCode.API_VERSION,
186
+ reader.plugin,
187
+ "synth_api",
188
+ "unsupported SDK API",
189
+ expected=SYNTH_API,
190
+ actual=synth_api,
191
+ )
192
+ )
193
+ entrypoints = reader.table(
194
+ data["entrypoints"], "entrypoints", "", "skill context renderer tool"
195
+ )
196
+
197
+ tool = None
198
+ if "tool" in data:
199
+ tool_data = reader.table(data["tool"], "tool", "name verbs")
200
+ verbs = reader.items(tool_data["verbs"], "tool.verbs", reader.verb)
201
+ if not verbs:
202
+ raise reader.fail("tool.verbs", "tool facade must declare at least one verb")
203
+ reader.unique(tuple(verb.id for verb in verbs), "tool.verbs")
204
+ tool = ToolSpec(reader.identifier(tool_data["name"], "tool.name"), verbs)
205
+
206
+ manifest = Manifest(
207
+ reader.plugin,
208
+ version,
209
+ synth_api,
210
+ reader.choice(data["activation"], "activation", Activation),
211
+ frozenset(
212
+ reader.unique(
213
+ reader.items(
214
+ data["permissions"],
215
+ "permissions",
216
+ lambda item, field: reader.choice(item, field, Permission),
217
+ ),
218
+ "permissions",
219
+ )
220
+ ),
221
+ EntrypointSpec(
222
+ **{
223
+ key: reader.identifier(entrypoints[key], "entrypoints." + key)
224
+ if key in entrypoints
225
+ else None
226
+ for key in ("skill", "context", "renderer", "tool")
227
+ }
228
+ ),
229
+ reader.items(data.get("sources", []), "sources", reader.source),
230
+ reader.items(data.get("panels", []), "panels", reader.panel),
231
+ reader.items(data.get("cursors", []), "cursors", reader.cursor),
232
+ reader.items(data.get("views", []), "views", reader.view),
233
+ tool,
234
+ )
235
+ _validate_links(manifest)
236
+ return manifest
237
+
238
+
239
+ def _validate_links(manifest: Manifest) -> None:
240
+ reader = _ManifestReader()
241
+ reader.plugin = manifest.id
242
+ sources = set(reader.unique(tuple(source.id for source in manifest.sources), "sources"))
243
+ panels = set(reader.unique(tuple(panel.id for panel in manifest.panels), "panels"))
244
+ cursors = set(reader.unique(tuple(cursor.id for cursor in manifest.cursors), "cursors"))
245
+ reader.unique(tuple(view.id for view in manifest.views), "views")
246
+ for panel in manifest.panels:
247
+ unknown_sources = set(panel.sources) - sources
248
+ if unknown_sources:
249
+ raise reader.fail(panel.id, f"undeclared sources {sorted(unknown_sources)}")
250
+ for view in manifest.views:
251
+ unknown_cursors = set(view.emits + view.consumes) - cursors
252
+ if view.panel not in panels or unknown_cursors:
253
+ raise reader.fail(
254
+ view.id, f"unknown panel or cursors ({view.panel}, {sorted(unknown_cursors)})"
255
+ )
256
+ if bool(manifest.views) != (manifest.entrypoints.renderer is not None):
257
+ raise reader.fail("entrypoints.renderer", "renderer and views must be declared together")
258
+ if bool(manifest.tool) != (manifest.entrypoints.tool is not None):
259
+ raise reader.fail(
260
+ "entrypoints.tool", "tool entrypoint and facade must be declared together"
261
+ )
262
+ if manifest.views and Permission.UI_SLOTS not in manifest.permissions:
263
+ raise reader.fail("permissions", "views require ui_slots")
264
+ if (
265
+ manifest.tool is not None
266
+ and Permission.PAID_SPEND not in manifest.permissions
267
+ and any(verb.approval is ApprovalTier.PAID_SPEND for verb in manifest.tool.verbs)
268
+ ):
269
+ raise reader.fail("permissions", "paid tool verbs require paid_spend")
@@ -0,0 +1,332 @@
1
+ """Trusted bundled pack declarations and the authenticated source publisher."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from dataclasses import dataclass
7
+ from hashlib import sha256
8
+ from importlib.resources import files
9
+ from typing import Protocol
10
+
11
+ from .contracts import (
12
+ ApprovalTier,
13
+ Health,
14
+ JsonObject,
15
+ Lifecycle,
16
+ Manifest,
17
+ Pin,
18
+ ToolReceipt,
19
+ )
20
+ from .job_binding import JobAnchor, install
21
+ from .lifecycle import Action, PluginLifecycle
22
+ from .manifest import load_manifest
23
+ from .records import record, text
24
+ from .schemas import SchemaCatalog
25
+ from .surfaces import display_line
26
+
27
+ Adapter = Callable[[str, JsonObject, JsonObject, str | None], object]
28
+
29
+
30
+ class Gateway(Protocol):
31
+ def send(self, op: str, **fields: object) -> object: ...
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class Pack:
36
+ manifest: Manifest
37
+ schemas: Mapping[str, JsonObject]
38
+ present: Adapter
39
+ skill: str
40
+ default_tiling: str
41
+ follow: Callable[[SourcePublisher, str | None], None]
42
+ launch_receipts: bool
43
+
44
+ def manage(self, gateway: Gateway, operation: str, source: str) -> ToolReceipt:
45
+ if operation != "status":
46
+ raise ValueError(f"Unknown {self.manifest.id} tool action")
47
+ reply = gateway.send("source.snapshot", source=source)
48
+ if (
49
+ not isinstance(reply, dict)
50
+ or reply.get("registration", {}).get("plugin") != self.manifest.id
51
+ ):
52
+ raise ValueError(f"Source {source} is outside {self.manifest.id}")
53
+ live = reply["live"]
54
+ fact = (
55
+ reply.get("facts", {}).get("state", {}).get("fact", {}).get("payload", {})
56
+ )
57
+ frame = live.get("streams", {}).get("status", {}).get("payload", {})
58
+ result = {"source": source, "state": live["health"], "data": fact | frame}
59
+ tool = self.manifest.tool
60
+ assert tool is not None
61
+ status = next(verb for verb in tool.verbs if verb.id == "status")
62
+ schemas = SchemaCatalog(self.manifest.id, self.schemas)
63
+ binding = reply["registration"]
64
+ source_spec = next(
65
+ (
66
+ spec
67
+ for spec in self.manifest.sources
68
+ if (spec.dialect, spec.dialect_version, spec.schema_ref)
69
+ == (
70
+ binding.get("dialect"),
71
+ binding.get("dialect_version"),
72
+ binding.get("schema_ref"),
73
+ )
74
+ ),
75
+ None,
76
+ )
77
+ if source_spec is None:
78
+ raise ValueError("Plugin status receipt has an unsupported source dialect")
79
+ payload_max = 2 * source_spec.bounds.max_payload_bytes
80
+ schemas.encode(source_spec.schema_ref, source, result["data"], payload_max)
81
+ schemas.encode(status.output_schema_ref, source, result, payload_max + 512)
82
+ return ToolReceipt(result)
83
+
84
+ def context(self, health: Health, payload: JsonObject | None) -> str:
85
+ state = payload.get("status") if payload is not None else None
86
+ suffix = f" · {state}" if isinstance(state, str) else ""
87
+ return display_line(f"{self.manifest.id} · {health.value}{suffix}"[:512])
88
+
89
+
90
+ def load_pack(
91
+ package: str,
92
+ schemas: Mapping[str, JsonObject],
93
+ present: Adapter,
94
+ follow: Callable[[SourcePublisher, str | None], None],
95
+ *,
96
+ tiling: str = "balanced",
97
+ launch_receipts: bool = False,
98
+ ) -> Pack:
99
+ root = files(package)
100
+ manifest = load_manifest(root.joinpath("plugin.toml").read_text(encoding="utf-8"))
101
+ schemas = dict(schemas)
102
+ if manifest.tool is not None:
103
+ for verb in manifest.tool.verbs:
104
+ schemas[verb.input_schema_ref] = record()
105
+ schemas[verb.output_schema_ref] = record(
106
+ ("source", "state", "data"),
107
+ source=text(128),
108
+ state=text(32),
109
+ data={"type": "object"},
110
+ )
111
+ catalog = SchemaCatalog(manifest.id, schemas)
112
+ for source in manifest.sources:
113
+ catalog.require(source.schema_ref, source.id)
114
+ for cursor in manifest.cursors:
115
+ catalog.require(cursor.schema_ref, cursor.id)
116
+ return Pack(
117
+ manifest,
118
+ schemas,
119
+ present,
120
+ root.joinpath("SKILL.md").read_text(encoding="utf-8"),
121
+ tiling,
122
+ follow,
123
+ launch_receipts,
124
+ )
125
+
126
+
127
+ def job_receipt(pack: Pack, source_id: str, job_id: str) -> ToolReceipt:
128
+ """Convert a backend-issued job id into a stable view pin."""
129
+ pill = next(
130
+ view.id for view in pack.manifest.views if view.density.value == "compact"
131
+ )
132
+ return ToolReceipt({"job_id": job_id}, Pin(source_id, pill))
133
+
134
+
135
+ class SourcePublisher:
136
+ """Publish a plugin-owned push feed. The gateway checks authentication and schemas."""
137
+
138
+ def __init__(
139
+ self,
140
+ gateway: Gateway,
141
+ pack: Pack,
142
+ source: str,
143
+ *,
144
+ identity: str | None = None,
145
+ anchor: JobAnchor | None = None,
146
+ ) -> None:
147
+ self.gateway = gateway
148
+ self.pack = pack
149
+ self.spec = next(spec for spec in pack.manifest.sources if spec.id == source)
150
+ self.identity = identity or source
151
+ self.catalog = SchemaCatalog(pack.manifest.id, pack.schemas)
152
+ self.registration = None
153
+ self.anchor = anchor
154
+ self.bound_job: str | None = None
155
+ self.job_key: str | None = None
156
+ self.latest_revision: int | None = None
157
+ self._lifecycle = PluginLifecycle()
158
+ self._lifecycle.advance(Action.VALIDATE)
159
+
160
+ @property
161
+ def lifecycle(self) -> Lifecycle:
162
+ return self._lifecycle.phase
163
+
164
+ @property
165
+ def binding(self) -> JsonObject:
166
+ return {
167
+ "source": self.identity,
168
+ "dialect": self.spec.dialect,
169
+ "dialect_version": self.spec.dialect_version,
170
+ }
171
+
172
+ def register(self) -> int:
173
+ if self._lifecycle.permits(Action.MOUNT):
174
+ self._lifecycle.advance(Action.MOUNT)
175
+ schema = self.pack.schemas[self.spec.schema_ref]
176
+ streams = {"status": {"mode": "latest_value", "schema": schema}}
177
+ bounds = {"max_payload_bytes": self.spec.bounds.max_payload_bytes}
178
+ if self.spec.bounds.max_tail_bytes is not None:
179
+ bounds["max_tail_bytes"] = self.spec.bounds.max_tail_bytes
180
+ streams["logs"] = {
181
+ "mode": "offset_append",
182
+ "schema": {"type": "string", "maxLength": 4096},
183
+ }
184
+ status_tool = {}
185
+ tool = self.pack.manifest.tool
186
+ if tool is not None and any(
187
+ verb.id == "status" and verb.approval is ApprovalTier.READ
188
+ for verb in tool.verbs
189
+ ):
190
+ status_tool = {
191
+ "status_tool": {
192
+ "name": tool.name,
193
+ "operation": "status",
194
+ "approval": "read",
195
+ }
196
+ }
197
+ reply = self.gateway.send(
198
+ "source.register",
199
+ **self.binding,
200
+ **status_tool,
201
+ plugin=self.pack.manifest.id,
202
+ schema_ref=self.spec.schema_ref,
203
+ transport="push",
204
+ bounds=bounds,
205
+ facts={"state": schema},
206
+ streams=streams,
207
+ )
208
+ if not isinstance(reply, dict) or type(reply.get("seq")) is not int:
209
+ raise ValueError(f"Invalid registration receipt for {self.identity}")
210
+ self.registration = reply["seq"]
211
+ if self._lifecycle.permits(Action.ACTIVATE):
212
+ self._lifecycle.advance(Action.ACTIVATE)
213
+ return self.registration
214
+
215
+ def unmount(self) -> None:
216
+ self._lifecycle.advance(Action.UNMOUNT)
217
+ self.registration = None
218
+
219
+ def _required_registration(self) -> int:
220
+ if self.registration is None or not self._lifecycle.serving:
221
+ raise ValueError(f"Source {self.identity} requires active registration")
222
+ return self.registration
223
+
224
+ def bind_job(self, job_id: str, identity: JsonObject) -> ToolReceipt:
225
+ """Record launch custody before pinning, so replay cannot undo an owner's unpin."""
226
+ if not isinstance(job_id, str) or not 0 < len(job_id) <= 128:
227
+ raise ValueError("Verified job identity is required")
228
+ if self.bound_job is not None and job_id != self.bound_job:
229
+ raise ValueError("Source is already bound to a different backend job")
230
+ if self.bound_job == job_id:
231
+ return ToolReceipt({"job_id": job_id})
232
+ key = f"job-{sha256(job_id.encode()).hexdigest()[:32]}"
233
+ snapshot = self._snapshot()
234
+ state = snapshot.get("facts", {}).get("state", {}).get("fact")
235
+ self.job_key = key
236
+ if state is not None:
237
+ previous = state.get("id", "")
238
+ if previous.startswith("job-") and not previous.startswith(key + "-"):
239
+ raise ValueError("Source is already bound to a different backend job")
240
+ if not previous.startswith("job-") and any(
241
+ state.get("payload", {}).get(field) != value
242
+ for field, value in identity.items()
243
+ ):
244
+ raise ValueError("Legacy source receipt disagrees with the backend job")
245
+ if not previous.startswith("job-"):
246
+ self.fact(f"{key}-identity", identity)
247
+ self.bound_job = job_id
248
+ return ToolReceipt({"job_id": job_id})
249
+ self.fact(f"{key}-identity", identity)
250
+ self.bound_job = job_id
251
+ if self.anchor is None:
252
+ return ToolReceipt({"job_id": job_id})
253
+ receipt = job_receipt(self.pack, self.identity, job_id)
254
+ assert receipt.pin is not None
255
+ install(self.gateway, self.anchor, receipt.pin)
256
+ return receipt
257
+
258
+ def _snapshot(self) -> dict:
259
+ snapshot = self.gateway.send("source.snapshot", source=self.identity)
260
+ if not isinstance(snapshot, dict):
261
+ raise TypeError("Invalid gateway source snapshot")
262
+ revision = (
263
+ snapshot.get("live", {})
264
+ .get("streams", {})
265
+ .get("status", {})
266
+ .get("revision")
267
+ )
268
+ if revision is not None:
269
+ if type(revision) is not int or not 0 <= revision < 2**64:
270
+ raise ValueError("Invalid gateway source revision")
271
+ self.latest_revision = max(self.latest_revision or 0, revision)
272
+ return snapshot
273
+
274
+ def update(self, payload: JsonObject) -> object:
275
+ """Advance the coalesced stream across foreground adapter restarts."""
276
+ if self.latest_revision is None:
277
+ self._snapshot()
278
+ revision = (self.latest_revision or 0) + 1
279
+ if revision >= 2**64:
280
+ raise ValueError("Plugin source revision exhausted")
281
+ receipt = self.tick(revision, payload)
282
+ self.latest_revision = revision
283
+ return receipt
284
+
285
+ def fact(
286
+ self, operation: str, payload: JsonObject, *, cause: int | None = None
287
+ ) -> object:
288
+ registered = self._required_registration()
289
+ self.validate(payload)
290
+ return self.gateway.send(
291
+ "source.fact",
292
+ **self.binding,
293
+ id=operation,
294
+ kind="state",
295
+ payload=payload,
296
+ cause=registered if cause is None else cause,
297
+ )
298
+
299
+ def tick(self, revision: int, payload: JsonObject) -> object:
300
+ self._required_registration()
301
+ self.validate(payload)
302
+ return self.gateway.send(
303
+ "source.frame",
304
+ **self.binding,
305
+ stream="status",
306
+ frame={"mode": "latest_value", "revision": revision, "payload": payload},
307
+ )
308
+
309
+ def append(self, offset: int, text: str) -> object:
310
+ self._required_registration()
311
+ if self.spec.bounds.max_tail_bytes is None:
312
+ raise ValueError(f"Source {self.identity} has no append stream")
313
+ return self.gateway.send(
314
+ "source.frame",
315
+ **self.binding,
316
+ stream="logs",
317
+ frame={"mode": "offset_append", "offset": offset, "payload": text},
318
+ )
319
+
320
+ def health(self, state: Health) -> object:
321
+ self._required_registration()
322
+ reply = self.gateway.send("source.health", **self.binding, state=state.value)
323
+ self._lifecycle.observe_health(degraded=state is not Health.CONNECTED)
324
+ return reply
325
+
326
+ def validate(self, payload: JsonObject) -> None:
327
+ self.catalog.encode(
328
+ self.spec.schema_ref,
329
+ self.spec.id,
330
+ payload,
331
+ self.spec.bounds.max_payload_bytes,
332
+ )
@@ -0,0 +1,98 @@
1
+ """Bounded adapters for event-driven managed plugin sources."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Protocol
7
+
8
+ from .contracts import Health, JsonObject
9
+ from .job_binding import JobAnchor
10
+ from .pack import Pack, SourcePublisher
11
+
12
+
13
+ class Callback(Protocol):
14
+ def __call__(self, publisher: SourcePublisher, endpoint: str | None) -> None: ...
15
+
16
+
17
+ def publish(
18
+ client,
19
+ pack: Pack,
20
+ identity: str,
21
+ endpoint: str | None,
22
+ adapter: Callback,
23
+ *,
24
+ anchor: JobAnchor | None = None,
25
+ ) -> None:
26
+ spec = _compatible_source(client, pack, identity)
27
+ source = SourcePublisher(client, pack, spec.id, identity=identity, anchor=anchor)
28
+ source.register()
29
+ try:
30
+ adapter(source, endpoint)
31
+ except KeyboardInterrupt:
32
+ source.health(Health.STALE)
33
+ except (OSError, ValueError, TypeError, KeyError):
34
+ source.health(Health.ERROR)
35
+ raise
36
+ finally:
37
+ source.unmount()
38
+
39
+
40
+ def _compatible_source(client, pack: Pack, identity: str):
41
+ preferred, *legacy = pack.manifest.sources
42
+ if not legacy:
43
+ return preferred
44
+ try:
45
+ snapshot = client.send("source.snapshot", source=identity)
46
+ except ValueError as error:
47
+ refusal = getattr(error, "refusal", None)
48
+ if isinstance(refusal, dict) and refusal.get("code") == "unknown_source":
49
+ return preferred
50
+ raise
51
+ declared = snapshot["registration"]
52
+ if declared.get("plugin") == pack.manifest.id:
53
+ for candidate in (preferred, *legacy):
54
+ if (candidate.dialect, candidate.dialect_version, candidate.schema_ref) == (
55
+ declared.get("dialect"),
56
+ declared.get("dialect_version"),
57
+ declared.get("schema_ref"),
58
+ ):
59
+ return candidate
60
+ raise ValueError(
61
+ f"Source {identity} was registered for an unsupported plugin dialect"
62
+ )
63
+
64
+
65
+ def native_changes(
66
+ source: SourcePublisher,
67
+ project: Callable[[dict], JsonObject],
68
+ kinds: frozenset[str],
69
+ *,
70
+ operation: str = "snapshot",
71
+ ) -> None:
72
+ """Read canonical native projections initially and after relevant pushed commits."""
73
+ snapshot = source.gateway.send("snapshot")
74
+ cursor = snapshot["cursor"]
75
+ if operation != "snapshot":
76
+ snapshot = source.gateway.send(operation)
77
+ source.fact(f"snapshot-{cursor}", project(snapshot))
78
+ source.health(Health.CONNECTED)
79
+ with source.gateway.subscribe(after=cursor) as subscription:
80
+ dirty = False
81
+ for envelope in subscription:
82
+ kind = envelope["type"]
83
+ if kind == "event" and envelope["event"]["kind"] in kinds:
84
+ dirty = True
85
+ elif kind == "caught_up":
86
+ dirty = True
87
+ source.health(Health.CONNECTED)
88
+ elif kind in {"disconnected", "resyncing"}:
89
+ source.health(Health.STALE)
90
+ if dirty:
91
+ fresh = source.gateway.send("snapshot")
92
+ head = fresh["cursor"]
93
+ if operation != "snapshot":
94
+ fresh = source.gateway.send(operation)
95
+ if head > cursor:
96
+ source.fact(f"snapshot-{head}", project(fresh))
97
+ cursor = head
98
+ dirty = False