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
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Local JSON Schema validation and immutable boundary payload copies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
|
|
9
|
+
from jsonschema import Draft202012Validator, SchemaError, ValidationError
|
|
10
|
+
|
|
11
|
+
from .contracts import ContractError, JsonObject, JsonValue, Refusal, RefusalCode
|
|
12
|
+
|
|
13
|
+
_DRAFT = "https://json-schema.org/draft/2020-12/schema"
|
|
14
|
+
_JSON_MAX_DEPTH = 24
|
|
15
|
+
_JSON_MAX_NODES = 4096
|
|
16
|
+
_SCHEMA_MAX_NODES = 256
|
|
17
|
+
_SCHEMA_MAX_BYTES = 32768
|
|
18
|
+
_SCHEMA_MAX_COUNT = 64
|
|
19
|
+
_UNBOUNDED_SCHEMA_KEYWORDS = frozenset(
|
|
20
|
+
{
|
|
21
|
+
"$ref",
|
|
22
|
+
"$dynamicRef",
|
|
23
|
+
"pattern",
|
|
24
|
+
"patternProperties",
|
|
25
|
+
"uniqueItems",
|
|
26
|
+
"contains",
|
|
27
|
+
"unevaluatedItems",
|
|
28
|
+
"unevaluatedProperties",
|
|
29
|
+
}
|
|
30
|
+
)
|
|
31
|
+
_SCHEMA_MAPPINGS = frozenset({"properties", "dependentSchemas", "$defs"})
|
|
32
|
+
_SCHEMA_ARRAYS = frozenset({"allOf", "anyOf", "oneOf", "prefixItems"})
|
|
33
|
+
_SCHEMA_CHILDREN = frozenset(
|
|
34
|
+
{
|
|
35
|
+
"additionalProperties",
|
|
36
|
+
"items",
|
|
37
|
+
"propertyNames",
|
|
38
|
+
"not",
|
|
39
|
+
"if",
|
|
40
|
+
"then",
|
|
41
|
+
"else",
|
|
42
|
+
}
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class _JsonByteBudget(ValueError):
|
|
47
|
+
def __init__(self, lower_bound: int) -> None:
|
|
48
|
+
self.lower_bound = lower_bound
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _check_json(value: object, *, max_chars: int, max_nodes: int) -> None:
|
|
52
|
+
nodes = 0
|
|
53
|
+
text_chars = 0
|
|
54
|
+
|
|
55
|
+
def check(node: object, depth: int) -> None:
|
|
56
|
+
nonlocal nodes, text_chars
|
|
57
|
+
nodes += 1
|
|
58
|
+
if depth > _JSON_MAX_DEPTH or nodes > max_nodes:
|
|
59
|
+
raise ValueError(f"JSON exceeds depth {_JSON_MAX_DEPTH} or {max_nodes} nodes")
|
|
60
|
+
if type(node) is str:
|
|
61
|
+
text_chars += len(node)
|
|
62
|
+
if text_chars > max_chars:
|
|
63
|
+
raise _JsonByteBudget(text_chars)
|
|
64
|
+
return
|
|
65
|
+
if node is None or type(node) is bool:
|
|
66
|
+
return
|
|
67
|
+
if type(node) is int and node.bit_length() <= 4096:
|
|
68
|
+
return
|
|
69
|
+
if type(node) is float and math.isfinite(node):
|
|
70
|
+
return
|
|
71
|
+
if type(node) is list:
|
|
72
|
+
for item in node:
|
|
73
|
+
check(item, depth + 1)
|
|
74
|
+
return
|
|
75
|
+
if type(node) is dict:
|
|
76
|
+
for key, item in node.items():
|
|
77
|
+
if type(key) is not str:
|
|
78
|
+
raise ValueError("JSON object keys must be strings")
|
|
79
|
+
check(key, depth + 1)
|
|
80
|
+
check(item, depth + 1)
|
|
81
|
+
return
|
|
82
|
+
raise ValueError(f"invalid or oversized JSON value of type {type(node).__name__}")
|
|
83
|
+
|
|
84
|
+
check(value, 0)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _check_schema_vocabulary(schema: JsonValue) -> None:
|
|
88
|
+
if not isinstance(schema, dict):
|
|
89
|
+
return # The meta-schema checks validity of child shape and boolean schemas.
|
|
90
|
+
blocked = _UNBOUNDED_SCHEMA_KEYWORDS.intersection(schema)
|
|
91
|
+
if blocked:
|
|
92
|
+
raise ValueError(f"fixture schema uses unsupported keywords {sorted(blocked)}")
|
|
93
|
+
if "$schema" in schema and schema["$schema"] != _DRAFT:
|
|
94
|
+
raise ValueError(f"expected JSON Schema dialect {_DRAFT}")
|
|
95
|
+
for key, child in schema.items():
|
|
96
|
+
if key in _SCHEMA_MAPPINGS and isinstance(child, dict):
|
|
97
|
+
for nested in child.values():
|
|
98
|
+
_check_schema_vocabulary(nested)
|
|
99
|
+
elif key in _SCHEMA_ARRAYS and isinstance(child, list):
|
|
100
|
+
for nested in child:
|
|
101
|
+
_check_schema_vocabulary(nested)
|
|
102
|
+
elif key in _SCHEMA_CHILDREN:
|
|
103
|
+
_check_schema_vocabulary(child)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def encode_object(
|
|
107
|
+
value: object,
|
|
108
|
+
*,
|
|
109
|
+
plugin: str,
|
|
110
|
+
subject: str,
|
|
111
|
+
max_bytes: int,
|
|
112
|
+
) -> bytes:
|
|
113
|
+
try:
|
|
114
|
+
if type(value) is not dict:
|
|
115
|
+
raise ValueError("expected a JSON object")
|
|
116
|
+
_check_json(value, max_chars=max_bytes, max_nodes=_JSON_MAX_NODES)
|
|
117
|
+
encoded = json.dumps(
|
|
118
|
+
value, ensure_ascii=False, allow_nan=False, separators=(",", ":")
|
|
119
|
+
).encode("utf-8")
|
|
120
|
+
except _JsonByteBudget as error:
|
|
121
|
+
raise ContractError(
|
|
122
|
+
Refusal(
|
|
123
|
+
RefusalCode.PAYLOAD_TOO_LARGE,
|
|
124
|
+
plugin,
|
|
125
|
+
subject,
|
|
126
|
+
"JSON text already exceeds its byte budget",
|
|
127
|
+
expected=max_bytes,
|
|
128
|
+
actual=error.lower_bound,
|
|
129
|
+
)
|
|
130
|
+
) from error
|
|
131
|
+
except (ValueError, TypeError, RuntimeError) as error:
|
|
132
|
+
raise ContractError(
|
|
133
|
+
Refusal(RefusalCode.PAYLOAD_INVALID, plugin, subject, str(error))
|
|
134
|
+
) from error
|
|
135
|
+
if len(encoded) > max_bytes:
|
|
136
|
+
raise ContractError(
|
|
137
|
+
Refusal(
|
|
138
|
+
RefusalCode.PAYLOAD_TOO_LARGE,
|
|
139
|
+
plugin,
|
|
140
|
+
subject,
|
|
141
|
+
"JSON payload exceeds its byte budget",
|
|
142
|
+
expected=max_bytes,
|
|
143
|
+
actual=len(encoded),
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
return encoded
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class SchemaCatalog:
|
|
150
|
+
def __init__(self, plugin: str, schemas: Mapping[str, JsonObject]) -> None:
|
|
151
|
+
self._plugin = plugin
|
|
152
|
+
self._validators: dict[str, Draft202012Validator] = {}
|
|
153
|
+
if len(schemas) > _SCHEMA_MAX_COUNT:
|
|
154
|
+
raise ContractError(
|
|
155
|
+
Refusal(
|
|
156
|
+
RefusalCode.SCHEMA_INVALID,
|
|
157
|
+
plugin,
|
|
158
|
+
"schemas",
|
|
159
|
+
"too many fixture schemas",
|
|
160
|
+
expected=_SCHEMA_MAX_COUNT,
|
|
161
|
+
actual=len(schemas),
|
|
162
|
+
)
|
|
163
|
+
)
|
|
164
|
+
for schema_ref, schema in schemas.items():
|
|
165
|
+
try:
|
|
166
|
+
_check_json(schema, max_chars=_SCHEMA_MAX_BYTES, max_nodes=_SCHEMA_MAX_NODES)
|
|
167
|
+
if type(schema) is not dict:
|
|
168
|
+
raise ValueError("expected a JSON Schema object")
|
|
169
|
+
_check_schema_vocabulary(schema)
|
|
170
|
+
frozen_copy = json.loads(json.dumps(schema, allow_nan=False))
|
|
171
|
+
Draft202012Validator.check_schema(frozen_copy)
|
|
172
|
+
except (SchemaError, ValueError) as error:
|
|
173
|
+
detail = error.message if isinstance(error, SchemaError) else str(error)
|
|
174
|
+
if isinstance(error, _JsonByteBudget):
|
|
175
|
+
detail = f"schema exceeds the {_SCHEMA_MAX_BYTES} byte text budget"
|
|
176
|
+
raise ContractError(
|
|
177
|
+
Refusal(RefusalCode.SCHEMA_INVALID, plugin, schema_ref, detail)
|
|
178
|
+
) from error
|
|
179
|
+
self._validators[schema_ref] = Draft202012Validator(frozen_copy)
|
|
180
|
+
|
|
181
|
+
def require(self, schema_ref: str, subject: str) -> None:
|
|
182
|
+
if schema_ref not in self._validators:
|
|
183
|
+
raise ContractError(
|
|
184
|
+
Refusal(
|
|
185
|
+
RefusalCode.SCHEMA_INVALID,
|
|
186
|
+
self._plugin,
|
|
187
|
+
subject,
|
|
188
|
+
"unknown schema reference",
|
|
189
|
+
actual=schema_ref,
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
def encode(self, schema_ref: str, subject: str, value: object, max_bytes: int) -> bytes:
|
|
194
|
+
self.require(schema_ref, subject)
|
|
195
|
+
encoded = encode_object(value, plugin=self._plugin, subject=subject, max_bytes=max_bytes)
|
|
196
|
+
try:
|
|
197
|
+
self._validators[schema_ref].validate(json.loads(encoded))
|
|
198
|
+
except ValidationError as error:
|
|
199
|
+
path = ".".join(str(part) for part in error.absolute_path)
|
|
200
|
+
rule = error.validator
|
|
201
|
+
raise ContractError(
|
|
202
|
+
Refusal(
|
|
203
|
+
RefusalCode.PAYLOAD_INVALID,
|
|
204
|
+
self._plugin,
|
|
205
|
+
subject,
|
|
206
|
+
f"payload violates {rule} at {path or '<root>'}",
|
|
207
|
+
expected=schema_ref,
|
|
208
|
+
)
|
|
209
|
+
) from error
|
|
210
|
+
return encoded
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""Fixture source validation and bounded, push-only in-memory projections."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
from .contracts import (
|
|
10
|
+
ContractError,
|
|
11
|
+
Health,
|
|
12
|
+
JsonObject,
|
|
13
|
+
Refusal,
|
|
14
|
+
RefusalCode,
|
|
15
|
+
SourceSpec,
|
|
16
|
+
Transport,
|
|
17
|
+
)
|
|
18
|
+
from .schemas import SchemaCatalog
|
|
19
|
+
|
|
20
|
+
__all__ = ("SourceProjection", "SourceSnapshot")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class SourceSnapshot:
|
|
25
|
+
registration: SourceSpec
|
|
26
|
+
health: Health
|
|
27
|
+
fact: JsonObject | None
|
|
28
|
+
frame: JsonObject | None
|
|
29
|
+
sequence: int | None
|
|
30
|
+
tail: str | None
|
|
31
|
+
tail_start: int | None
|
|
32
|
+
next_offset: int | None
|
|
33
|
+
refusal: Refusal | None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, slots=True)
|
|
37
|
+
class SourceCapture:
|
|
38
|
+
registration: SourceSpec
|
|
39
|
+
health: Health
|
|
40
|
+
fact: bytes | None
|
|
41
|
+
frame: bytes | None
|
|
42
|
+
sequence: int | None
|
|
43
|
+
tail: bytes | None
|
|
44
|
+
next_offset: int | None
|
|
45
|
+
refusal: Refusal | None
|
|
46
|
+
|
|
47
|
+
def snapshot(self) -> SourceSnapshot:
|
|
48
|
+
tail_start = None
|
|
49
|
+
if self.tail is not None and self.next_offset is not None:
|
|
50
|
+
tail_start = self.next_offset - len(self.tail)
|
|
51
|
+
return SourceSnapshot(
|
|
52
|
+
self.registration,
|
|
53
|
+
self.health,
|
|
54
|
+
json.loads(self.fact) if self.fact is not None else None,
|
|
55
|
+
json.loads(self.frame) if self.frame is not None else None,
|
|
56
|
+
self.sequence,
|
|
57
|
+
self.tail.decode("utf-8") if self.tail is not None else None,
|
|
58
|
+
tail_start,
|
|
59
|
+
self.next_offset,
|
|
60
|
+
self.refusal,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class SourceProjection:
|
|
65
|
+
"""Collect one fixture source. Snapshots expose copies of retained JSON."""
|
|
66
|
+
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
plugin: str,
|
|
70
|
+
spec: SourceSpec,
|
|
71
|
+
schemas: SchemaCatalog,
|
|
72
|
+
active: Callable[[], bool],
|
|
73
|
+
) -> None:
|
|
74
|
+
self.plugin = plugin
|
|
75
|
+
self.spec = spec
|
|
76
|
+
self._schemas = schemas
|
|
77
|
+
self._active = active
|
|
78
|
+
self._fact: bytes | None = None
|
|
79
|
+
self._revision = 0
|
|
80
|
+
self.reset_live()
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def refusal(self) -> Refusal | None:
|
|
84
|
+
return self._refusal
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def revision(self) -> int:
|
|
88
|
+
return self._revision
|
|
89
|
+
|
|
90
|
+
def reset_live(self) -> None:
|
|
91
|
+
self._revision += 1
|
|
92
|
+
self._health = Health.UNAVAILABLE
|
|
93
|
+
self._frame: bytes | None = None
|
|
94
|
+
self._sequence: int | None = None
|
|
95
|
+
self._tail: bytes | None = b"" if self.spec.transport is Transport.OFFSET_APPEND else None
|
|
96
|
+
self._next_offset = 0 if self._tail is not None else None
|
|
97
|
+
self._refusal: Refusal | None = None
|
|
98
|
+
|
|
99
|
+
def snapshot(self) -> SourceSnapshot:
|
|
100
|
+
return self.capture().snapshot()
|
|
101
|
+
|
|
102
|
+
def capture(self) -> SourceCapture:
|
|
103
|
+
"""Capture retained bytes without decoding JSON on a paint loop."""
|
|
104
|
+
return SourceCapture(
|
|
105
|
+
self.spec,
|
|
106
|
+
self._health,
|
|
107
|
+
self._fact,
|
|
108
|
+
self._frame,
|
|
109
|
+
self._sequence,
|
|
110
|
+
self._tail,
|
|
111
|
+
self._next_offset,
|
|
112
|
+
self._refusal,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
def publish_health(self, health: Health) -> Refusal | None:
|
|
116
|
+
if not self._active():
|
|
117
|
+
return self._error(RefusalCode.INACTIVE, "publish requires an active plugin").refusal
|
|
118
|
+
if not isinstance(health, Health):
|
|
119
|
+
return self._degrade(
|
|
120
|
+
self._error(RefusalCode.PAYLOAD_INVALID, "expected a typed source health")
|
|
121
|
+
)
|
|
122
|
+
self._revision += 1
|
|
123
|
+
self._health = health
|
|
124
|
+
if health is Health.CONNECTED:
|
|
125
|
+
self._refusal = None
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
def publish_fact(self, payload: JsonObject) -> Refusal | None:
|
|
129
|
+
if not self._active():
|
|
130
|
+
return self._error(RefusalCode.INACTIVE, "publish requires an active plugin").refusal
|
|
131
|
+
try:
|
|
132
|
+
encoded = self._encode(payload)
|
|
133
|
+
except ContractError as error:
|
|
134
|
+
return self._degrade(error)
|
|
135
|
+
self._revision += 1
|
|
136
|
+
self._fact = encoded
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
def publish_latest(self, sequence: int, payload: JsonObject) -> Refusal | None:
|
|
140
|
+
if not self._active():
|
|
141
|
+
return self._error(RefusalCode.INACTIVE, "publish requires an active plugin").refusal
|
|
142
|
+
try:
|
|
143
|
+
if self.spec.transport is not Transport.LATEST_VALUE:
|
|
144
|
+
raise self._error(
|
|
145
|
+
RefusalCode.PAYLOAD_INVALID, "source transport requires offset append"
|
|
146
|
+
)
|
|
147
|
+
if type(sequence) is not int or sequence < 0:
|
|
148
|
+
raise self._error(
|
|
149
|
+
RefusalCode.PAYLOAD_INVALID, "expected a nonnegative integer sequence"
|
|
150
|
+
)
|
|
151
|
+
if self._sequence is not None and sequence <= self._sequence:
|
|
152
|
+
raise self._error(
|
|
153
|
+
RefusalCode.SEQUENCE_STALE,
|
|
154
|
+
"live sequence must advance",
|
|
155
|
+
self._sequence + 1,
|
|
156
|
+
sequence,
|
|
157
|
+
)
|
|
158
|
+
encoded = self._encode(payload)
|
|
159
|
+
except ContractError as error:
|
|
160
|
+
return self._degrade(error)
|
|
161
|
+
self._revision += 1
|
|
162
|
+
self._frame = encoded
|
|
163
|
+
self._sequence = sequence
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
def publish_append(self, offset: int, payload: JsonObject) -> Refusal | None:
|
|
167
|
+
if not self._active():
|
|
168
|
+
return self._error(RefusalCode.INACTIVE, "publish requires an active plugin").refusal
|
|
169
|
+
try:
|
|
170
|
+
budget = self.spec.bounds.max_tail_bytes
|
|
171
|
+
if self._tail is None or self._next_offset is None or budget is None:
|
|
172
|
+
raise self._error(
|
|
173
|
+
RefusalCode.PAYLOAD_INVALID, "source transport requires latest value"
|
|
174
|
+
)
|
|
175
|
+
if type(offset) is not int or offset < 0:
|
|
176
|
+
raise self._error(
|
|
177
|
+
RefusalCode.PAYLOAD_INVALID, "expected a nonnegative UTF-8 byte offset"
|
|
178
|
+
)
|
|
179
|
+
if offset != self._next_offset:
|
|
180
|
+
raise self._error(
|
|
181
|
+
RefusalCode.OFFSET_MISMATCH,
|
|
182
|
+
"append offset must equal the next UTF-8 byte position",
|
|
183
|
+
self._next_offset,
|
|
184
|
+
offset,
|
|
185
|
+
)
|
|
186
|
+
encoded = self._encode(payload)
|
|
187
|
+
text = json.loads(encoded).get("text")
|
|
188
|
+
if not isinstance(text, str) or not text:
|
|
189
|
+
raise self._error(
|
|
190
|
+
RefusalCode.PAYLOAD_INVALID, "append payload requires nonempty text"
|
|
191
|
+
)
|
|
192
|
+
chunk = text.encode("utf-8")
|
|
193
|
+
except ContractError as error:
|
|
194
|
+
return self._degrade(error)
|
|
195
|
+
|
|
196
|
+
retained_tail = (self._tail + chunk)[-budget:]
|
|
197
|
+
# A bounded byte cut may bisect the first UTF-8 code point.
|
|
198
|
+
first_code_point = 0
|
|
199
|
+
while (
|
|
200
|
+
first_code_point < len(retained_tail) and retained_tail[first_code_point] & 0xC0 == 0x80
|
|
201
|
+
):
|
|
202
|
+
first_code_point += 1
|
|
203
|
+
self._tail = retained_tail[first_code_point:]
|
|
204
|
+
self._next_offset += len(chunk)
|
|
205
|
+
self._revision += 1
|
|
206
|
+
self._frame = encoded
|
|
207
|
+
return None
|
|
208
|
+
|
|
209
|
+
def _encode(self, payload: JsonObject) -> bytes:
|
|
210
|
+
return self._schemas.encode(
|
|
211
|
+
self.spec.schema_ref,
|
|
212
|
+
self.spec.id,
|
|
213
|
+
payload,
|
|
214
|
+
self.spec.bounds.max_payload_bytes,
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
def _error(
|
|
218
|
+
self,
|
|
219
|
+
code: RefusalCode,
|
|
220
|
+
detail: str,
|
|
221
|
+
expected: int | None = None,
|
|
222
|
+
actual: int | None = None,
|
|
223
|
+
) -> ContractError:
|
|
224
|
+
return ContractError(Refusal(code, self.plugin, self.spec.id, detail, expected, actual))
|
|
225
|
+
|
|
226
|
+
def _degrade(self, error: ContractError) -> Refusal:
|
|
227
|
+
self._revision += 1
|
|
228
|
+
self._health = Health.ERROR
|
|
229
|
+
self._refusal = error.refusal
|
|
230
|
+
return error.refusal
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Surface-neutral plugin callbacks and typed outcomes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Callable, Mapping
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
|
|
9
|
+
from .contracts import Health, JsonObject, ToolReceipt, ViewSpec
|
|
10
|
+
from .sources import SourceSnapshot
|
|
11
|
+
|
|
12
|
+
__all__ = ("ContextSnapshot", "Entrypoints", "RenderRequest", "RenderedView", "display_line")
|
|
13
|
+
|
|
14
|
+
_ANSI_SEQUENCE = re.compile(
|
|
15
|
+
r"(?:\x1b\[|\x9b)[0-?]*[ -/]*[@-~]"
|
|
16
|
+
r"|(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)"
|
|
17
|
+
r"|\x1b[@-_]"
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True)
|
|
22
|
+
class ContextSnapshot:
|
|
23
|
+
text: str
|
|
24
|
+
health: Health
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True, slots=True)
|
|
28
|
+
class RenderRequest:
|
|
29
|
+
view: ViewSpec
|
|
30
|
+
sources: Mapping[str, SourceSnapshot]
|
|
31
|
+
cursors: Mapping[str, JsonObject]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class RenderedView:
|
|
36
|
+
lines: tuple[str, ...]
|
|
37
|
+
health: tuple[tuple[str, Health], ...]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class Entrypoints:
|
|
42
|
+
skills: Mapping[str, str] = field(default_factory=dict)
|
|
43
|
+
contexts: Mapping[str, Callable[[], ContextSnapshot]] = field(default_factory=dict)
|
|
44
|
+
renderers: Mapping[str, Callable[[RenderRequest], tuple[str, ...]]] = field(
|
|
45
|
+
default_factory=dict
|
|
46
|
+
)
|
|
47
|
+
tools: Mapping[str, Callable[[str, JsonObject], ToolReceipt]] = field(default_factory=dict)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def display_line(text: str) -> str:
|
|
51
|
+
"""Remove controls and formatting code points at the plugin output boundary."""
|
|
52
|
+
return "".join(
|
|
53
|
+
character for character in _ANSI_SEQUENCE.sub("", text) if character.isprintable()
|
|
54
|
+
)
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Lazy model tool catalog bound to engine-authorized sources."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Collection, Mapping, Sequence
|
|
6
|
+
from itertools import islice
|
|
7
|
+
|
|
8
|
+
from .contracts import MAX_CONTEXT_CHARS, ApprovalTier, JsonObject, ToolReceipt
|
|
9
|
+
from .discovery import bundled_entries
|
|
10
|
+
from .pack import Gateway, Pack
|
|
11
|
+
from .surfaces import display_line
|
|
12
|
+
|
|
13
|
+
_SOURCE_COUNT_MAX = 64
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class PackLoadError(RuntimeError):
|
|
17
|
+
"""A bundled pack entry point failed to import or declared a different pack id."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, entrypoint: str, target: str, cause: str) -> None:
|
|
20
|
+
self.entrypoint = entrypoint
|
|
21
|
+
self.target = target
|
|
22
|
+
self.cause = cause
|
|
23
|
+
super().__init__(f"pack_load_failed: {entrypoint} ({target}): {cause}")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def packs(
|
|
27
|
+
*,
|
|
28
|
+
failed: list[PackLoadError] | None = None,
|
|
29
|
+
include: Collection[str] | None = None,
|
|
30
|
+
) -> dict[str, Pack]:
|
|
31
|
+
"""Load bundled packs; any load failure raises ``PackLoadError``.
|
|
32
|
+
|
|
33
|
+
Pass ``failed`` only where one broken pack must not take down its siblings
|
|
34
|
+
(the surface host's poison isolation): failures are then recorded there as
|
|
35
|
+
typed errors instead of raised. Discovery refusals always raise.
|
|
36
|
+
"""
|
|
37
|
+
available = {}
|
|
38
|
+
if include is not None and not include:
|
|
39
|
+
return available
|
|
40
|
+
for entry in bundled_entries("synth_code.bundled_packs"):
|
|
41
|
+
if include is not None and entry.name not in include:
|
|
42
|
+
continue
|
|
43
|
+
try:
|
|
44
|
+
pack = _load(entry)
|
|
45
|
+
except PackLoadError as error:
|
|
46
|
+
if failed is None:
|
|
47
|
+
raise
|
|
48
|
+
failed.append(error)
|
|
49
|
+
continue
|
|
50
|
+
available[entry.name] = pack
|
|
51
|
+
return available
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _load(entry) -> Pack:
|
|
55
|
+
try:
|
|
56
|
+
pack = entry.load()
|
|
57
|
+
except Exception as error:
|
|
58
|
+
# Re-raised typed with the entrypoint named.
|
|
59
|
+
raise PackLoadError(
|
|
60
|
+
entry.name, entry.value, f"{type(error).__name__}: {error}"
|
|
61
|
+
) from error
|
|
62
|
+
declared = getattr(getattr(pack, "manifest", None), "id", None)
|
|
63
|
+
if declared != entry.name:
|
|
64
|
+
raise PackLoadError(
|
|
65
|
+
entry.name, entry.value, f"manifest id {declared!r} does not match the entrypoint"
|
|
66
|
+
)
|
|
67
|
+
return pack
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _scope(
|
|
71
|
+
active_sources: Sequence[Mapping[str, object]],
|
|
72
|
+
) -> dict[tuple[str, str], list[str]]:
|
|
73
|
+
scope: dict[tuple[str, str], list[str]] = {}
|
|
74
|
+
for entry in islice(active_sources, _SOURCE_COUNT_MAX):
|
|
75
|
+
source, plugin, name = (
|
|
76
|
+
entry.get("source"),
|
|
77
|
+
entry.get("plugin"),
|
|
78
|
+
entry.get("name"),
|
|
79
|
+
)
|
|
80
|
+
if (
|
|
81
|
+
isinstance(source, str)
|
|
82
|
+
and 0 < len(source) <= 128
|
|
83
|
+
and isinstance(plugin, str)
|
|
84
|
+
and isinstance(name, str)
|
|
85
|
+
):
|
|
86
|
+
identities = scope.setdefault((plugin, name), [])
|
|
87
|
+
if source not in identities:
|
|
88
|
+
identities.append(source)
|
|
89
|
+
return scope
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def definitions(active_sources: Sequence[Mapping[str, object]]) -> list[JsonObject]:
|
|
93
|
+
"""Advertise only read tools for packs with a registered, granted source."""
|
|
94
|
+
scope = _scope(active_sources)
|
|
95
|
+
definitions = []
|
|
96
|
+
for plugin, pack in packs(include={plugin for plugin, _ in scope}).items():
|
|
97
|
+
tool = pack.manifest.tool
|
|
98
|
+
if tool is None or not scope.get((plugin, tool.name)):
|
|
99
|
+
continue
|
|
100
|
+
read_verbs = [
|
|
101
|
+
verb.id for verb in tool.verbs if verb.approval is ApprovalTier.READ
|
|
102
|
+
]
|
|
103
|
+
if not read_verbs:
|
|
104
|
+
continue
|
|
105
|
+
definitions.append(
|
|
106
|
+
{
|
|
107
|
+
"name": tool.name,
|
|
108
|
+
"description": f"Read registered {plugin} source state.",
|
|
109
|
+
"inputSchema": {
|
|
110
|
+
"type": "object",
|
|
111
|
+
"additionalProperties": False,
|
|
112
|
+
"required": ["op", "source"],
|
|
113
|
+
"properties": {
|
|
114
|
+
"op": {"type": "string", "enum": read_verbs},
|
|
115
|
+
"source": {"type": "string", "enum": scope[plugin, tool.name]},
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
}
|
|
119
|
+
)
|
|
120
|
+
return definitions
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def turn_context(active_sources: Sequence[Mapping[str, object]]) -> str:
|
|
124
|
+
"""Supply bounded skills only for exact tool grants in the current turn."""
|
|
125
|
+
scope = _scope(active_sources)
|
|
126
|
+
hints = []
|
|
127
|
+
remaining = MAX_CONTEXT_CHARS
|
|
128
|
+
for plugin, pack in packs(include={plugin for plugin, _ in scope}).items():
|
|
129
|
+
tool = pack.manifest.tool
|
|
130
|
+
if tool is None or pack.manifest.entrypoints.skill is None:
|
|
131
|
+
continue
|
|
132
|
+
sources = scope.get((plugin, tool.name), ())
|
|
133
|
+
if not sources:
|
|
134
|
+
continue
|
|
135
|
+
_, delimiter, body = pack.skill[3:].partition("---")
|
|
136
|
+
skill = body if pack.skill.startswith("---") and delimiter else pack.skill
|
|
137
|
+
heading = display_line(f"{tool.name} · {', '.join(sources[:2])}")
|
|
138
|
+
instructions = display_line(" ".join(skill.split()))
|
|
139
|
+
hint = f"{heading}. {instructions}".rstrip()
|
|
140
|
+
if remaining <= len(heading):
|
|
141
|
+
break
|
|
142
|
+
hints.append(hint[:remaining])
|
|
143
|
+
remaining -= len(hints[-1]) + 1
|
|
144
|
+
return "\n".join(hints)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def invoke(
|
|
148
|
+
gateway: Gateway,
|
|
149
|
+
active_sources: Sequence[Mapping[str, object]],
|
|
150
|
+
name: str,
|
|
151
|
+
arguments: JsonObject,
|
|
152
|
+
) -> ToolReceipt:
|
|
153
|
+
"""Honor only the per-turn grant and the facade's declared read posture."""
|
|
154
|
+
scope = _scope(active_sources)
|
|
155
|
+
if arguments.keys() != {"op", "source"}:
|
|
156
|
+
raise ValueError("Pack tool requires a declared operation and source")
|
|
157
|
+
operation, source = arguments["op"], arguments["source"]
|
|
158
|
+
if not isinstance(operation, str) or not isinstance(source, str):
|
|
159
|
+
raise TypeError("Pack tool operation and source must be text")
|
|
160
|
+
for plugin, pack in packs(include={plugin for plugin, _ in scope}).items():
|
|
161
|
+
tool = pack.manifest.tool
|
|
162
|
+
if tool is None or tool.name != name:
|
|
163
|
+
continue
|
|
164
|
+
if source not in scope.get((plugin, name), ()):
|
|
165
|
+
raise ValueError(f"Source {source} is outside the current tool grant")
|
|
166
|
+
if not any(
|
|
167
|
+
verb.id == operation and verb.approval is ApprovalTier.READ
|
|
168
|
+
for verb in tool.verbs
|
|
169
|
+
):
|
|
170
|
+
raise ValueError(f"Operation {operation} is outside the current tool grant")
|
|
171
|
+
return pack.manage(gateway, operation, source)
|
|
172
|
+
raise ValueError("Unknown pack tool")
|