@stdiobus/workers-registry 1.3.11 → 1.3.14

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.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ "use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var import_readline=__toESM(require("readline"),1);var shuttingDown=false;var rl=import_readline.default.createInterface({input:process.stdin,output:process.stdout,terminal:false});function processMessage(line){if(shuttingDown){return}try{const msg=JSON.parse(line);if(msg.id!==void 0&&msg.method!==void 0){const response={jsonrpc:"2.0",id:msg.id,result:{echo:msg.params||{},method:msg.method,timestamp:new Date().toISOString()}};if(msg.sessionId){response.sessionId=msg.sessionId}console.log(JSON.stringify(response))}else if(msg.method!==void 0&&msg.id===void 0){if(msg.sessionId){const notification={jsonrpc:"2.0",method:"echo.notification",params:{original:msg.method,timestamp:new Date().toISOString()},sessionId:msg.sessionId};console.log(JSON.stringify(notification))}}}catch(err){console.error(`[echo-worker] Error parsing message: ${err.message}`);console.error(`[echo-worker] Raw input: ${line.substring(0,100)}...`)}}function handleShutdown(){if(shuttingDown){return}shuttingDown=true;console.error("[echo-worker] Received SIGTERM, shutting down gracefully...");rl.close()}process.on("SIGTERM",handleShutdown);process.on("SIGINT",handleShutdown);rl.on("line",processMessage);rl.on("close",()=>{console.error("[echo-worker] stdin closed, exiting");process.exit(0)});process.on("uncaughtException",err=>{console.error(`[echo-worker] Uncaught exception: ${err.message}`);console.error(err.stack);process.exit(1)});process.on("unhandledRejection",(reason,promise)=>{console.error("[echo-worker] Unhandled promise rejection:",reason);process.exit(1)});console.error("[echo-worker] Started, waiting for NDJSON messages on stdin...");
3
+ //# sourceMappingURL=echo-worker.cjs.map
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../../../workers-registry/echo-worker/echo-worker.js"],
4
4
  "sourcesContent": ["#!/usr/bin/env node\n\n/*\n * Apache License 2.0\n * Copyright (c) 2025\u2013present Raman Marozau, Target Insight Function.\n * Contact: raman@worktif.com\n *\n * This file is part of the stdio bus protocol reference implementation:\n * stdio_bus_kernel_workers (target: <target_stdio_bus_kernel_workers>).\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @file echo-worker/echo-worker.js\n * @brief Simple NDJSON echo worker for testing stdio Bus kernel\n *\n * This is a minimal reference implementation demonstrating the worker-to-daemon\n * contract for Agent Transport OS (stdio Bus kernel). It serves as both a functional test\n * worker and documentation of the NDJSON communication protocol.\n *\n * ## NDJSON Communication Contract\n *\n * stdio Bus kernel workers communicate with the daemon via stdin/stdout using NDJSON\n * (Newline-Delimited JSON) format:\n *\n * - **Input (stdin)**: The daemon sends JSON-RPC messages, one per line.\n * Each message is a complete JSON object terminated by a newline (\\n).\n *\n * - **Output (stdout)**: The worker writes JSON-RPC responses, one per line.\n * Each response MUST be a complete JSON object terminated by a newline.\n * The worker MUST NOT write anything else to stdout (no logs, no debug output).\n *\n * - **Errors (stderr)**: All logging, errors, and debug output MUST go to stderr.\n * The daemon does not process stderr; it's for operator visibility only.\n *\n * ## Message Types\n *\n * 1. **Requests**: Have both `id` and `method` fields. MUST receive a response\n * with the same `id`.\n *\n * 2. **Notifications**: Have `method` but no `id`. MUST NOT receive a response.\n * Workers may optionally send notifications back to the client.\n *\n * 3. **Responses**: Have `id` and either `result` or `error`. Sent by workers\n * in reply to requests.\n *\n * ## Session Affinity\n *\n * Messages may include a `sessionId` field for session-based routing:\n * - The daemon routes all messages with the same `sessionId` to the same worker\n * - Workers MUST preserve `sessionId` in responses when present in requests\n * - This enables stateful conversations within a session\n *\n * ## Graceful Shutdown\n *\n * Workers MUST handle SIGTERM for graceful shutdown:\n * - Stop accepting new messages\n * - Complete any in-flight processing\n * - Exit with code 0\n *\n * The daemon sends SIGTERM during shutdown or when restarting workers.\n *\n * @example\n * // Start the echo worker\n * node workers-registry/echo-worker/echo-worker.js\n *\n * // Send a request (from another terminal or via stdio Bus kernel)\n * echo '{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"method\":\"test\",\"params\":{\"foo\":\"bar\"}}' | node workers-registry/echo-worker/echo-worker.js\n *\n * // Expected response:\n * // {\"jsonrpc\":\"2.0\",\"id\":\"1\",\"result\":{\"echo\":{\"foo\":\"bar\"},\"method\":\"test\",\"timestamp\":\"...\"}}\n *\n * @see spec/agent-transport-os.md for the full normative specification\n * @see docs-internal/integration-for-platforms.md for worker implementation guidance\n */\n\nimport readline from 'readline';\n\n/**\n * Flag to track shutdown state.\n * When true, the worker will not process new messages.\n */\nlet shuttingDown = false;\n\n/**\n * Create readline interface for NDJSON processing.\n *\n * The readline module handles line-based input efficiently, buffering\n * partial lines until a complete newline-terminated message is received.\n * This is essential for NDJSON processing where messages may arrive\n * in chunks over the pipe.\n */\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\n/**\n * Process a single JSON-RPC message from stdin.\n *\n * This function implements the core worker contract:\n * 1. Parse the incoming JSON message\n * 2. Determine message type (request vs notification)\n * 3. Generate appropriate response\n * 4. Preserve sessionId for session affinity\n *\n * @param {string} line - Raw JSON line from stdin (without trailing newline)\n *\n * ## Request Handling\n *\n * For requests (messages with both `id` and `method`):\n * - Generate a response with the same `id`\n * - Include `result` object with echoed data\n * - Preserve `sessionId` if present\n *\n * ## Notification Handling\n *\n * For notifications (messages with `method` but no `id`):\n * - Do NOT send a response (per JSON-RPC 2.0 spec)\n * - Optionally send a notification back if sessionId is present\n *\n * ## Error Handling\n *\n * For malformed JSON:\n * - Log error to stderr (never stdout)\n * - Continue processing subsequent messages\n * - Do NOT crash the worker\n */\nfunction processMessage(line) {\n // Skip processing if we're shutting down\n if (shuttingDown) {\n return;\n }\n\n try {\n const msg = JSON.parse(line);\n\n // Request: has both id and method - MUST send response\n if (msg.id !== undefined && msg.method !== undefined) {\n const response = {\n jsonrpc: '2.0',\n id: msg.id,\n result: {\n echo: msg.params || {},\n method: msg.method,\n timestamp: new Date().toISOString()\n }\n };\n\n // Session affinity: preserve sessionId in response\n // This is REQUIRED for session-based routing to work correctly.\n // The daemon uses sessionId to route responses back to the\n // correct client connection.\n if (msg.sessionId) {\n response.sessionId = msg.sessionId;\n }\n\n // Write response as NDJSON (JSON + newline)\n // console.log automatically adds the newline\n console.log(JSON.stringify(response));\n }\n // Notification: has method but no id - MUST NOT send response\n else if (msg.method !== undefined && msg.id === undefined) {\n // Per JSON-RPC 2.0: notifications don't receive responses.\n // However, workers may send their own notifications to clients.\n // If sessionId is present, we demonstrate sending a notification back.\n if (msg.sessionId) {\n const notification = {\n jsonrpc: '2.0',\n method: 'echo.notification',\n params: {\n original: msg.method,\n timestamp: new Date().toISOString()\n },\n sessionId: msg.sessionId\n };\n console.log(JSON.stringify(notification));\n }\n }\n // Response or other message type: ignore\n // Workers typically don't receive responses, but if they do,\n // they should be silently ignored.\n } catch (err) {\n // Log parse errors to stderr (NEVER stdout)\n // stdout is reserved exclusively for NDJSON protocol messages\n console.error(`[echo-worker] Error parsing message: ${err.message}`);\n console.error(`[echo-worker] Raw input: ${line.substring(0, 100)}...`);\n }\n}\n\n/**\n * Handle graceful shutdown on SIGTERM.\n *\n * The stdio Bus kernel daemon sends SIGTERM when:\n * - The daemon itself is shutting down\n * - The worker needs to be restarted (due to crash or configuration change)\n * - The worker pool is being scaled down\n *\n * Proper SIGTERM handling ensures:\n * - No message loss (in-flight messages complete)\n * - Clean process exit (exit code 0)\n * - Resource cleanup (file handles, connections)\n *\n * Workers that don't handle SIGTERM will receive SIGKILL after the\n * daemon's configured drain timeout (default: 30 seconds).\n */\nfunction handleShutdown() {\n if (shuttingDown) {\n return; // Already shutting down\n }\n\n shuttingDown = true;\n console.error('[echo-worker] Received SIGTERM, shutting down gracefully...');\n\n // Close the readline interface to stop accepting new input\n rl.close();\n}\n\n// Register SIGTERM handler for graceful shutdown\nprocess.on('SIGTERM', handleShutdown);\n\n// Also handle SIGINT (Ctrl+C) for development convenience\nprocess.on('SIGINT', handleShutdown);\n\n// Process each line from stdin as an NDJSON message\nrl.on('line', processMessage);\n\n// Handle stdin close (daemon closed the pipe)\nrl.on('close', () => {\n console.error('[echo-worker] stdin closed, exiting');\n process.exit(0);\n});\n\n// Handle uncaught exceptions\n// Log to stderr and exit with error code\n// The daemon will restart the worker based on restart policy\nprocess.on('uncaughtException', (err) => {\n console.error(`[echo-worker] Uncaught exception: ${err.message}`);\n console.error(err.stack);\n process.exit(1);\n});\n\n// Handle unhandled promise rejections\nprocess.on('unhandledRejection', (reason, promise) => {\n console.error('[echo-worker] Unhandled promise rejection:', reason);\n process.exit(1);\n});\n\n// Log startup to stderr (for debugging)\nconsole.error('[echo-worker] Started, waiting for NDJSON messages on stdin...');\n"],
