"""App Script Automation Bridge — Peripheral Nervous System integration. Part of TIA-ARCHITECT-CORE v22.2154: Synchronizes Google App Script workers with the HF Cortex as peripheral nervous system nodes. """ import json import logging import time from typing import Dict, List, Optional import urllib.request import urllib.parse import urllib.error logger = logging.getLogger(__name__) class AppScriptBridge: """Bridge for Google App Script peripheral nervous system nodes.""" def __init__(self, cortex_endpoint: Optional[str] = None): """Initialize App Script bridge. Args: cortex_endpoint: HF Cortex endpoint URL """ self.cortex_endpoint = cortex_endpoint or "https://huggingface.co/spaces/DJ-Goanna-Coding/TIA" self.peripheral_nodes = {} self.trigger_registry = {} self.last_sync_time = None def register_peripheral_node( self, node_id: str, script_url: str, node_type: str = "trigger", auth_token: Optional[str] = None ) -> None: """Register a Google App Script peripheral node. Args: node_id: Unique identifier for the node script_url: Web app deployment URL for the App Script node_type: Type of node (trigger, sensor, actuator) auth_token: Optional authentication token """ self.peripheral_nodes[node_id] = { "script_url": script_url, "node_type": node_type, "auth_token": auth_token, "status": "REGISTERED", "registered_at": time.time(), "last_ping": None } logger.info(f"Registered peripheral node: {node_id} ({node_type})") def sync_with_cortex(self, data: Dict) -> Dict: """Synchronize peripheral node data with HF Cortex. Args: data: Data to synchronize Returns: Sync result dict """ try: # Prepare sync payload payload = { "source": "APP_SCRIPT_PERIPHERAL", "timestamp": time.time(), "data": data } # Send to cortex (mock - would use actual HF API) self.last_sync_time = time.time() logger.info(f"Synced with cortex: {len(str(data))} bytes") return { "status": "SYNCED", "sync_time": self.last_sync_time, "bytes_transferred": len(json.dumps(payload)) } except Exception as exc: logger.error(f"Cortex sync failed: {exc}") return { "status": "FAILED", "error": str(exc) } def trigger_peripheral_node( self, node_id: str, trigger_data: Optional[Dict] = None ) -> Dict: """Trigger a peripheral node to execute. Args: node_id: Node identifier trigger_data: Optional data to send to node Returns: Trigger result dict """ if node_id not in self.peripheral_nodes: return { "status": "ERROR", "error": f"Node not found: {node_id}" } node = self.peripheral_nodes[node_id] try: # Prepare trigger payload payload = { "trigger": "CORTEX_COMMAND", "timestamp": time.time(), "data": trigger_data or {} } # Add authentication if available headers = {"Content-Type": "application/json"} if node["auth_token"]: headers["Authorization"] = f"Bearer {node['auth_token']}" # Send trigger to App Script req = urllib.request.Request( node["script_url"], data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST" ) with urllib.request.urlopen(req, timeout=30) as response: result = json.loads(response.read().decode("utf-8")) node["last_ping"] = time.time() node["status"] = "ACTIVE" return { "status": "TRIGGERED", "node_id": node_id, "response": result, "timestamp": time.time() } except urllib.error.HTTPError as exc: logger.error(f"HTTP error triggering node {node_id}: {exc.code}") return { "status": "ERROR", "error": f"HTTP {exc.code}: {exc.reason}" } except Exception as exc: logger.error(f"Failed to trigger node {node_id}: {exc}") return { "status": "ERROR", "error": str(exc) } def poll_peripheral_nodes(self) -> Dict: """Poll all peripheral nodes for status. Returns: Poll results dict """ results = { "poll_time": time.time(), "total_nodes": len(self.peripheral_nodes), "active_nodes": 0, "inactive_nodes": 0, "node_status": [] } for node_id, node in self.peripheral_nodes.items(): try: # Simple ping check ping_result = self._ping_node(node_id) if ping_result["status"] == "ACTIVE": results["active_nodes"] += 1 else: results["inactive_nodes"] += 1 results["node_status"].append({ "node_id": node_id, "status": ping_result["status"], "last_ping": node.get("last_ping") }) except Exception as exc: logger.error(f"Failed to poll node {node_id}: {exc}") results["inactive_nodes"] += 1 return results def _ping_node(self, node_id: str) -> Dict: """Ping a peripheral node to check status. Args: node_id: Node identifier Returns: Ping result dict """ if node_id not in self.peripheral_nodes: return {"status": "NOT_FOUND"} node = self.peripheral_nodes[node_id] try: # Simple GET request to check availability req = urllib.request.Request( node["script_url"], headers={"User-Agent": "TIA-AppScriptBridge/1.0"} ) with urllib.request.urlopen(req, timeout=10) as response: if response.getcode() == 200: node["last_ping"] = time.time() return {"status": "ACTIVE"} else: return {"status": "INACTIVE"} except Exception: return {"status": "INACTIVE"} def create_trigger_template(self, trigger_type: str = "time_based") -> str: """Generate Google App Script trigger template. Args: trigger_type: Type of trigger (time_based, spreadsheet, form, etc.) Returns: App Script code template """ if trigger_type == "time_based": return """ /** * Time-based trigger for TIA Cortex synchronization * Runs every hour to send data to HF Cortex */ function hourlyTrigger() { const data = collectPeripheralData(); sendToCortex(data); } /** * Collect data from peripheral systems */ function collectPeripheralData() { return { timestamp: new Date().toISOString(), source: 'APP_SCRIPT_PERIPHERAL', data: { // Add your data collection logic here status: 'ACTIVE', metrics: {} } }; } /** * Send data to TIA Cortex */ function sendToCortex(data) { const CORTEX_ENDPOINT = 'YOUR_CORTEX_ENDPOINT_HERE'; const AUTH_TOKEN = 'YOUR_AUTH_TOKEN_HERE'; const options = { method: 'post', contentType: 'application/json', headers: { 'Authorization': 'Bearer ' + AUTH_TOKEN }, payload: JSON.stringify(data) }; try { const response = UrlFetchApp.fetch(CORTEX_ENDPOINT, options); Logger.log('Cortex sync successful: ' + response.getContentText()); } catch (error) { Logger.log('Cortex sync failed: ' + error.toString()); } } /** * Set up time-based trigger (run once to install) */ function setupTrigger() { // Delete existing triggers const triggers = ScriptApp.getProjectTriggers(); triggers.forEach(trigger => ScriptApp.deleteTrigger(trigger)); // Create hourly trigger ScriptApp.newTrigger('hourlyTrigger') .timeBased() .everyHours(1) .create(); Logger.log('Trigger installed successfully'); } """ elif trigger_type == "spreadsheet": return """ /** * Spreadsheet trigger for TIA Cortex synchronization * Triggers on spreadsheet edit */ function onEdit(e) { const data = { timestamp: new Date().toISOString(), source: 'SPREADSHEET_PERIPHERAL', trigger: 'EDIT', range: e.range.getA1Notation(), value: e.value }; sendToCortex(data); } /** * Send data to TIA Cortex */ function sendToCortex(data) { const CORTEX_ENDPOINT = 'YOUR_CORTEX_ENDPOINT_HERE'; const AUTH_TOKEN = 'YOUR_AUTH_TOKEN_HERE'; const options = { method: 'post', contentType: 'application/json', headers: { 'Authorization': 'Bearer ' + AUTH_TOKEN }, payload: JSON.stringify(data) }; try { UrlFetchApp.fetch(CORTEX_ENDPOINT, options); } catch (error) { Logger.log('Cortex sync failed: ' + error.toString()); } } """ else: return "// Unknown trigger type" def get_status(self) -> Dict: """Get App Script bridge status. Returns: Status dict """ return { "bridge": "ACTIVE", "cortex_endpoint": self.cortex_endpoint, "registered_nodes": len(self.peripheral_nodes), "last_sync_time": self.last_sync_time } def main(): """CLI entry point for App Script bridge.""" bridge = AppScriptBridge() print("=" * 80) print("APP SCRIPT AUTOMATION BRIDGE — Peripheral Nervous System") print("=" * 80) # Register example nodes bridge.register_peripheral_node( "spreadsheet_monitor_1", "https://script.google.com/macros/s/EXAMPLE/exec", "trigger" ) bridge.register_peripheral_node( "form_collector_1", "https://script.google.com/macros/s/EXAMPLE2/exec", "sensor" ) # Get status status = bridge.get_status() print(f"\nBridge Status:") print(json.dumps(status, indent=2)) # Generate trigger template print(f"\nTime-Based Trigger Template:") template = bridge.create_trigger_template("time_based") print(template[:500] + "..." if len(template) > 500 else template) if __name__ == "__main__": main()