VibeCoding / src /modules /skill /domain /models.py
dellweb3's picture
Deploy verified conversational workbench and isolated Java application previews
5ca3c16 verified
Raw History Blame Contribute Delete
7.21 kB
"""Declarative Skill contracts. None of these objects can execute user code."""
from __future__ import annotations
import hashlib
import json
import math
from typing import Annotated, Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
Identifier = Annotated[str, Field(pattern=r"^[A-Za-z][A-Za-z0-9_-]{0,79}$")]
Version = Annotated[str, Field(pattern=r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")]
Kind = Literal["string", "integer", "number", "boolean", "object", "array"]
class Contract(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
class SkillError(Exception):
def __init__(self, code, message, status=422, details=None):
self.code, self.message, self.status, self.details = code, message, status, details or {}
super().__init__(message)
def canonical(value):
if isinstance(value, BaseModel):
value = value.model_dump(mode="json")
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
def digest(value):
return hashlib.sha256(canonical(value).encode()).hexdigest()
def fits(value, kind):
return {"string": lambda: isinstance(value, str), "integer": lambda: type(value) is int,
"number": lambda: type(value) is int or type(value) is float and math.isfinite(value),
"boolean": lambda: type(value) is bool, "object": lambda: isinstance(value, dict),
"array": lambda: isinstance(value, list)}[kind]()
class Port(Contract):
name: Identifier
type: Kind
required: bool = True
class Operation(Contract):
operation_id: Identifier
version: Version
name: str = Field(min_length=1, max_length=120)
handler_ref: Identifier
inputs: list[Port] = Field(max_length=24)
outputs: list[Port] = Field(max_length=24)
permissions: list[str] = Field(max_length=20)
replay: Literal["read", "idempotent", "confirm"]
timeout_seconds: int = Field(ge=1, le=600)
model_calls: int = Field(ge=0, le=1)
token_limit: int = Field(ge=0, le=60000)
evidence_refs: list[str] = Field(default_factory=list, max_length=20)
state: Literal["draft", "approved", "retired"] = "draft"
@model_validator(mode="after")
def unique_ports(self):
for ports in [self.inputs, self.outputs]:
if len({p.name for p in ports}) != len(ports):
raise ValueError("DUPLICATE_PORT")
if self.model_calls and self.token_limit < 1:
raise ValueError("MODEL_BUDGET_REQUIRED")
return self
class Node(Contract):
id: Identifier
kind: Literal["start", "operation", "approval", "end"]
operation_ref: str | None = Field(default=None, max_length=110)
approval_scope: Literal["design", "execution", "acceptance"] | None = None
inputs: dict[str, Any] = Field(default_factory=dict)
label: str = Field(default="", max_length=120)
@model_validator(mode="after")
def shape(self):
if (self.kind == "operation") != bool(self.operation_ref):
raise ValueError("OPERATION_REFERENCE_REQUIRED_ONLY_FOR_OPERATION")
if (self.kind == "approval") != bool(self.approval_scope):
raise ValueError("APPROVAL_SCOPE_REQUIRED_ONLY_FOR_APPROVAL")
if len(canonical(self.inputs)) > 24000:
raise ValueError("NODE_INPUT_TOO_LARGE")
return self
class ControlEdge(Contract):
source: Identifier
target: Identifier
class DataEdge(Contract):
source: Identifier
source_port: Identifier
target: Identifier
target_port: Identifier
class ResourceEdge(Contract):
node: Identifier
resource: Identifier
kind: Literal["knowledge", "framework"]
class Graph(Contract):
schema_version: Literal["zkcoding.skill-graph/v1"] = "zkcoding.skill-graph/v1"
nodes: list[Node] = Field(min_length=2, max_length=64)
control_edges: list[ControlEdge] = Field(min_length=1, max_length=128)
data_edges: list[DataEdge] = Field(default_factory=list, max_length=256)
resource_edges: list[ResourceEdge] = Field(default_factory=list, max_length=128)
class KnowledgeBinding(Contract):
name: Identifier
collection_id: Identifier
revision: str = Field(min_length=1, max_length=100)
usage: Literal["reference", "enterprise-rule"] = "reference"
class Budget(Contract):
max_model_calls: int = Field(default=3, ge=1, le=6)
max_tokens: int = Field(default=60000, ge=1, le=120000)
max_repairs: int = Field(default=1, ge=0, le=2)
max_seconds: int = Field(default=1800, ge=1, le=3600)
class Framework(Contract):
profile_id: Identifier
version: Version
language: Literal["java"] = "java"
java_release: Literal[17] = 17
frontend: list[Literal["html", "javascript", "css"]] = Field(default_factory=lambda: ["html", "javascript", "css"])
build_tool: Literal["maven", "jdk"] = "jdk"
dependencies: dict[str, str] = Field(default_factory=dict, max_length=50)
allowed_paths: list[str] = Field(default_factory=lambda: ["src/main/", "src/test/", "docs/"])
state: Literal["draft", "approved", "retired"] = "draft"
evidence_refs: list[str] = Field(default_factory=list, max_length=20)
@model_validator(mode="after")
def safe_paths(self):
if not self.allowed_paths or any(not p.endswith("/") or not p.startswith(("src/main/", "src/test/", "docs/", "website/")) or ".." in p or "\\" in p or ":" in p for p in self.allowed_paths):
raise ValueError("INVALID_ALLOWED_PATH")
return self
class CanvasPosition(Contract):
x: float = Field(ge=0, le=10000)
y: float = Field(ge=0, le=10000)
class Draft(Contract):
skill_id: Identifier
name: str = Field(min_length=1, max_length=120)
description: str = Field(default="", max_length=2000)
instructions: str = Field(default="", max_length=6000)
editor_positions: dict[Identifier, CanvasPosition] = Field(default_factory=dict, max_length=64)
project_id: Identifier | None = None
execution_profile_ref: Identifier | None = None
framework_ref: str = Field(min_length=1, max_length=110)
graph: Graph
knowledge_bindings: list[KnowledgeBinding] = Field(max_length=10)
budget: Budget = Field(default_factory=Budget)
execution_policy_ref: Literal["java-coding-light-v1"] = "java-coding-light-v1"
@model_validator(mode="after")
def unique_bindings(self):
if len({b.name for b in self.knowledge_bindings}) != len(self.knowledge_bindings):
raise ValueError("DUPLICATE_KNOWLEDGE_BINDING")
if set(self.editor_positions) - {node.id for node in self.graph.nodes}:
raise ValueError('EDITOR_POSITION_NODE_NOT_FOUND')
return self
class Actor(Contract):
tenant_id: str = Field(min_length=1, max_length=100)
user_id: str = Field(min_length=1, max_length=100)
roles: list[str] = Field(default_factory=list, max_length=20)
class Issue(Contract):
code: str
location: str
message: str
class ValidationReport(Contract):
valid: bool
digest: str
issues: list[Issue]
execution_order: list[str]
operation_locks: dict[str, str]
model_calls: int
model_token_limits: int