5
- "mappings": ";AAyFA,OAAO,aAAc,WAMrB,IAAI,aAAe,MAUnB,IAAM,GAAK,SAAS,gBAAgB,CAClC,MAAO,QAAQ,MACf,OAAQ,QAAQ,OAChB,SAAU,KACZ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AM,6DAA6D,EAG3E,GAAG,MAAM,CACX,CAGA,QAAQ,GAAG,UAAW,cAAc,EAGpC,QAAQ,GAAG,SAAU,cAAc,EAGnC,GAAG,GAAG,OAAQ,cAAc,EAG5B,GAAG,GAAG,QAAS,IAAM,CACnB,QAAQ,MAAM,qCAAqC,EACnD,QAAQ,KAAK,CAAC,CAChB,CAAC,EAKD,QAAQ,GAAG,oBAAsB,KAAQ,CACvC,QAAQ,MAAM,qCAAqC,IAAI,OAAO,EAAE,EAChE,QAAQ,MAAM,IAAI,KAAK,EACvB,QAAQ,KAAK,CAAC,CAChB,CAAC,EAGD,QAAQ,GAAG,qBAAsB,CAAC,OAAQ,UAAY,CACpD,QAAQ,MAAM,6CAA8C,MAAM,EAClE,QAAQ,KAAK,CAAC,CAChB,CAAC,EAGD,QAAQ,MAAM,gEAAgE",
6
+ "names": ["readline"]
7
7
  }
