clm-kernel 0.0.0__py3-none-any.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.
- clm/__init__.py +230 -0
- clm/__main__.py +25 -0
- clm/cross_cutting/__init__.py +50 -0
- clm/cross_cutting/_test_runner.py +36 -0
- clm/cross_cutting/async_utils.py +25 -0
- clm/cross_cutting/cel_builder.py +123 -0
- clm/cross_cutting/cel_converter.py +697 -0
- clm/cross_cutting/cel_engine.py +252 -0
- clm/cross_cutting/cel_ops.py +72 -0
- clm/cross_cutting/cel_ops_db.py +157 -0
- clm/cross_cutting/cel_ops_files.py +99 -0
- clm/cross_cutting/cel_ops_state.py +71 -0
- clm/cross_cutting/cel_ops_strings.py +64 -0
- clm/cross_cutting/cel_resolver.py +63 -0
- clm/cross_cutting/cel_slices.py +56 -0
- clm/cross_cutting/cel_store.py +330 -0
- clm/cross_cutting/clm_logger.py +140 -0
- clm/cross_cutting/config/__init__.py +155 -0
- clm/cross_cutting/config/config_constants.py +392 -0
- clm/cross_cutting/config/env_parameters.py +90 -0
- clm/cross_cutting/config/logging.py +378 -0
- clm/cross_cutting/config/settings.py +504 -0
- clm/cross_cutting/context.py +5 -0
- clm/cross_cutting/domain_models.py +55 -0
- clm/cross_cutting/domain_types.py +61 -0
- clm/cross_cutting/effects.py +67 -0
- clm/cross_cutting/errors.py +153 -0
- clm/cross_cutting/governance.py +331 -0
- clm/cross_cutting/guards.py +41 -0
- clm/cross_cutting/mcard.py +321 -0
- clm/cross_cutting/native.py +185 -0
- clm/cross_cutting/observability.py +289 -0
- clm/cross_cutting/pcard.py +434 -0
- clm/cross_cutting/registry.py +71 -0
- clm/cross_cutting/resources.py +84 -0
- clm/cross_cutting/secrets.py +44 -0
- clm/cross_cutting/subprocess_utils.py +118 -0
- clm/cross_cutting/telemetry.py +164 -0
- clm/cross_cutting/testing/__init__.py +8 -0
- clm/cross_cutting/testing/comparator.py +187 -0
- clm/cross_cutting/testing/datasets.py +87 -0
- clm/cross_cutting/timeutil.py +20 -0
- clm/cross_cutting/types/new_type_check.py +0 -0
- clm/cross_cutting/utils/__init__.py +1 -0
- clm/cross_cutting/utils/url_safety.py +50 -0
- clm/cross_cutting/vcard.py +560 -0
- clm/cross_cutting/writer.py +118 -0
- clm/layer0/README.md +50 -0
- clm/layer0/__init__.py +223 -0
- clm/layer0/algebra.py +60 -0
- clm/layer0/algebra_baldwin.py +133 -0
- clm/layer0/algebra_baldwin_generators.py +36 -0
- clm/layer0/algebra_equivalence.py +262 -0
- clm/layer0/algebra_ingest.py +306 -0
- clm/layer0/algebra_manifest_io.py +156 -0
- clm/layer0/assembler.py +481 -0
- clm/layer0/cel/__init__.py +23 -0
- clm/layer0/cel_eval.py +491 -0
- clm/layer0/codec.py +106 -0
- clm/layer0/context.py +122 -0
- clm/layer0/db.py +160 -0
- clm/layer0/exceptions.py +73 -0
- clm/layer0/fibration.py +106 -0
- clm/layer0/gates.py +50 -0
- clm/layer0/hash.py +80 -0
- clm/layer0/loader.py +826 -0
- clm/layer0/math_utils.py +163 -0
- clm/layer0/mcard.py +96 -0
- clm/layer0/model/__init__.py +0 -0
- clm/layer0/model/action.py +223 -0
- clm/layer0/model/card.py +280 -0
- clm/layer0/model/card_triad.py +427 -0
- clm/layer0/model/compatibility.py +60 -0
- clm/layer0/model/dictionary.py +46 -0
- clm/layer0/model/dots.py +331 -0
- clm/layer0/model/event_producer.py +88 -0
- clm/layer0/model/g_time.py +89 -0
- clm/layer0/model/handle.py +163 -0
- clm/layer0/model/hash/__init__.py +6 -0
- clm/layer0/model/hash/algorithms/__init__.py +3 -0
- clm/layer0/model/hash/algorithms/custom_hash.py +7 -0
- clm/layer0/model/hash/algorithms/local_sha256.py +178 -0
- clm/layer0/model/hash/constants.py +53 -0
- clm/layer0/model/hash/enums.py +60 -0
- clm/layer0/model/hash/validator.py +307 -0
- clm/layer0/model/interpreter.py +275 -0
- clm/layer0/model/pagination.py +45 -0
- clm/layer0/model/pcard.py +716 -0
- clm/layer0/model/schema.py +44 -0
- clm/layer0/model/utils/__init__.py +1 -0
- clm/layer0/model/utils/content_analyzer.py +152 -0
- clm/layer0/model/validators/__init__.py +1 -0
- clm/layer0/model/validators/base_validator.py +44 -0
- clm/layer0/model/validators/binary_validator.py +66 -0
- clm/layer0/model/validators/text_validator.py +82 -0
- clm/layer0/model/validators/validation_registry.py +49 -0
- clm/layer0/model/vcard.py +823 -0
- clm/layer0/model/vcard_ext/__init__.py +39 -0
- clm/layer0/model/vcard_ext/core.py +60 -0
- clm/layer0/model/vcard_ext/network.py +23 -0
- clm/layer0/model/vcard_ext/observability.py +63 -0
- clm/layer0/model/vcard_ext/storage.py +60 -0
- clm/layer0/model/vcard_ext/vendors.py +211 -0
- clm/layer0/model/vcard_sandwich.py +119 -0
- clm/layer0/model/vcard_vocabulary.py +463 -0
- clm/layer0/model/workflow.py +274 -0
- clm/layer0/narrative.py +431 -0
- clm/layer0/ontology/collection.py +125 -0
- clm/layer0/parser.py +429 -0
- clm/layer0/relations.py +73 -0
- clm/layer0/rule_evaluator.py +251 -0
- clm/layer0/schema/__init__.py +38 -0
- clm/layer0/schema/ddl.py +97 -0
- clm/layer0/templates/abstract.yaml +99 -0
- clm/layer0/templates/balanced.yaml +253 -0
- clm/layer0/templates/concrete.yaml +172 -0
- clm/layer0/type_registry.py +223 -0
- clm/layer0/types.py +204 -0
- clm/layer0/utils.py +886 -0
- clm/layer0/verifier_core.py +262 -0
- clm/layer1/__init__.py +31 -0
- clm/layer1/action_dispatcher.py +275 -0
- clm/layer1/adapter_registry.py +233 -0
- clm/layer1/algebra_baldwin_generators.py +192 -0
- clm/layer1/arrow_compiler.py +525 -0
- clm/layer1/batch_processor.py +152 -0
- clm/layer1/cel/__init__.py +27 -0
- clm/layer1/cel/builder.py +173 -0
- clm/layer1/engine.py +759 -0
- clm/layer1/engine_async.py +89 -0
- clm/layer1/eval_callback.py +49 -0
- clm/layer1/gate_composer.py +229 -0
- clm/layer1/hoare_sandwich.py +298 -0
- clm/layer1/identity_guard.py +348 -0
- clm/layer1/matrix.py +138 -0
- clm/layer1/neural_runtime.py +221 -0
- clm/layer1/operations/__init__.py +123 -0
- clm/layer1/operations/augment.py +156 -0
- clm/layer1/operations/base.py +109 -0
- clm/layer1/operations/builtins.py +338 -0
- clm/layer1/operations/dispatch.py +144 -0
- clm/layer1/operations/exclude.py +107 -0
- clm/layer1/operations/handle.py +197 -0
- clm/layer1/operations/identity.py +139 -0
- clm/layer1/operations/invert.py +66 -0
- clm/layer1/operations/loader.py +116 -0
- clm/layer1/operations/manipulators/__init__.py +23 -0
- clm/layer1/operations/manipulators/document.py +211 -0
- clm/layer1/operations/manipulators/media.py +134 -0
- clm/layer1/operations/manipulators/structured.py +159 -0
- clm/layer1/operations/manipulators/tabular.py +334 -0
- clm/layer1/operations/port.py +65 -0
- clm/layer1/operations/services.py +529 -0
- clm/layer1/operations/split.py +117 -0
- clm/layer1/operations/substitute.py +75 -0
- clm/layer1/petri.py +1052 -0
- clm/layer1/pocketflow_orchestrator.py +408 -0
- clm/layer1/pocketflow_scheduler.py +519 -0
- clm/layer1/protocols.py +197 -0
- clm/layer1/runtime_adapter.py +718 -0
- clm/layer1/runtimes/__init__.py +71 -0
- clm/layer1/runtimes/_generated_assertions.py +125 -0
- clm/layer1/runtimes/_generated_types.py +42 -0
- clm/layer1/runtimes/base.py +265 -0
- clm/layer1/runtimes/binary.py +101 -0
- clm/layer1/runtimes/factory.py +203 -0
- clm/layer1/runtimes/javascript.py +321 -0
- clm/layer1/runtimes/javascript_runtime.js +33 -0
- clm/layer1/runtimes/js_scripts/isomorphism.mjs +22 -0
- clm/layer1/runtimes/js_scripts/loader.mjs +52 -0
- clm/layer1/runtimes/lambda_calc.py +126 -0
- clm/layer1/runtimes/python.py +288 -0
- clm/layer1/runtimes/python_runtime.py +41 -0
- clm/layer1/runtimes/script.py +114 -0
- clm/layer1/sandbox.py +334 -0
- clm/layer1/savepoint_guard.py +136 -0
- clm/layer1/sparse_net.py +122 -0
- clm/layer1/spec_tester.py +165 -0
- clm/layer1/store.py +295 -0
- clm/layer1/test_runner.py +498 -0
- clm/layer1/type_inspector.py +166 -0
- clm/layer1/verifier.py +772 -0
- clm/layer1/vm.py +91 -0
- clm/layer2/__init__.py +78 -0
- clm/layer2/card_collection.py +678 -0
- clm/layer2/classifier.py +479 -0
- clm/layer2/engine/__init__.py +1 -0
- clm/layer2/engine/abstract_sql_engine.py +320 -0
- clm/layer2/engine/base.py +193 -0
- clm/layer2/engine/duckdb_engine.py +576 -0
- clm/layer2/engine/sqlite_engine.py +518 -0
- clm/layer2/fiber/__init__.py +31 -0
- clm/layer2/fiber/context.py +89 -0
- clm/layer2/fiber/disposable.py +163 -0
- clm/layer2/fiber/fiber.py +125 -0
- clm/layer2/fiber/hoare.py +191 -0
- clm/layer2/file_io.py +376 -0
- clm/layer2/file_registrar.py +77 -0
- clm/layer2/ingest.py +202 -0
- clm/layer2/lineage.py +322 -0
- clm/layer2/mcard_fs.py +262 -0
- clm/layer2/merkle.py +11 -0
- clm/layer2/mime.py +244 -0
- clm/layer2/mime_detector.py +245 -0
- clm/layer2/private_collection.py +118 -0
- clm/layer2/shared_store.py +11 -0
- clm/layer2/storage/__init__.py +190 -0
- clm/layer2/storage/db_bitemporal.py +141 -0
- clm/layer2/storage/db_driver.py +331 -0
- clm/layer2/storage/db_hyperlinks.py +214 -0
- clm/layer2/storage/db_pool.py +139 -0
- clm/layer2/storage/db_repository.py +229 -0
- clm/layer2/storage/savepoint.py +78 -0
- clm/layer2/storage/sqlite_wal.py +74 -0
- clm/layer2/tridb.py +245 -0
- clm/layer2/vcard_receipt.py +71 -0
- clm/layer2/vfs.py +17 -0
- clm/layer3/__init__.py +141 -0
- clm/layer3/agency/__init__.py +19 -0
- clm/layer3/agency/config.py +220 -0
- clm/layer3/agency/providers/__init__.py +15 -0
- clm/layer3/agency/providers/base.py +91 -0
- clm/layer3/agency/providers/mlc_llm.py +169 -0
- clm/layer3/agency/providers/ollama.py +203 -0
- clm/layer3/agency/router.py +71 -0
- clm/layer3/agency/runtime.py +524 -0
- clm/layer3/gateway.py +353 -0
- clm/layer3/open_interpreter_adapter.py +159 -0
- clm/layer3/rag/__init__.py +70 -0
- clm/layer3/rag/cli.py +228 -0
- clm/layer3/rag/config.py +153 -0
- clm/layer3/rag/embeddings/__init__.py +16 -0
- clm/layer3/rag/embeddings/base.py +79 -0
- clm/layer3/rag/embeddings/ollama.py +211 -0
- clm/layer3/rag/embeddings/vision.py +290 -0
- clm/layer3/rag/engine.py +276 -0
- clm/layer3/rag/graph/__init__.py +22 -0
- clm/layer3/rag/graph/community.py +198 -0
- clm/layer3/rag/graph/engine.py +433 -0
- clm/layer3/rag/graph/extractor.py +255 -0
- clm/layer3/rag/graph/schema.py +115 -0
- clm/layer3/rag/graph/store.py +641 -0
- clm/layer3/rag/indexer.py +333 -0
- clm/layer3/rag/llm_providers.json +52 -0
- clm/layer3/rag/semantic_versioning.py +313 -0
- clm/layer3/rag/vector/__init__.py +28 -0
- clm/layer3/rag/vector/handle_vector_store.py +749 -0
- clm/layer3/rag/vector/schema.py +151 -0
- clm/layer3/rag/vector/store.py +632 -0
- clm/layer3/reticulum/__init__.py +55 -0
- clm/layer3/reticulum/bridge.py +74 -0
- clm/layer3/reticulum/daemon.py +88 -0
- clm/layer3/reticulum/discovery.py +164 -0
- clm/layer3/reticulum/identity.py +107 -0
- clm/layer3/reticulum/media.py +148 -0
- clm/layer3/reticulum/transport.py +133 -0
- clm/layer3/satori/__init__.py +209 -0
- clm/layer3/satori/alpha_conversion.py +168 -0
- clm/layer3/satori/beta_reduction.py +359 -0
- clm/layer3/satori/continuation.py +38 -0
- clm/layer3/satori/eta_conversion.py +205 -0
- clm/layer3/satori/free_variables.py +163 -0
- clm/layer3/satori/io_effects.py +370 -0
- clm/layer3/satori/lambda_runtime.py +726 -0
- clm/layer3/satori/lambda_term.py +230 -0
- clm/layer3/satori/sheaf_audit.py +261 -0
- clm/layer3/satori/speech_act.py +279 -0
- clm/layer4/README.md +9 -0
- clm/layer4/__init__.py +67 -0
- clm/layer4/_sovereign_executor.py +580 -0
- clm/layer4/action_commands.py +719 -0
- clm/layer4/api.py +236 -0
- clm/layer4/bootstrap/__init__.py +13 -0
- clm/layer4/bootstrap/bootstrapper.py +118 -0
- clm/layer4/bootstrap/cleanup.py +44 -0
- clm/layer4/bootstrap/clm_hooks.py +49 -0
- clm/layer4/bootstrap/genesis.py +77 -0
- clm/layer4/bootstrap/injection.py +125 -0
- clm/layer4/cli.py +549 -0
- clm/layer4/collection_manager.py +553 -0
- clm/layer4/commands/__init__.py +81 -0
- clm/layer4/commands/action_cmd.py +42 -0
- clm/layer4/commands/check_cmd.py +82 -0
- clm/layer4/commands/envelope.py +73 -0
- clm/layer4/commands/evaluate_cmd.py +224 -0
- clm/layer4/commands/mcard_cmd.py +24 -0
- clm/layer4/commands/petri_cmd.py +92 -0
- clm/layer4/commands/tridb_cmd.py +319 -0
- clm/layer4/commands/version_cmd.py +27 -0
- clm/layer4/diff_commands.py +167 -0
- clm/layer4/eoa_sponsor.py +232 -0
- clm/layer4/events.py +69 -0
- clm/layer4/flux_gateway.py +133 -0
- clm/layer4/gateway.py +91 -0
- clm/layer4/loader.py +307 -0
- clm/layer4/mcard_commands.py +166 -0
- clm/layer4/membrane.py +273 -0
- clm/layer4/navigation.py +50 -0
- clm/layer4/protocol/protocol_entry_python.py +108 -0
- clm/layer4/protocol/python_sync.py +126 -0
- clm/layer4/runner.py +150 -0
- clm/layer4/satori.py +262 -0
- clm/layer4/server/python_sync_client.py +150 -0
- clm/layer4/server/python_sync_server.py +139 -0
- clm/layer4/server/service_api.py +315 -0
- clm/layer4/server/start_servers.py +107 -0
- clm/layer4/server/stop_servers.py +24 -0
- clm/layer4/simulated_optimization_fix.py +0 -0
- clm/layer4/storage.py +463 -0
- clm/layer4/tridb_admin.py +268 -0
- clm/layer4/websocket/test_ws_client.py +104 -0
- clm/layer4/websocket/test_ws_server.py +138 -0
- clm/layer4/websocket/ws_server_local.py +160 -0
- clm/layer5/__init__.py +51 -0
- clm/layer5/async_batch_writer.py +133 -0
- clm/layer5/learning.py +276 -0
- clm/layer5/telemetry_hook.py +107 -0
- clm/layer5/type_lattice.py +238 -0
- clm/py.typed +0 -0
- clm/schemas/__init__.py +652 -0
- clm/schemas/abstract_face_schema.yaml +77 -0
- clm/schemas/cel_schema.yaml +416 -0
- clm/schemas/lifecycle/__init__.py +45 -0
- clm/schemas/lifecycle/models.py +123 -0
- clm/schemas/lifecycle/service.py +364 -0
- clm/schemas/mcard_schema.sql +192 -0
- clm/schemas/mcard_vector_schema.sql +283 -0
- clm/schemas/mlp-context-v1.json +91 -0
- clm_kernel-0.0.0.dist-info/METADATA +121 -0
- clm_kernel-0.0.0.dist-info/RECORD +333 -0
- clm_kernel-0.0.0.dist-info/WHEEL +4 -0
- clm_kernel-0.0.0.dist-info/entry_points.txt +3 -0
- clm_kernel-0.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Cross-Runtime Communication Demo: Python Sync Server
|
|
4
|
+
|
|
5
|
+
This starts a sync server that JavaScript (or any HTTP client) can connect to.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
# Add the project root to path
|
|
15
|
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
|
16
|
+
|
|
17
|
+
from clm.layer0.model.card import MCard
|
|
18
|
+
from clm.layer2.card_collection import CardCollection
|
|
19
|
+
|
|
20
|
+
# Create a collection with some seed data
|
|
21
|
+
collection = CardCollection(db_path=":memory:")
|
|
22
|
+
|
|
23
|
+
# Add initial MCards to demonstrate sync
|
|
24
|
+
seed_cards = [
|
|
25
|
+
MCard("Hello from Python! 🐍"),
|
|
26
|
+
MCard("Python PTR Server is ready"),
|
|
27
|
+
MCard(json.dumps({"origin": "python", "timestamp": time.time()})),
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
for card in seed_cards:
|
|
31
|
+
collection.add(card)
|
|
32
|
+
|
|
33
|
+
print(f"[Python Server] Created collection with {len(seed_cards)} seed MCards:")
|
|
34
|
+
for card in seed_cards:
|
|
35
|
+
content = card.get_content()
|
|
36
|
+
if isinstance(content, bytes):
|
|
37
|
+
content = content.decode("utf-8")
|
|
38
|
+
print(f" • {card.hash[:16]}... = '{content[:50]}'")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SyncHandler(BaseHTTPRequestHandler):
|
|
42
|
+
"""Handle sync protocol requests."""
|
|
43
|
+
|
|
44
|
+
def log_message(self, format, *args):
|
|
45
|
+
print(f"[Python Server] {args[0]}")
|
|
46
|
+
|
|
47
|
+
def _send_json(self, code, data):
|
|
48
|
+
self.send_response(code)
|
|
49
|
+
self.send_header("Content-Type", "application/json")
|
|
50
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
51
|
+
self.end_headers()
|
|
52
|
+
self.wfile.write(json.dumps(data).encode())
|
|
53
|
+
|
|
54
|
+
def do_OPTIONS(self):
|
|
55
|
+
"""Handle CORS preflight."""
|
|
56
|
+
self.send_response(200)
|
|
57
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
58
|
+
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
|
59
|
+
self.send_header("Access-Control-Allow-Headers", "Content-Type")
|
|
60
|
+
self.end_headers()
|
|
61
|
+
|
|
62
|
+
def do_GET(self):
|
|
63
|
+
if self.path == "/sync/manifest":
|
|
64
|
+
# Return list of all hashes
|
|
65
|
+
cards = collection.get_all_mcards_raw()
|
|
66
|
+
hashes = [c.hash for c in cards]
|
|
67
|
+
print(f"[Python Server] Manifest requested: {len(hashes)} cards")
|
|
68
|
+
self._send_json(200, hashes)
|
|
69
|
+
elif self.path == "/health":
|
|
70
|
+
self._send_json(200, {"status": "healthy", "runtime": "python"})
|
|
71
|
+
else:
|
|
72
|
+
self._send_json(404, {"error": "Not found"})
|
|
73
|
+
|
|
74
|
+
def do_POST(self):
|
|
75
|
+
content_length = int(self.headers.get("Content-Length", 0))
|
|
76
|
+
body = json.loads(self.rfile.read(content_length).decode())
|
|
77
|
+
|
|
78
|
+
if self.path == "/sync/batch":
|
|
79
|
+
# Receive cards from client
|
|
80
|
+
cards_data = body.get("cards", [])
|
|
81
|
+
added = 0
|
|
82
|
+
for card_json in cards_data:
|
|
83
|
+
try:
|
|
84
|
+
import base64
|
|
85
|
+
|
|
86
|
+
content = base64.b64decode(card_json["content"])
|
|
87
|
+
card = MCard(content)
|
|
88
|
+
collection.add(card)
|
|
89
|
+
added += 1
|
|
90
|
+
print(f"[Python Server] Received MCard: {card.hash[:16]}...")
|
|
91
|
+
except Exception as e:
|
|
92
|
+
print(f"[Python Server] Error adding card: {e}")
|
|
93
|
+
|
|
94
|
+
self._send_json(200, {"success": True, "added": added})
|
|
95
|
+
|
|
96
|
+
elif self.path == "/sync/get":
|
|
97
|
+
# Send requested cards to client
|
|
98
|
+
hashes = body.get("hashes", [])
|
|
99
|
+
cards = []
|
|
100
|
+
import base64
|
|
101
|
+
|
|
102
|
+
for h in hashes:
|
|
103
|
+
card = collection.get(h)
|
|
104
|
+
if card:
|
|
105
|
+
content = card.get_content()
|
|
106
|
+
if isinstance(content, str):
|
|
107
|
+
content = content.encode()
|
|
108
|
+
cards.append(
|
|
109
|
+
{
|
|
110
|
+
"hash": card.hash,
|
|
111
|
+
"content": base64.b64encode(content).decode(),
|
|
112
|
+
"g_time": card.g_time,
|
|
113
|
+
}
|
|
114
|
+
)
|
|
115
|
+
print(f"[Python Server] Sending {len(cards)} cards to client")
|
|
116
|
+
self._send_json(200, {"cards": cards})
|
|
117
|
+
|
|
118
|
+
else:
|
|
119
|
+
self._send_json(404, {"error": "Not found"})
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
if __name__ == "__main__":
|
|
123
|
+
port = 3001
|
|
124
|
+
server = HTTPServer(("", port), SyncHandler)
|
|
125
|
+
|
|
126
|
+
print(f"\n{'=' * 60}")
|
|
127
|
+
print(f" Python Sync Server running on http://localhost:{port}")
|
|
128
|
+
print(" Endpoints:")
|
|
129
|
+
print(" GET /sync/manifest - List all MCard hashes")
|
|
130
|
+
print(" POST /sync/batch - Receive MCards from client")
|
|
131
|
+
print(" POST /sync/get - Send MCards to client")
|
|
132
|
+
print(f"{'=' * 60}\n")
|
|
133
|
+
print("Waiting for JavaScript client to connect...\n")
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
server.serve_forever()
|
|
137
|
+
except KeyboardInterrupt:
|
|
138
|
+
print("\n[Python Server] Shutting down")
|
|
139
|
+
server.shutdown()
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
MCard/PTR Service Engine API
|
|
4
|
+
|
|
5
|
+
A FastAPI service that exposes CLM execution across all installed language runtimes
|
|
6
|
+
via the CLM Protocol (schema/clm_protocol.json).
|
|
7
|
+
|
|
8
|
+
Endpoints:
|
|
9
|
+
POST /execute — Execute code in any registered runtime
|
|
10
|
+
POST /clm/run — Run a CLM YAML file
|
|
11
|
+
GET /runtimes — List available runtimes and their status
|
|
12
|
+
GET /protocol — Return the CLM protocol spec
|
|
13
|
+
GET /health — Health check
|
|
14
|
+
|
|
15
|
+
Usage:
|
|
16
|
+
uvicorn scripts.service_api:app --host 0.0.0.0 --port 8000
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
import time
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from clm.cross_cutting.config.config_constants import SERVICE_RUNTIME_CHECK_TIMEOUT_SECS
|
|
27
|
+
from fastapi import FastAPI, HTTPException
|
|
28
|
+
from pydantic import BaseModel
|
|
29
|
+
|
|
30
|
+
PROJECT_ROOT = Path(__file__).parent.parent.resolve()
|
|
31
|
+
REGISTRY_DIR = PROJECT_ROOT / "schema" / "runtime_registry"
|
|
32
|
+
PROTOCOL_PATH = PROJECT_ROOT / "schema" / "clm_protocol.json"
|
|
33
|
+
|
|
34
|
+
app = FastAPI(
|
|
35
|
+
title="MCard/PTR Service Engine",
|
|
36
|
+
description="Cross-language CLM execution service with protocol-compliant runtimes",
|
|
37
|
+
version="1.0.0",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ── Models ────────────────────────────────────────────────────────────────────
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ExecuteRequest(BaseModel):
|
|
45
|
+
runtime: str = "python"
|
|
46
|
+
code: str
|
|
47
|
+
context: dict[str, Any] = {}
|
|
48
|
+
entry_point: str | None = None
|
|
49
|
+
timeout_ms: int = 30000
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ExecuteResponse(BaseModel):
|
|
53
|
+
success: bool
|
|
54
|
+
result: Any = None
|
|
55
|
+
error: str | None = None
|
|
56
|
+
runtime: str = ""
|
|
57
|
+
duration_ms: float = 0
|
|
58
|
+
logs: list[str] = []
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class CLMRunRequest(BaseModel):
|
|
62
|
+
file: str
|
|
63
|
+
runtimes: list[str] = ["python"]
|
|
64
|
+
timeout_ms: int = 30000
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class RuntimeInfo(BaseModel):
|
|
68
|
+
id: str
|
|
69
|
+
command: Any
|
|
70
|
+
entry_script: str | None
|
|
71
|
+
protocol_version: str
|
|
72
|
+
available: bool
|
|
73
|
+
version: str | None = None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# ── Runtime Registry ──────────────────────────────────────────────────────────
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def load_registry() -> dict[str, dict]:
|
|
80
|
+
"""Load all runtime manifests from schema/runtime_registry/."""
|
|
81
|
+
registry = {}
|
|
82
|
+
if REGISTRY_DIR.exists():
|
|
83
|
+
for f in REGISTRY_DIR.glob("*.json"):
|
|
84
|
+
with open(f) as fh:
|
|
85
|
+
manifest = json.load(fh)
|
|
86
|
+
registry[manifest["id"]] = manifest
|
|
87
|
+
return registry
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def check_runtime_available(manifest: dict) -> tuple[bool, str | None]:
|
|
91
|
+
"""Check if a runtime is available on the system."""
|
|
92
|
+
env_check = manifest.get("environment_check")
|
|
93
|
+
if not env_check:
|
|
94
|
+
return False, None
|
|
95
|
+
try:
|
|
96
|
+
result = subprocess.run(
|
|
97
|
+
env_check.split(),
|
|
98
|
+
capture_output=True,
|
|
99
|
+
text=True,
|
|
100
|
+
timeout=SERVICE_RUNTIME_CHECK_TIMEOUT_SECS,
|
|
101
|
+
)
|
|
102
|
+
if result.returncode == 0:
|
|
103
|
+
version = result.stdout.strip().split("\n")[0]
|
|
104
|
+
return True, version
|
|
105
|
+
return False, None
|
|
106
|
+
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
|
|
107
|
+
return False, None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ── Protocol Execution ────────────────────────────────────────────────────────
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def execute_via_protocol(
|
|
114
|
+
manifest: dict, code: str, context: dict, entry_point: str | None, timeout_ms: int
|
|
115
|
+
) -> ExecuteResponse:
|
|
116
|
+
"""Execute code using the CLM protocol (JSON stdin/stdout)."""
|
|
117
|
+
entry_script = manifest.get("entry_script")
|
|
118
|
+
if not entry_script:
|
|
119
|
+
return ExecuteResponse(
|
|
120
|
+
success=False,
|
|
121
|
+
error=f"Runtime '{manifest['id']}' has no entry_script (not protocol-compliant)",
|
|
122
|
+
runtime=manifest["id"],
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
entry_path = PROJECT_ROOT / entry_script
|
|
126
|
+
if not entry_path.exists():
|
|
127
|
+
return ExecuteResponse(
|
|
128
|
+
success=False,
|
|
129
|
+
error=f"Entry script not found: {entry_script}",
|
|
130
|
+
runtime=manifest["id"],
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
# Build the protocol request
|
|
134
|
+
request = {"code": code, "context": context, "config": {}}
|
|
135
|
+
if entry_point:
|
|
136
|
+
request["entry_point"] = entry_point
|
|
137
|
+
|
|
138
|
+
# Determine command
|
|
139
|
+
command = manifest.get("command", "python3")
|
|
140
|
+
if isinstance(command, list):
|
|
141
|
+
cmd = command + [str(entry_path)]
|
|
142
|
+
else:
|
|
143
|
+
cmd = [command, str(entry_path)]
|
|
144
|
+
|
|
145
|
+
start = time.perf_counter()
|
|
146
|
+
try:
|
|
147
|
+
proc = subprocess.run(
|
|
148
|
+
cmd,
|
|
149
|
+
input=json.dumps(request),
|
|
150
|
+
capture_output=True,
|
|
151
|
+
text=True,
|
|
152
|
+
timeout=timeout_ms / 1000,
|
|
153
|
+
cwd=str(PROJECT_ROOT),
|
|
154
|
+
)
|
|
155
|
+
duration_ms = (time.perf_counter() - start) * 1000
|
|
156
|
+
|
|
157
|
+
# Parse the JSON response from stdout (last line)
|
|
158
|
+
stdout = proc.stdout.strip()
|
|
159
|
+
if not stdout:
|
|
160
|
+
return ExecuteResponse(
|
|
161
|
+
success=False,
|
|
162
|
+
error=f"No output from runtime. Stderr: {proc.stderr[:500]}",
|
|
163
|
+
runtime=manifest["id"],
|
|
164
|
+
duration_ms=round(duration_ms, 2),
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
# Take last JSON line
|
|
168
|
+
for line in reversed(stdout.split("\n")):
|
|
169
|
+
line = line.strip()
|
|
170
|
+
if line.startswith("{"):
|
|
171
|
+
response_data = json.loads(line)
|
|
172
|
+
return ExecuteResponse(
|
|
173
|
+
success=response_data.get("success", False),
|
|
174
|
+
result=response_data.get("result"),
|
|
175
|
+
error=response_data.get("error"),
|
|
176
|
+
runtime=manifest["id"],
|
|
177
|
+
duration_ms=response_data.get("duration_ms", round(duration_ms, 2)),
|
|
178
|
+
logs=response_data.get("logs", []),
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
return ExecuteResponse(
|
|
182
|
+
success=False,
|
|
183
|
+
error=f"No JSON in output: {stdout[:200]}",
|
|
184
|
+
runtime=manifest["id"],
|
|
185
|
+
duration_ms=round(duration_ms, 2),
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
except subprocess.TimeoutExpired:
|
|
189
|
+
return ExecuteResponse(
|
|
190
|
+
success=False,
|
|
191
|
+
error=f"Timeout after {timeout_ms}ms",
|
|
192
|
+
runtime=manifest["id"],
|
|
193
|
+
duration_ms=timeout_ms,
|
|
194
|
+
)
|
|
195
|
+
except json.JSONDecodeError as e:
|
|
196
|
+
return ExecuteResponse(
|
|
197
|
+
success=False,
|
|
198
|
+
error=f"Invalid JSON response: {e}",
|
|
199
|
+
runtime=manifest["id"],
|
|
200
|
+
)
|
|
201
|
+
except Exception as e:
|
|
202
|
+
return ExecuteResponse(
|
|
203
|
+
success=False,
|
|
204
|
+
error=str(e),
|
|
205
|
+
runtime=manifest["id"],
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# ── Endpoints ─────────────────────────────────────────────────────────────────
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@app.post("/execute", response_model=ExecuteResponse)
|
|
213
|
+
async def execute(req: ExecuteRequest):
|
|
214
|
+
"""Execute code in the specified runtime via the CLM protocol."""
|
|
215
|
+
registry = load_registry()
|
|
216
|
+
|
|
217
|
+
# Resolve aliases
|
|
218
|
+
from clm.layer1.runtimes.base import resolve_runtime_alias
|
|
219
|
+
|
|
220
|
+
runtime_id = resolve_runtime_alias(req.runtime)
|
|
221
|
+
|
|
222
|
+
manifest = registry.get(runtime_id)
|
|
223
|
+
if not manifest:
|
|
224
|
+
raise HTTPException(
|
|
225
|
+
status_code=400,
|
|
226
|
+
detail=f"Unknown runtime: '{req.runtime}'. Available: {list(registry.keys())}",
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
available, _ = check_runtime_available(manifest)
|
|
230
|
+
if not available:
|
|
231
|
+
raise HTTPException(
|
|
232
|
+
status_code=503,
|
|
233
|
+
detail=f"Runtime '{runtime_id}' is not available on this system",
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
return execute_via_protocol(
|
|
237
|
+
manifest, req.code, req.context, req.entry_point, req.timeout_ms
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
@app.post("/clm/run")
|
|
242
|
+
async def run_clm(req: CLMRunRequest):
|
|
243
|
+
"""Run a CLM YAML file through specified runtimes and return results."""
|
|
244
|
+
clm_path = PROJECT_ROOT / req.file
|
|
245
|
+
if not clm_path.exists():
|
|
246
|
+
raise HTTPException(status_code=404, detail=f"CLM file not found: {req.file}")
|
|
247
|
+
|
|
248
|
+
from clm.layer4.runner import CLMRunner
|
|
249
|
+
|
|
250
|
+
runner = CLMRunner()
|
|
251
|
+
context = {"pcard_dir": str(clm_path.parent.absolute())}
|
|
252
|
+
|
|
253
|
+
results = {}
|
|
254
|
+
for runtime in req.runtimes:
|
|
255
|
+
if runtime == "python":
|
|
256
|
+
try:
|
|
257
|
+
import io
|
|
258
|
+
|
|
259
|
+
old_stdout, old_stderr = sys.stdout, sys.stderr
|
|
260
|
+
sys.stdout = io.StringIO()
|
|
261
|
+
sys.stderr = io.StringIO()
|
|
262
|
+
try:
|
|
263
|
+
report = runner.run_file(str(clm_path), context=context)
|
|
264
|
+
finally:
|
|
265
|
+
sys.stdout, sys.stderr = old_stdout, old_stderr
|
|
266
|
+
results["python"] = {
|
|
267
|
+
"success": report.get("status") == "success",
|
|
268
|
+
"result": report.get("result"),
|
|
269
|
+
}
|
|
270
|
+
except Exception as e:
|
|
271
|
+
sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__
|
|
272
|
+
results["python"] = {"success": False, "error": str(e)}
|
|
273
|
+
|
|
274
|
+
return {"file": req.file, "results": results}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
@app.get("/runtimes")
|
|
278
|
+
async def list_runtimes():
|
|
279
|
+
"""List all registered runtimes and their availability."""
|
|
280
|
+
registry = load_registry()
|
|
281
|
+
runtimes = []
|
|
282
|
+
for rid, manifest in registry.items():
|
|
283
|
+
available, version = check_runtime_available(manifest)
|
|
284
|
+
runtimes.append(
|
|
285
|
+
RuntimeInfo(
|
|
286
|
+
id=rid,
|
|
287
|
+
command=manifest.get("command"),
|
|
288
|
+
entry_script=manifest.get("entry_script"),
|
|
289
|
+
protocol_version=manifest.get("protocol_version", "1.0"),
|
|
290
|
+
available=available,
|
|
291
|
+
version=version,
|
|
292
|
+
)
|
|
293
|
+
)
|
|
294
|
+
return {"runtimes": [r.model_dump() for r in runtimes]}
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
@app.get("/protocol")
|
|
298
|
+
async def get_protocol():
|
|
299
|
+
"""Return the CLM protocol specification."""
|
|
300
|
+
if PROTOCOL_PATH.exists():
|
|
301
|
+
with open(PROTOCOL_PATH) as f:
|
|
302
|
+
return json.load(f)
|
|
303
|
+
raise HTTPException(status_code=404, detail="Protocol spec not found")
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
@app.get("/health")
|
|
307
|
+
async def health():
|
|
308
|
+
"""Health check."""
|
|
309
|
+
registry = load_registry()
|
|
310
|
+
available_count = sum(1 for m in registry.values() if check_runtime_available(m)[0])
|
|
311
|
+
return {
|
|
312
|
+
"status": "healthy",
|
|
313
|
+
"registered_runtimes": len(registry),
|
|
314
|
+
"available_runtimes": available_count,
|
|
315
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Unified Server Script (CLM-based)
|
|
4
|
+
Executes chapter_10_service CLMs to deploy servers.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from clm.cross_cutting.config.config_constants import (
|
|
12
|
+
DEFAULT_API_PORT,
|
|
13
|
+
DEFAULT_WS_PORT,
|
|
14
|
+
ENV_API_PORT,
|
|
15
|
+
ENV_API_PORT_LEGACY,
|
|
16
|
+
ENV_WS_PORT,
|
|
17
|
+
ENV_WS_PORT_LEGACY,
|
|
18
|
+
)
|
|
19
|
+
from clm.layer4.runner import CLMRunner
|
|
20
|
+
from dotenv import load_dotenv
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def main():
|
|
24
|
+
# Load environment variables from .env file
|
|
25
|
+
load_dotenv()
|
|
26
|
+
|
|
27
|
+
# Get ports from environment or defaults
|
|
28
|
+
api_port = int(
|
|
29
|
+
os.getenv(ENV_API_PORT, os.getenv(ENV_API_PORT_LEGACY, str(DEFAULT_API_PORT)))
|
|
30
|
+
)
|
|
31
|
+
ws_port = int(
|
|
32
|
+
os.getenv(ENV_WS_PORT, os.getenv(ENV_WS_PORT_LEGACY, str(DEFAULT_WS_PORT)))
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
parser = argparse.ArgumentParser(description="Start MCard Servers via CLM")
|
|
36
|
+
parser.add_argument(
|
|
37
|
+
"--stop", action="store_true", help="Stop servers instead of starting"
|
|
38
|
+
)
|
|
39
|
+
args = parser.parse_args()
|
|
40
|
+
|
|
41
|
+
# Define CLM paths (relative to project root)
|
|
42
|
+
project_root = Path(__file__).parent.absolute()
|
|
43
|
+
|
|
44
|
+
clm_deploy_configs = [
|
|
45
|
+
# HTTP Server
|
|
46
|
+
{
|
|
47
|
+
"file": "system/services/http_server.yaml",
|
|
48
|
+
"context": {"action": "deploy"},
|
|
49
|
+
},
|
|
50
|
+
# WebSocket Server
|
|
51
|
+
{
|
|
52
|
+
"file": "system/services/ws_server.yaml",
|
|
53
|
+
"context": {"action": "deploy"},
|
|
54
|
+
},
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
clm_stop_configs = [
|
|
58
|
+
{
|
|
59
|
+
"file": "system/services/http_server_stop.yaml",
|
|
60
|
+
"context": {"action": "stop"},
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
"file": "system/services/ws_server_stop.yaml",
|
|
64
|
+
"context": {"action": "stop"},
|
|
65
|
+
},
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
configs = clm_stop_configs if args.stop else clm_deploy_configs
|
|
69
|
+
action_name = "Stopping" if args.stop else "Starting"
|
|
70
|
+
|
|
71
|
+
print(f"🚀 {action_name} MCard Polyglot Services...")
|
|
72
|
+
print(f" Configuration: API={api_port}, WS={ws_port}")
|
|
73
|
+
print()
|
|
74
|
+
|
|
75
|
+
runner = CLMRunner()
|
|
76
|
+
|
|
77
|
+
for config in configs:
|
|
78
|
+
clm_path = project_root / config["file"]
|
|
79
|
+
if not clm_path.exists():
|
|
80
|
+
print(f"❌ CLM not found: {config['file']}")
|
|
81
|
+
continue
|
|
82
|
+
|
|
83
|
+
print(f"📄 Executing: {config['file']}")
|
|
84
|
+
try:
|
|
85
|
+
report = runner.run_file(str(clm_path), context=config["context"])
|
|
86
|
+
|
|
87
|
+
result = report.get("result", {})
|
|
88
|
+
success = result.get("success", False)
|
|
89
|
+
status = "✅ SUCCESS" if success else "❌ FAILED"
|
|
90
|
+
|
|
91
|
+
print(f" Status: {status}")
|
|
92
|
+
if not success:
|
|
93
|
+
print(f" Error: {result.get('error')}")
|
|
94
|
+
elif "message" in result:
|
|
95
|
+
print(f" Message: {result['message']}")
|
|
96
|
+
|
|
97
|
+
except Exception as e:
|
|
98
|
+
print(f"❌ Execution failed: {e}")
|
|
99
|
+
|
|
100
|
+
print()
|
|
101
|
+
if not args.stop:
|
|
102
|
+
print("Servers are running in background (daemonized).")
|
|
103
|
+
print("To stop servers, run: python start_servers.py --stop")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
if __name__ == "__main__":
|
|
107
|
+
main()
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Stop Servers Script
|
|
4
|
+
Executing this will stop both the HTTP server and WebSocket server
|
|
5
|
+
by invoking their respective CLM stop configurations.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main():
|
|
13
|
+
print("🛑 Stopping MCard Servers...")
|
|
14
|
+
# Just reuse start_servers.py with --stop flag
|
|
15
|
+
cmd = [sys.executable, "start_servers.py", "--stop"]
|
|
16
|
+
try:
|
|
17
|
+
subprocess.run(cmd, check=True)
|
|
18
|
+
except subprocess.CalledProcessError as e:
|
|
19
|
+
print(f"Error stopping servers: {e}")
|
|
20
|
+
sys.exit(1)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
if __name__ == "__main__":
|
|
24
|
+
main()
|
|
File without changes
|