@@ -1,3 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import readline from"readline";var shuttingDown=false;var rl=readline.createInterface({input:process.stdin,output:process.stdout,terminal:false});function processMessage(line){if(shuttingDown){return}try{const msg=JSON.parse(line);if(msg.id!==void 0&&msg.method!==void 0){const response={jsonrpc:"2.0",id:msg.id,result:{echo:msg.params||{},method:msg.method,timestamp:new Date().toISOString()}};if(msg.sessionId){response.sessionId=msg.sessionId}console.log(JSON.stringify(response))}else if(msg.method!==void 0&&msg.id===void 0){if(msg.sessionId){const notification={jsonrpc:"2.0",method:"echo.notification",params:{original:msg.method,timestamp:new Date().toISOString()},sessionId:msg.sessionId};console.log(JSON.stringify(notification))}}}catch(err){console.error(`[echo-worker] Error parsing message: ${err.message}`);console.error(`[echo-worker] Raw input: ${line.substring(0,100)}...`)}}function handleShutdown(){if(shuttingDown){return}shuttingDown=true;console.error("[echo-worker] Received SIGTERM, shutting down gracefully...");rl.close()}process.on("SIGTERM",handleShutdown);process.on("SIGINT",handleShutdown);rl.on("line",processMessage);rl.on("close",()=>{console.error("[echo-worker] stdin closed, exiting");process.exit(0)});process.on("uncaughtException",err=>{console.error(`[echo-worker] Uncaught exception: ${err.message}`);console.error(err.stack);process.exit(1)});process.on("unhandledRejection",(reason,promise)=>{console.error("[echo-worker] Unhandled promise rejection:",reason);process.exit(1)});console.error("[echo-worker] Started, waiting for NDJSON messages on stdin...");
3
- //# sourceMappingURL=echo-worker.js.map
2
+ // ESM wrapper for CommonJS bundle
3
+ import { createRequire } from 'module';
4
+ import { fileURLToPath } from 'url';
5
+ import { dirname, join } from 'path';
6
+
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = dirname(__filename);
9
+ const require = createRequire(import.meta.url);
10
+
11
+ // Import the CommonJS bundle
12
+ require('./echo-worker.cjs');