@convilyn/sdk-author 0.8.0 → 0.9.0

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.
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts","../src/errors.ts","../src/types.ts","../src/cli/print.ts","../src/cli/scaffold.ts","../src/cli/load-server.ts","../src/workflow.ts","../src/cli/load-workflow.ts","../src/auth.ts","../src/config.ts","../src/client.ts","../src/jsonrpc.ts","../src/http-runtime.ts","../src/tool-server.ts","../src/compliance.ts","../src/cli/commands.ts","../src/cli/program.ts","../src/cli.ts"],"names":["readdir","path","resolve","mkdir","writeFile","join","pathToFileURL","readFile","extname","createHmac","timingSafeEqual","createServer","isRecord","stat","fail","Command"],"mappings":";;;;;;;;;;;AACO,IAAM,OAAA,GAAU,OAAA;;;ACkBvB,IAAM,2BAAA,mBAA8B,MAAA,CAAO,GAAA,CAAI,0CAA0C,CAAA;AAGlF,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA;AAAA,EAE7C,CAAU,2BAA2B,IAAI,IAAA;AAAA,EAEzC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF,CAAA;AA6BO,IAAM,qBAAA,GAAN,cAAoC,mBAAA,CAAoB;AAAA,EACpD,MAAA;AAAA,EAET,WAAA,CAAY,QAAgC,OAAA,EAAiB;AAC3D,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AACF,CAAA;AAQO,IAAM,oBAAA,GAAN,cAAmC,mBAAA,CAAoB;AAAA,EAC5D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,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AM,UAAU,MAAM,OAAA,CAAQ,EAAE,SAAA,EAAW,GAAG,MAAM,CAAA;AACpD,MAAA,IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AACxB,QAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,mBAAA,EAAsB,SAAS,CAAA,yBAAA,CAA2B,CAAA;AACtE,QAAA;AAAA,MACF;AACA,MAAA,KAAA,MAAW,SAAS,OAAA,EAAS;AAC3B,QAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,CAAA,EAAI,KAAA,CAAM,SAAS,CAAA,EAAA,EAAK,MAAM,KAAK,CAAA,CAAA,EAAI,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,MACpE;AAAA,IACF,SAAS,GAAA,EAAK;AACZ,MAAAA,KAAAA,CAAK,SAAS,GAAG,CAAA;AAAA,IACnB;AAAA,EACF,CAAC,CAAA;AAEH,EAAA,OAAO,OAAA;AACT;;;AC3LA,YAAA,GACG,UAAA,CAAW,OAAA,CAAQ,IAAI,CAAA,CACvB,KAAA,CAAM,CAAC,GAAA,KAAiB;AACvB,EAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,OAAA,EAAW,GAAA,CAAc,OAAO;AAAA,CAAI,CAAA;AACzD,EAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AACrB,CAAC,CAAA","file":"cli.cjs","sourcesContent":["/** The SDK release version (independent of the manifest schema version). */\nexport const VERSION = '0.8.0'\n\n/**\n * The schema version stamped into a compiled manifest's `sdk_version` field —\n * kept in lockstep with the Python / Go author SDKs' manifest format.\n */\nexport const MANIFEST_SDK_VERSION = '1.0.0'\n","/**\n * Typed errors raised by the Author SDK — a faithful port of the Python / Go\n * author SDKs.\n *\n * ConvilynAuthorError base; everything the SDK throws\n * ├── InvalidSignatureError inbound HMAC verification failed\n * ├── ConvilynStartupError server cannot safely start (fail-closed gate)\n * └── ConfirmationInvalidError confirmation-handshake token rejected\n */\n\n/**\n * Well-known brand for {@link ConvilynAuthorError}. `Symbol.for` resolves to the\n * *same* symbol from the global registry regardless of which module instance\n * (ESM vs. CJS) created it, so {@link isConvilynAuthorError} stays reliable even\n * when a process ends up loading both entry points of this package (a classic\n * Node.js dual-package hazard where `instanceof` across the two module graphs\n * can false-negative). Prefer the guard function over `instanceof` unless you\n * can guarantee a single module graph.\n */\nconst CONVILYN_AUTHOR_ERROR_BRAND = Symbol.for('@convilyn/sdk-author.ConvilynAuthorError')\n\n/** Base class for every error the Author SDK throws. */\nexport class ConvilynAuthorError extends Error {\n /** @internal brand marker — see {@link isConvilynAuthorError} */\n readonly [CONVILYN_AUTHOR_ERROR_BRAND] = true\n\n constructor(message: string) {\n super(message)\n this.name = 'ConvilynAuthorError'\n }\n}\n\n/**\n * Reliable `err instanceof ConvilynAuthorError` replacement across module\n * graphs. Use this (not `instanceof`) when the error may have crossed an\n * ESM/CJS boundary — e.g. a dependency `require()`s this package while your\n * own code `import`s it.\n */\nexport function isConvilynAuthorError(err: unknown): err is ConvilynAuthorError {\n return (\n typeof err === 'object' &&\n err !== null &&\n (err as Record<PropertyKey, unknown>)[CONVILYN_AUTHOR_ERROR_BRAND] === true\n )\n}\n\n/** Stable machine-readable reason for an {@link InvalidSignatureError}. */\nexport type InvalidSignatureReason =\n | 'missing_secret'\n | 'missing_header'\n | 'invalid_timestamp'\n | 'timestamp_out_of_range'\n | 'signature_mismatch'\n\n/**\n * Raised when an inbound HMAC signature fails verification. `reason` is a stable\n * machine-readable code; `message` is human-readable and safe to log. Reasons\n * are intentionally coarse to avoid leaking signing details to attackers.\n */\nexport class InvalidSignatureError extends ConvilynAuthorError {\n readonly reason: InvalidSignatureReason\n\n constructor(reason: InvalidSignatureReason, message: string) {\n super(message)\n this.name = 'InvalidSignatureError'\n this.reason = reason\n }\n}\n\n/**\n * Raised when the server cannot safely start — e.g. `serve()` without\n * `CONVILYN_HMAC_SECRET` and without the explicit insecure-local-dev opt-in.\n * Port of the Python / Go `ConvilynStartupError` (fail-closed startup\n * contract).\n */\nexport class ConvilynStartupError extends ConvilynAuthorError {\n constructor(message: string) {\n super(message)\n this.name = 'ConvilynStartupError'\n }\n}\n\n/**\n * Raised when a platform API call (via {@link ConvilynClient}) returns a non-2xx\n * response. `status` is the HTTP status; `body` is the parsed JSON (or text) the\n * server returned.\n */\nexport class ConvilynApiError extends ConvilynAuthorError {\n readonly status: number\n readonly body: unknown\n\n constructor(status: number, message: string, body: unknown) {\n super(message)\n this.name = 'ConvilynApiError'\n this.status = status\n this.body = body\n }\n}\n\n/** Stable machine-readable reason for a {@link ConfirmationInvalidError}. */\nexport type ConfirmationInvalidReason =\n 'malformed' | 'expired' | 'digest_mismatch' | 'signature_mismatch'\n\n/**\n * Raised when a confirmation-handshake token fails verification. `reason` is a\n * stable machine-readable code (maps to the framework's `CONFIRMATION_INVALID`).\n */\nexport class ConfirmationInvalidError extends ConvilynAuthorError {\n readonly reason: ConfirmationInvalidReason\n\n constructor(reason: ConfirmationInvalidReason, message: string) {\n super(message)\n this.name = 'ConfirmationInvalidError'\n this.reason = reason\n }\n}\n","/**\n * Core value types shared across the Author SDK — tool results, error details,\n * data references, and the manifest schema rows. Mirrors the Go SDK's `types.go`\n * and the Python `types.py`. Domain fields are camelCase; the snake_case wire\n * mapping lives in `manifest.ts` (and, later, the JSON-RPC runtime).\n */\n\n/** Reference to data stored in the ToolDataStore (the LLM sees only the summary). */\nexport interface ToolDataRef {\n refId: string\n summary: string\n}\n\n/** Structured error detail for a failed tool execution. */\nexport interface ToolError {\n code: string\n message: string\n details?: Record<string, unknown>\n}\n\n/** Result returned from a tool execution. Build via {@link ToolResult.ok} / `.fail`. */\nexport interface ToolResult {\n success: boolean\n data?: Record<string, unknown>\n error?: ToolError\n executionTimeMs?: number\n /**\n * Optional LLM-facing one-line summary. When set it becomes the wire\n * envelope's required `summary`; otherwise the JSON-RPC runtime derives one.\n * (Added in A3; omitting it preserves the A1 `ok` / `fail` shapes exactly.)\n */\n summary?: string\n}\n\n/** Constructors for {@link ToolResult} (mirrors Python `ToolResult.ok` / `.fail`). */\nexport const ToolResult = {\n ok(data: Record<string, unknown>, summary?: string): ToolResult {\n return summary !== undefined ? { success: true, data, summary } : { success: true, data }\n },\n fail(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n summary?: string\n ): ToolResult {\n const error: ToolError = details ? { code, message, details } : { code, message }\n return summary !== undefined ? { success: false, error, summary } : { success: false, error }\n },\n}\n\n/** Manifest schema for a single tool. */\nexport interface ToolSpec {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n idempotent: boolean\n outputSchema?: Record<string, unknown>\n}\n\n/** Manifest schema for the server section. */\nexport interface ServerSpec {\n name: string\n version: string\n description: string\n mcpServerName?: string\n}\n\n/** One line of a compliance report. */\nexport interface ComplianceResult {\n passed: boolean\n checkName: string\n message: string\n details?: Record<string, unknown>\n}\n\n/** Full report from a local compliance run. */\nexport interface ComplianceReport {\n results: ComplianceResult[]\n}\n\n/** True when every check in the report passed. */\nexport function allChecksPassed(report: ComplianceReport): boolean {\n return report.results.every((result) => result.passed)\n}\n\n/** Just the failing checks of a report. */\nexport function failedChecks(report: ComplianceReport): ComplianceResult[] {\n return report.results.filter((result) => !result.passed)\n}\n","/**\n * A tiny output seam for the CLI so command cores stay testable (inject a\n * capturing {@link Printer} in tests) and the package keeps no raw `console.log`.\n */\n\nexport interface Printer {\n out(line: string): void\n err(line: string): void\n}\n\n/** Default {@link Printer} writing to the real stdout / stderr. */\nexport const consolePrinter: Printer = {\n out: (line) => {\n process.stdout.write(`${line}\\n`)\n },\n err: (line) => {\n process.stderr.write(`${line}\\n`)\n },\n}\n","/**\n * `convilyn-author init` — scaffold a new tool-server project. Pure local file\n * writes; no platform calls. Refuses to write into a non-empty directory.\n *\n * The scaffold authors in TypeScript and builds to `dist/server.js`; the\n * generated `synth` / `dev` / `test` scripts point the CLI at that built module\n * (the CLI loads JS, not TS — no TS runtime is pulled in).\n */\n\nimport { mkdir, readdir, writeFile } from 'node:fs/promises'\nimport { resolve, join } from 'node:path'\nimport { VERSION } from '../version'\n\nconst NAME_RE = /^[a-zA-Z0-9_-]+$/\n\n/** Validate a project name (alphanumeric, hyphen, underscore). */\nexport function isValidProjectName(name: string): boolean {\n return NAME_RE.test(name)\n}\n\nfunction serverTs(name: string): string {\n return `import { defineTool, ToolServer, ToolResult } from '@convilyn/sdk-author'\nimport { z } from 'zod'\n\nconst echo = defineTool({\n name: 'echo',\n description: 'Echo the input text back.',\n input: z.object({ text: z.string().min(1) }),\n idempotent: true,\n handler: (args) => ToolResult.ok({ echoed: args.text }, \\`Echoed \\${args.text.length} chars\\`),\n})\n\nexport const server = new ToolServer(\n { name: '${name}', version: '0.1.0', description: 'A Convilyn tool server.' },\n { tools: [echo] }\n)\n\nexport default server\n`\n}\n\nfunction packageJson(name: string): string {\n return `${JSON.stringify(\n {\n name,\n version: '0.1.0',\n private: true,\n type: 'module',\n scripts: {\n build: 'tsc',\n synth: 'convilyn-author synth --file dist/server.js',\n dev: 'convilyn-author dev --file dist/server.js',\n test: 'convilyn-author test --file dist/server.js',\n },\n dependencies: {\n '@convilyn/sdk-author': `^${VERSION}`,\n zod: '^3.23.0',\n },\n devDependencies: {\n typescript: '^5.7.2',\n },\n },\n null,\n 2\n )}\\n`\n}\n\nconst TSCONFIG = `${JSON.stringify(\n {\n compilerOptions: {\n target: 'ES2022',\n module: 'NodeNext',\n moduleResolution: 'NodeNext',\n outDir: 'dist',\n strict: true,\n skipLibCheck: true,\n declaration: false,\n },\n include: ['server.ts'],\n },\n null,\n 2\n)}\\n`\n\nconst GITIGNORE = `node_modules/\ndist/\nconvilyn.manifest.json\n.env\n`\n\nconst ENV_EXAMPLE = `# Inbound HMAC secret (enables POST /mcp signature verification)\nCONVILYN_HMAC_SECRET=\n# Local dev server port\nCONVILYN_PORT=8080\n# Platform API (used by push/deploy once those land)\nCONVILYN_PLATFORM_URL=https://api.convilyn.corenovus.com\nCONVILYN_API_KEY=\n`\n\nfunction readme(name: string): string {\n return `# ${name}\n\nA Convilyn tool server, scaffolded by \\`convilyn-author init\\`.\n\n## Develop\n\n\\`\\`\\`bash\nnpm install\nnpm run build # server.ts -> dist/server.js\nnpx convilyn-author dev # run the JSON-RPC /mcp server locally\nnpx convilyn-author synth # write convilyn.manifest.json\nnpx convilyn-author test # local compliance checks\n\\`\\`\\`\n\nEdit \\`server.ts\\` to add tools with \\`defineTool\\`.\n`\n}\n\n/** The files {@link scaffoldProject} writes, keyed by their relative path. */\nexport function projectFiles(name: string): Record<string, string> {\n return {\n 'server.ts': serverTs(name),\n 'package.json': packageJson(name),\n 'tsconfig.json': TSCONFIG,\n '.gitignore': GITIGNORE,\n '.env.example': ENV_EXAMPLE,\n 'README.md': readme(name),\n }\n}\n\nasync function isNonEmptyDir(dir: string): Promise<boolean> {\n try {\n const entries = await readdir(dir)\n return entries.length > 0\n } catch {\n return false // does not exist yet\n }\n}\n\n/** Result of {@link scaffoldProject}. */\nexport interface ScaffoldResult {\n path: string\n files: string[]\n}\n\n/**\n * Scaffold a project named `name` into `dir` (default `./<name>`). Throws on an\n * invalid name or a non-empty target directory.\n */\nexport async function scaffoldProject(options: {\n name: string\n dir?: string\n}): Promise<ScaffoldResult> {\n const { name } = options\n if (!isValidProjectName(name)) {\n throw new Error(\n `Invalid project name \"${name}\": use letters, digits, hyphens, underscores only.`\n )\n }\n const path = resolve(options.dir ?? `./${name}`)\n if (await isNonEmptyDir(path)) {\n throw new Error(`Target directory \"${path}\" is not empty — refusing to overwrite.`)\n }\n await mkdir(path, { recursive: true })\n const files = projectFiles(name)\n const written: string[] = []\n for (const [rel, content] of Object.entries(files)) {\n await writeFile(join(path, rel), content, 'utf8')\n written.push(rel)\n }\n return { path, files: written.sort() }\n}\n","/**\n * Locate and load the author's {@link ToolServer} from a built JS module. Used by\n * the `synth` / `dev` / `test` commands.\n *\n * The export is **duck-typed**, never `instanceof`-checked: the CLI binary bundles\n * its own copy of `ToolServer`, while the author's instance comes from *their*\n * installed `@convilyn/sdk-author` — two distinct class identities. We therefore\n * recognise a server by the shape the commands actually use (`server` metadata +\n * `manifest()` + `dispatch()`).\n *\n * The author points at a built `.js`/`.mjs`/`.cjs` module (default `server.js`)\n * exporting the server as the default export or a named `server` export.\n */\n\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { ToolServer } from '../tool-server'\n\nfunction isToolServerLike(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return false\n }\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.manifest === 'function' &&\n typeof candidate.dispatch === 'function' &&\n typeof candidate.server === 'object' &&\n candidate.server !== null\n )\n}\n\nfunction pickServer(mod: Record<string, unknown>): unknown {\n if (isToolServerLike(mod.default)) {\n return mod.default\n }\n if (isToolServerLike(mod.server)) {\n return mod.server\n }\n for (const value of Object.values(mod)) {\n if (isToolServerLike(value)) {\n return value\n }\n }\n return undefined\n}\n\n/**\n * Import `file` and return the {@link ToolServer} it exports. Throws a\n * descriptive error when the module cannot be imported or exports no server.\n */\nexport async function loadToolServer(file: string): Promise<ToolServer> {\n const absolute = resolve(file)\n let mod: Record<string, unknown>\n try {\n mod = (await import(pathToFileURL(absolute).href)) as Record<string, unknown>\n } catch (err) {\n throw new Error(\n `Could not import server module \"${file}\": ${(err as Error).message}. ` +\n `Point --file at a built .js module (e.g. \"npm run build\" then --file dist/server.js).`\n )\n }\n const server = pickServer(mod)\n if (server === undefined) {\n throw new Error(\n `No ToolServer found in \"${file}\". Export it as the default export or as a named \"server\" export.`\n )\n }\n return server as ToolServer\n}\n","/**\n * `WorkflowSpec` — an immutable fluent builder for the portable workflow\n * authoring artifact the platform consumes.\n *\n * Two wire shapes, one method each (single responsibility per contract):\n *\n * - `compile()` emits the snake_case {@link WorkflowBlueprint} — the PUBLIC\n * publish artifact the Developer Portal's `submit_workflow` accepts, in\n * cross-SDK parity with the Python author SDK's `compile()`.\n * - `toExportPayload()` emits the camelCase {@link ExportPayload} — the\n * user_workflows authoring/canvas contract\n * (`docs/contracts/user_workflows/user_workflows_openapi.yaml`), which\n * carries UI-only metadata (positions, notes, canvasLayout) the blueprint\n * deliberately omits.\n *\n * Every `with*` / `add*` / `use*` method returns a NEW `WorkflowSpec` (the\n * receiver is never mutated), matching the project's immutability rule. Contract\n * constraints are enforced client-side so a bad spec fails fast with a clear\n * {@link ConvilynAuthorError} instead of a server 422.\n */\n\nimport { readFile, writeFile } from 'node:fs/promises'\nimport { ConvilynAuthorError } from './errors'\n\n/** Lifecycle visibility of a persisted workflow (set via the platform, not here). */\nexport type Visibility = 'private' | 'public' | 'archived'\n\n/** Provenance of a workflow's fork source. */\nexport type SourceType = 'curated' | 'user' | 'blank'\n\n/** 2D position on the Builder canvas — pure UI metadata, ignored by the agent. */\nexport interface Position {\n x: number\n y: number\n}\n\n/**\n * One tool the agent may call. `toolName` is the\n * `\"server-name:tool_name\"` form (e.g. `\"doc-parser-mcp:extract_text\"`).\n * `position` is UI-only and does not affect execution order.\n */\nexport interface ToolPaletteItem {\n toolName: string\n position: Position\n note?: string\n}\n\n/** Optional Builder-only canvas state. Ignored by the compiler and the agent. */\nexport interface CanvasLayout {\n edges?: Array<{ from: string; to: string }>\n viewport?: { zoom?: number; pan?: Position }\n}\n\n/** The camelCase user_workflows authoring/canvas artifact (`ExportPayload`). */\nexport interface ExportPayload {\n schemaVersion: string\n name: string\n description?: string\n systemPrompt: string\n toolPalette: ToolPaletteItem[]\n canvasLayout?: CanvasLayout\n tags: string[]\n}\n\n/**\n * Public blueprint schema version. The platform's translator is keyed on\n * this so its internal workflow contract can evolve without breaking an\n * already-published author SDK. Mirrors the Python SDK's `PUBLIC_SCHEMA_VERSION`.\n */\nexport const PUBLIC_SCHEMA_VERSION = '1'\n\n/** Public agent-mode knobs an author may set on a blueprint. */\nexport interface BlueprintAgentConfig {\n system_prompt?: string\n max_iterations?: number\n temperature?: number\n}\n\n/** MCP server and tool configuration (\"server:tool\" refs). */\nexport interface BlueprintMcpConfig {\n mcp_servers: string[]\n tools: string[]\n}\n\n/**\n * The compiled PUBLIC publish artifact — snake_case, in cross-SDK parity with\n * the Python author SDK's `WorkflowBlueprint`. This is what the Developer\n * Portal's `submit_workflow` accepts; platform-internal fields (category,\n * platform, prompt-template ids) are injected by the server-side translator.\n */\nexport interface WorkflowBlueprint {\n public_schema_version: string\n spec_id: string\n version: string\n name: string\n description?: string\n keywords?: string[]\n agent_config?: BlueprintAgentConfig\n mcp_config?: BlueprintMcpConfig\n}\n\n/** Cross-SDK alias — the Python SDK names its `compile()` output the same way. */\nexport type CompiledWorkflowSpec = WorkflowBlueprint\n\n// ── contract constraints (user_workflows_openapi.yaml) ───────────────────────\nconst DEFAULT_SCHEMA_VERSION = '1.0'\nconst MAX_NAME = 80\nconst MAX_DESCRIPTION = 500\nconst MAX_SYSTEM_PROMPT = 8000\nconst MAX_TOOLS = 20\nconst MAX_TOOL_NAME = 128\nconst MAX_NOTE = 200\nconst MAX_TAGS = 8\nconst MAX_TAG_LEN = 24\nconst ORIGIN: Position = { x: 0, y: 0 }\n/** Invariant I3: the pause-for-input tool is never allowed in a workflow palette. */\nconst FORBIDDEN_TOOL = 'request_user_input'\n\nconst DEFAULT_VERSION = '1.0.0'\nconst MAX_SPEC_ID = 128\nconst SEMVER_RE = /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/\n\ninterface WorkflowSpecState {\n name: string\n description?: string\n systemPrompt: string\n schemaVersion: string\n specId?: string\n version: string\n tags: string[]\n toolPalette: ToolPaletteItem[]\n canvasLayout?: CanvasLayout\n}\n\nfunction validateName(name: string): void {\n if (name.length < 1 || name.length > MAX_NAME) {\n throw new ConvilynAuthorError(`name must be 1–${MAX_NAME} characters (got ${name.length})`)\n }\n}\n\nfunction validateSpecId(specId: string): void {\n if (specId.length < 1 || specId.length > MAX_SPEC_ID || /\\s/.test(specId)) {\n throw new ConvilynAuthorError(\n `specId must be 1–${MAX_SPEC_ID} characters with no whitespace ` +\n `(the portal expects the \"dev_<developer-id>.<name>\" namespace)`\n )\n }\n}\n\nfunction validateVersion(version: string): void {\n if (!SEMVER_RE.test(version)) {\n throw new ConvilynAuthorError(`version must be valid semver (e.g. \"1.0.0\"; got \"${version}\")`)\n }\n}\n\nfunction validateDescription(description: string): void {\n if (description.length > MAX_DESCRIPTION) {\n throw new ConvilynAuthorError(`description must be ≤ ${MAX_DESCRIPTION} characters`)\n }\n}\n\nfunction validateSystemPrompt(systemPrompt: string): void {\n if (systemPrompt.length > MAX_SYSTEM_PROMPT) {\n throw new ConvilynAuthorError(`systemPrompt must be ≤ ${MAX_SYSTEM_PROMPT} characters`)\n }\n}\n\nfunction validateTag(tag: string): void {\n if (tag.length < 1 || tag.length > MAX_TAG_LEN) {\n throw new ConvilynAuthorError(`tag \"${tag}\" must be 1–${MAX_TAG_LEN} characters`)\n }\n}\n\nfunction validateTags(tags: string[]): void {\n if (tags.length > MAX_TAGS) {\n throw new ConvilynAuthorError(`at most ${MAX_TAGS} tags are allowed (got ${tags.length})`)\n }\n tags.forEach(validateTag)\n}\n\nfunction toolKey(toolName: string): string {\n // The forbidden tool may arrive bare or fully-qualified (\"server:request_user_input\").\n const parts = toolName.split(':')\n return parts[parts.length - 1] ?? toolName\n}\n\nfunction validateToolName(toolName: string): void {\n if (toolName.length < 1 || toolName.length > MAX_TOOL_NAME) {\n throw new ConvilynAuthorError(`toolName must be 1–${MAX_TOOL_NAME} characters`)\n }\n if (toolKey(toolName) === FORBIDDEN_TOOL) {\n throw new ConvilynAuthorError(\n `tool \"${FORBIDDEN_TOOL}\" is not permitted in a workflow palette ` +\n `(the agent cannot pause mid-execution)`\n )\n }\n}\n\n/** Immutable builder for a portable workflow spec. */\nexport class WorkflowSpec {\n #state: WorkflowSpecState\n\n constructor(name: string, options: { specId?: string; version?: string } = {}) {\n validateName(name)\n if (options.specId != null) {\n validateSpecId(options.specId)\n }\n const version = options.version ?? DEFAULT_VERSION\n validateVersion(version)\n this.#state = {\n name,\n systemPrompt: '',\n schemaVersion: DEFAULT_SCHEMA_VERSION,\n specId: options.specId,\n version,\n tags: [],\n toolPalette: [],\n }\n }\n\n #cloneWith(patch: Partial<WorkflowSpecState>): WorkflowSpec {\n const next = new WorkflowSpec(this.#state.name)\n next.#state = {\n ...this.#state,\n ...patch,\n tags: [...(patch.tags ?? this.#state.tags)],\n toolPalette: [...(patch.toolPalette ?? this.#state.toolPalette)],\n }\n return next\n }\n\n // ── read-only accessors (return copies to preserve immutability) ──────────\n get name(): string {\n return this.#state.name\n }\n get description(): string | undefined {\n return this.#state.description\n }\n get systemPrompt(): string {\n return this.#state.systemPrompt\n }\n get schemaVersion(): string {\n return this.#state.schemaVersion\n }\n get specId(): string | undefined {\n return this.#state.specId\n }\n get version(): string {\n return this.#state.version\n }\n get tags(): readonly string[] {\n return [...this.#state.tags]\n }\n get toolPalette(): readonly ToolPaletteItem[] {\n return this.#state.toolPalette.map((item) => ({ ...item, position: { ...item.position } }))\n }\n get canvasLayout(): CanvasLayout | undefined {\n return this.#state.canvasLayout\n }\n\n // ── builder methods ───────────────────────────────────────────────────────\n withName(name: string): WorkflowSpec {\n validateName(name)\n return this.#cloneWith({ name })\n }\n\n withDescription(description: string): WorkflowSpec {\n validateDescription(description)\n return this.#cloneWith({ description })\n }\n\n withSystemPrompt(systemPrompt: string): WorkflowSpec {\n validateSystemPrompt(systemPrompt)\n return this.#cloneWith({ systemPrompt })\n }\n\n withSchemaVersion(schemaVersion: string): WorkflowSpec {\n return this.#cloneWith({ schemaVersion })\n }\n\n /** Set the portal spec id (`dev_<developer-id>.<name>` namespace). */\n withSpecId(specId: string): WorkflowSpec {\n validateSpecId(specId)\n return this.#cloneWith({ specId })\n }\n\n /** Set the blueprint semver version (default `1.0.0`). */\n withVersion(version: string): WorkflowSpec {\n validateVersion(version)\n return this.#cloneWith({ version })\n }\n\n /** Replace the tag set. */\n withTags(tags: string[]): WorkflowSpec {\n validateTags(tags)\n return this.#cloneWith({ tags: [...tags] })\n }\n\n /** Append a tag (no-op if already present). */\n addTag(tag: string): WorkflowSpec {\n validateTag(tag)\n if (this.#state.tags.includes(tag)) {\n return this.#cloneWith({})\n }\n const tags = [...this.#state.tags, tag]\n validateTags(tags)\n return this.#cloneWith({ tags })\n }\n\n /**\n * Add (or replace, by `toolName`) one tool on the palette. Rejects the\n * `request_user_input` tool (invariant I3) and palettes larger than\n * {@link MAX_TOOLS}.\n */\n addTool(toolName: string, options: { position?: Position; note?: string } = {}): WorkflowSpec {\n validateToolName(toolName)\n if (options.note != null && options.note.length > MAX_NOTE) {\n throw new ConvilynAuthorError(`tool note must be ≤ ${MAX_NOTE} characters`)\n }\n const item: ToolPaletteItem = {\n toolName,\n position: options.position ? { ...options.position } : { ...ORIGIN },\n ...(options.note != null ? { note: options.note } : {}),\n }\n const existing = this.#state.toolPalette.findIndex((entry) => entry.toolName === toolName)\n const toolPalette =\n existing >= 0\n ? this.#state.toolPalette.map((entry, index) => (index === existing ? item : entry))\n : [...this.#state.toolPalette, item]\n if (toolPalette.length > MAX_TOOLS) {\n throw new ConvilynAuthorError(`at most ${MAX_TOOLS} tools are allowed`)\n }\n return this.#cloneWith({ toolPalette })\n }\n\n /** Add several tools by name (default canvas position), de-duplicated. */\n useTools(...toolNames: string[]): WorkflowSpec {\n return toolNames.reduce<WorkflowSpec>((spec, toolName) => spec.addTool(toolName), this)\n }\n\n withCanvasLayout(canvasLayout: CanvasLayout): WorkflowSpec {\n return this.#cloneWith({ canvasLayout })\n }\n\n // ── compile / serialize ───────────────────────────────────────────────────\n /**\n * The PUBLIC publish blueprint (snake_case; Python-SDK parity). This is the\n * shape `submitWorkflow` / `convilyn-author push` send to the Developer\n * Portal. Requires a `specId` (constructor option or {@link withSpecId}).\n *\n * Mirrors the Python SDK's `exclude_none` semantics: `agent_config` is\n * emitted only when a systemPrompt is set, `mcp_config` only when the\n * palette is non-empty. UI-only metadata (positions, notes, canvasLayout)\n * is deliberately NOT emitted — the portal's blueprint schema rejects\n * unknown fields; that data belongs to {@link toExportPayload}.\n */\n compile(): WorkflowBlueprint {\n const specId = this.#state.specId\n if (specId == null) {\n throw new ConvilynAuthorError(\n 'compile() requires a specId — pass it to the constructor ' +\n '(new WorkflowSpec(name, { specId })) or call withSpecId(). ' +\n 'The Developer Portal expects the \"dev_<developer-id>.<name>\" namespace.'\n )\n }\n const blueprint: WorkflowBlueprint = {\n public_schema_version: PUBLIC_SCHEMA_VERSION,\n spec_id: specId,\n version: this.#state.version,\n name: this.#state.name,\n keywords: [...this.#state.tags],\n }\n if (this.#state.description != null) {\n blueprint.description = this.#state.description\n }\n if (this.#state.systemPrompt !== '') {\n blueprint.agent_config = { system_prompt: this.#state.systemPrompt }\n }\n if (this.#state.toolPalette.length > 0) {\n const tools = this.#state.toolPalette.map((item) => item.toolName)\n const servers = [\n ...new Set(\n tools\n .filter((toolName) => toolName.includes(':'))\n .map((toolName) => toolName.split(':')[0] as string)\n ),\n ]\n blueprint.mcp_config = { mcp_servers: servers, tools }\n }\n return blueprint\n }\n\n /** The compiled blueprint serialised as 2-space-indented JSON. */\n compileJson(): string {\n return JSON.stringify(this.compile(), null, 2)\n }\n\n /** Write the compiled blueprint to a JSON file (default `workflow.spec.json`). */\n async save(path = 'workflow.spec.json'): Promise<string> {\n await writeFile(path, this.compileJson(), 'utf8')\n return path\n }\n\n /**\n * The camelCase user_workflows `ExportPayload` (canvas/authoring contract).\n * Carries the UI-only metadata (positions, notes, canvasLayout) that the\n * publish blueprint omits.\n */\n toExportPayload(): ExportPayload {\n const payload: ExportPayload = {\n schemaVersion: this.#state.schemaVersion,\n name: this.#state.name,\n systemPrompt: this.#state.systemPrompt,\n toolPalette: this.#state.toolPalette.map((item) => ({\n toolName: item.toolName,\n position: { ...item.position },\n ...(item.note != null ? { note: item.note } : {}),\n })),\n tags: [...this.#state.tags],\n }\n if (this.#state.description != null) {\n payload.description = this.#state.description\n }\n if (this.#state.canvasLayout != null) {\n payload.canvasLayout = this.#state.canvasLayout\n }\n return payload\n }\n\n /** Rebuild a {@link WorkflowSpec} from a user_workflows `ExportPayload`. */\n static fromExportPayload(payload: ExportPayload): WorkflowSpec {\n let spec = new WorkflowSpec(payload.name)\n .withSystemPrompt(payload.systemPrompt ?? '')\n .withSchemaVersion(payload.schemaVersion ?? DEFAULT_SCHEMA_VERSION)\n .withTags(payload.tags ?? [])\n if (payload.description != null) {\n spec = spec.withDescription(payload.description)\n }\n if (payload.canvasLayout != null) {\n spec = spec.withCanvasLayout(payload.canvasLayout)\n }\n for (const item of payload.toolPalette ?? []) {\n spec = spec.addTool(item.toolName, {\n position: item.position,\n ...(item.note != null ? { note: item.note } : {}),\n })\n }\n return spec\n }\n\n /**\n * Rebuild a {@link WorkflowSpec} from a publish blueprint. Lossy for canvas\n * metadata by design — that data lives in the `ExportPayload` contract.\n */\n static fromBlueprint(blueprint: WorkflowBlueprint): WorkflowSpec {\n let spec = new WorkflowSpec(blueprint.name, {\n specId: blueprint.spec_id,\n ...(blueprint.version != null ? { version: blueprint.version } : {}),\n })\n .withSystemPrompt(blueprint.agent_config?.system_prompt ?? '')\n .withTags(blueprint.keywords ?? [])\n if (blueprint.description != null) {\n spec = spec.withDescription(blueprint.description)\n }\n for (const toolName of blueprint.mcp_config?.tools ?? []) {\n spec = spec.addTool(toolName)\n }\n return spec\n }\n\n /**\n * Parse a spec from a JSON string. Shape-sniffs: objects carrying `spec_id`\n * or `public_schema_version` parse as a blueprint; anything else as an\n * `ExportPayload` — so `push --workflow-file` accepts both file formats.\n */\n static fromJson(data: string): WorkflowSpec {\n const parsed: unknown = JSON.parse(data)\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new ConvilynAuthorError('workflow spec JSON must be an object')\n }\n if ('spec_id' in parsed || 'public_schema_version' in parsed) {\n return WorkflowSpec.fromBlueprint(parsed as WorkflowBlueprint)\n }\n return WorkflowSpec.fromExportPayload(parsed as ExportPayload)\n }\n\n /** Read a saved spec from a JSON file (default `workflow.spec.json`). */\n static async load(path = 'workflow.spec.json'): Promise<WorkflowSpec> {\n return WorkflowSpec.fromJson(await readFile(path, 'utf8'))\n }\n}\n","/**\n * Locate and load the author's {@link WorkflowSpec} for the `push` command.\n *\n * Two shapes are accepted, mirroring how authors persist a spec:\n * - a compiled `.json` file written by `WorkflowSpec.save()` — loaded via\n * `WorkflowSpec.load()`;\n * - a built `.js`/`.mjs`/`.cjs` module exporting a `WorkflowSpec` as its\n * default or a named `workflow` export — duck-typed, never\n * `instanceof`-checked, because the CLI binary bundles its own copy of\n * `WorkflowSpec` while the author's instance comes from *their* installed\n * `@convilyn/sdk-author` (two distinct class identities). This matches the\n * `loadToolServer` contract for the server side.\n */\n\nimport { extname, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { WorkflowSpec } from '../workflow'\n\n/** The minimal surface `push` needs from a loaded workflow. */\nexport interface CompilableWorkflow {\n readonly name: string\n compile(): unknown\n}\n\nfunction isWorkflowSpecLike(value: unknown): value is CompilableWorkflow {\n if (typeof value !== 'object' || value === null) {\n return false\n }\n const candidate = value as Record<string, unknown>\n return typeof candidate.compile === 'function' && typeof candidate.name === 'string'\n}\n\nfunction pickWorkflow(mod: Record<string, unknown>): CompilableWorkflow | undefined {\n if (isWorkflowSpecLike(mod.default)) {\n return mod.default\n }\n if (isWorkflowSpecLike(mod.workflow)) {\n return mod.workflow\n }\n for (const value of Object.values(mod)) {\n if (isWorkflowSpecLike(value)) {\n return value\n }\n }\n return undefined\n}\n\n/**\n * Load the {@link WorkflowSpec} at `file`. A `.json` file is parsed as a\n * compiled spec; any other extension is imported as a built module. Throws a\n * descriptive error when the file cannot be loaded or exports no workflow.\n */\nexport async function loadWorkflowSpec(file: string): Promise<CompilableWorkflow> {\n const absolute = resolve(file)\n\n if (extname(absolute).toLowerCase() === '.json') {\n try {\n return await WorkflowSpec.load(absolute)\n } catch (err) {\n throw new Error(\n `Could not load workflow spec \"${file}\": ${(err as Error).message}. ` +\n `Point --workflow-file at a compiled spec JSON (from WorkflowSpec.save()) ` +\n `or a built .js module that exports a WorkflowSpec.`\n )\n }\n }\n\n let mod: Record<string, unknown>\n try {\n mod = (await import(pathToFileURL(absolute).href)) as Record<string, unknown>\n } catch (err) {\n throw new Error(\n `Could not import workflow module \"${file}\": ${(err as Error).message}. ` +\n `Point --workflow-file at a built .js module (e.g. \"npm run build\" then ` +\n `--workflow-file dist/workflow.js) or a compiled .spec.json.`\n )\n }\n const workflow = pickWorkflow(mod)\n if (workflow === undefined) {\n throw new Error(\n `No WorkflowSpec found in \"${file}\". Export it as the default export or as a named \"workflow\" export.`\n )\n }\n return workflow\n}\n","/**\n * Inbound HMAC verification for calls from the Convilyn gateway, plus the\n * matching signer. Mirrors the gateway's `mcp_gateway/hmac_signer.py` and the\n * Python / Go author SDKs **byte-for-byte**, so a TS-authored server is\n * interchangeable behind the same gateway.\n *\n * Wire format:\n * - `x-convilyn-signature` — HMAC-SHA256 hex digest\n * - `x-convilyn-timestamp` — Unix seconds (integer string)\n * - `x-convilyn-server-id` — server name, audit-only (NOT in the signed payload)\n *\n * Signed payload = `<timestamp>` bytes + `.` + raw body bytes. Comparison is\n * constant-time; a timestamp tolerance window defends against replay.\n *\n * This is a public author capability: a server using its own HTTP framework\n * (instead of the SDK's runtime) calls {@link verifySignature} to reject forged\n * requests.\n */\n\nimport { createHmac, timingSafeEqual } from 'node:crypto'\nimport { InvalidSignatureError } from './errors'\n\n/** HMAC header names (lowercase; match the gateway's signer). */\nexport const SIGNATURE_HEADER = 'x-convilyn-signature'\nexport const TIMESTAMP_HEADER = 'x-convilyn-timestamp'\nexport const SERVER_ID_HEADER = 'x-convilyn-server-id'\n\n/** Default replay window (seconds) vs the gateway clock. */\nexport const DEFAULT_HMAC_TOLERANCE_SECONDS = 300\n\n/**\n * Body accepted by the signer / verifier. The gateway signs the **raw body\n * bytes**, so a binary or non-UTF-8 body MUST be passed as `Uint8Array` — a\n * lossy-decoded `string` re-encodes as UTF-8 and will not reproduce the digest\n * (the request is rejected, never falsely accepted).\n */\nexport type RequestBody = string | Uint8Array\n\nfunction expectedSignature(secret: string, timestamp: string, body: RequestBody): string {\n return createHmac('sha256', secret).update(timestamp).update('.').update(body).digest('hex')\n}\n\n/**\n * Produce the `{ signature, timestamp }` pair for an outbound request, mirroring\n * the gateway's signer. Useful for tests and for clients calling a\n * developer-hosted server directly. `unixSeconds` is truncated to an integer.\n */\nexport function signRequest(\n secret: string,\n body: RequestBody,\n unixSeconds: number\n): { signature: string; timestamp: string } {\n const timestamp = String(Math.trunc(unixSeconds))\n return { signature: expectedSignature(secret, timestamp, body), timestamp }\n}\n\n/** Tunables for {@link verifySignature}. */\nexport interface VerifyOptions {\n /** Max clock skew (seconds) vs the gateway; `<= 0` uses the default 300. */\n toleranceSeconds?: number\n /** Override \"now\" (Unix seconds) for tests; defaults to the real clock. */\n now?: () => number\n}\n\nfunction constantTimeEqual(a: string, b: string): boolean {\n const aBuf = Buffer.from(a)\n const bBuf = Buffer.from(b)\n // timingSafeEqual throws on unequal length; a wrong-length digest is simply\n // not equal. The expected digest is a fixed 64-hex string, so the length\n // check leaks nothing useful.\n if (aBuf.length !== bBuf.length) {\n return false\n }\n return timingSafeEqual(aBuf, bBuf)\n}\n\n/**\n * Verify an inbound HMAC signature; throw {@link InvalidSignatureError} on any\n * failure (missing secret/headers, malformed or out-of-tolerance timestamp, or\n * digest mismatch). Header keys must be lowercased.\n */\nexport function verifySignature(\n secret: string,\n body: RequestBody,\n headers: Record<string, string | undefined>,\n options: VerifyOptions = {}\n): void {\n const tolerance =\n options.toleranceSeconds != null && options.toleranceSeconds > 0\n ? options.toleranceSeconds\n : DEFAULT_HMAC_TOLERANCE_SECONDS\n const now = options.now ?? (() => Math.floor(Date.now() / 1000))\n\n if (!secret) {\n throw new InvalidSignatureError('missing_secret', 'HMAC secret is not configured on the server')\n }\n\n const signature = headers[SIGNATURE_HEADER]\n const timestamp = headers[TIMESTAMP_HEADER]\n if (!signature || !timestamp) {\n throw new InvalidSignatureError(\n 'missing_header',\n 'Missing X-Convilyn-Signature or X-Convilyn-Timestamp'\n )\n }\n\n if (!/^[+-]?\\d+$/.test(timestamp)) {\n throw new InvalidSignatureError(\n 'invalid_timestamp',\n 'X-Convilyn-Timestamp must be an integer Unix-seconds value'\n )\n }\n const tsValue = Number(timestamp)\n\n if (Math.abs(now() - tsValue) > tolerance) {\n throw new InvalidSignatureError(\n 'timestamp_out_of_range',\n 'Request timestamp outside acceptable tolerance window'\n )\n }\n\n const expected = expectedSignature(secret, timestamp, body)\n if (!constantTimeEqual(expected, signature)) {\n throw new InvalidSignatureError(\n 'signature_mismatch',\n 'Signature did not match expected HMAC-SHA256 digest'\n )\n }\n}\n","/**\n * Environment-driven SDK configuration for a tool server. Port of the Go\n * `SDKConfig` / Python frozen `SDKConfig`. Read it with {@link SDKConfig.fromEnv};\n * construct directly (with explicit options) in tests.\n */\n\nimport { DEFAULT_HMAC_TOLERANCE_SECONDS } from './auth'\n\n/** Construction options for {@link SDKConfig}; each falls back to a default. */\nexport interface SDKConfigOptions {\n serverHost?: string\n serverPort?: number\n logLevel?: string\n awsRegion?: string\n dynamodbEndpoint?: string\n toolDataTable?: string\n environment?: string\n apiKey?: string\n platformUrl?: string\n hmacSecret?: string\n hmacToleranceSeconds?: number\n /** Secret for minting / verifying confirmation-handshake tokens. */\n toolConfirmationSecret?: string\n /** Whether the process runs in AWS Lambda (set by {@link SDKConfig.fromEnv}). */\n lambda?: boolean\n}\n\ntype EnvLike = Record<string, string | undefined>\n\nfunction envOr(env: EnvLike, key: string, fallback: string): string {\n const value = env[key]\n return value !== undefined && value !== '' ? value : fallback\n}\n\nfunction envIntOr(env: EnvLike, key: string, fallback: number): number {\n const value = env[key]\n if (value !== undefined && value !== '') {\n const parsed = Number(value)\n if (Number.isInteger(parsed)) {\n return parsed\n }\n }\n return fallback\n}\n\n/** Immutable SDK configuration. */\nexport class SDKConfig {\n readonly serverHost: string\n readonly serverPort: number\n readonly logLevel: string\n readonly awsRegion: string\n readonly dynamodbEndpoint: string\n readonly toolDataTable: string\n readonly environment: string\n readonly apiKey: string\n readonly platformUrl: string\n readonly hmacSecret: string\n readonly hmacToleranceSeconds: number\n readonly toolConfirmationSecret: string\n readonly #lambda: boolean\n\n constructor(options: SDKConfigOptions = {}) {\n this.serverHost = options.serverHost ?? '127.0.0.1'\n this.serverPort = options.serverPort ?? 8080\n this.logLevel = options.logLevel ?? 'INFO'\n this.awsRegion = options.awsRegion ?? 'ap-northeast-1'\n this.dynamodbEndpoint = options.dynamodbEndpoint ?? ''\n this.toolDataTable = options.toolDataTable ?? 'tool-data'\n this.environment = options.environment ?? 'local'\n this.apiKey = options.apiKey ?? ''\n this.platformUrl = options.platformUrl ?? 'https://api.convilyn.corenovus.com'\n this.hmacSecret = options.hmacSecret ?? ''\n this.hmacToleranceSeconds = options.hmacToleranceSeconds ?? DEFAULT_HMAC_TOLERANCE_SECONDS\n this.toolConfirmationSecret = options.toolConfirmationSecret ?? ''\n this.#lambda = options.lambda ?? false\n }\n\n /** True when running in AWS Lambda. */\n get isLambda(): boolean {\n return this.#lambda\n }\n\n /** True for a local/dev environment (relaxes HMAC). */\n get isLocal(): boolean {\n if (this.environment === 'local') {\n return true\n }\n return !this.#lambda && (this.serverHost === '127.0.0.1' || this.serverHost === 'localhost')\n }\n\n /** Load configuration from environment variables, falling back to defaults. */\n static fromEnv(env: EnvLike = typeof process !== 'undefined' ? process.env : {}): SDKConfig {\n return new SDKConfig({\n serverHost: envOr(env, 'CONVILYN_HOST', '127.0.0.1'),\n serverPort: envIntOr(env, 'CONVILYN_PORT', 8080),\n logLevel: envOr(env, 'CONVILYN_LOG_LEVEL', 'INFO'),\n awsRegion: envOr(env, 'AWS_REGION', 'ap-northeast-1'),\n dynamodbEndpoint: envOr(env, 'DYNAMODB_ENDPOINT', ''),\n toolDataTable: envOr(env, 'TOOL_DATA_TABLE', 'tool-data'),\n environment: envOr(env, 'CONVILYN_ENVIRONMENT', 'local'),\n apiKey: envOr(env, 'CONVILYN_API_KEY', ''),\n platformUrl: envOr(env, 'CONVILYN_PLATFORM_URL', 'https://api.convilyn.corenovus.com'),\n hmacSecret: envOr(env, 'CONVILYN_HMAC_SECRET', ''),\n hmacToleranceSeconds: envIntOr(\n env,\n 'CONVILYN_HMAC_TOLERANCE_SECONDS',\n DEFAULT_HMAC_TOLERANCE_SECONDS\n ),\n toolConfirmationSecret: envOr(env, 'CONVILYN_TOOL_CONFIRMATION_SECRET', ''),\n lambda: Boolean(env['AWS_LAMBDA_FUNCTION_NAME']),\n })\n }\n}\n","/**\n * `ConvilynClient` — a fetch-based client for the **Developer Portal**\n * (`/api/v1/developers/*`), the platform's third-party author/publish surface.\n *\n * This is the TypeScript counterpart of the Python `convilyn_sdk.ConvilynClient`\n * (`sdk/author-python/src/convilyn_sdk/client.py`): the author BUILDS a tool\n * server + workflow spec locally (`ToolServer`, `WorkflowSpec`,\n * `runComplianceChecks`), then INTEGRATES its own artifacts by registering them\n * through the portal:\n *\n * POST /developers/register — mint a `cvl_` developer key (no auth)\n * POST /developers/servers — submit a tool-server manifest\n * GET /developers/servers — list\n * GET /developers/servers/{id}/status — verification status\n * POST /developers/servers/{id}/test — sandbox test\n * DELETE /developers/servers/{id} — deactivate\n * POST /developers/workflows — submit a compiled workflow spec\n * GET /developers/workflows — list\n * GET /developers/workflows/{id}/status — status\n * POST /developers/workflows/{id}/test — sandbox test\n * DELETE /developers/workflows/{id} — deactivate\n * POST /developers/runtimes/hosted — deploy to the hosted author runtime\n * POST /developers/runtimes/{id}/rollback — flip to the previous version\n * GET /developers/runtimes/{id}/logs — recent runtime log lines\n *\n * Auth: `Authorization: Bearer <cvl_ developer key>`, read from\n * `CONVILYN_API_KEY` (`config.ts`). This SDK deliberately does NOT call the\n * first-party console surfaces (`/user_workflows/*`, `/mcp/tools/catalog`) — those\n * are JWT/session endpoints owned by the web UI, not an author-publishing API.\n * Response bodies are snake_case, matching the platform's Developer Portal\n * API.\n */\n\nimport { SDKConfig } from './config'\nimport { ConvilynApiError, ConvilynAuthorError } from './errors'\nimport type {\n DeployHostedResponse,\n DeveloperRegisterRequest,\n DeveloperRegisterResponse,\n DeveloperServer,\n RollbackResponse,\n RuntimeLogEntry,\n ServerStatusResponse,\n ServerSubmitRequest,\n ServerSubmitResponse,\n TestRunResponse,\n WorkflowListItem,\n WorkflowStatusResponse,\n WorkflowSubmitRequest,\n WorkflowSubmitResponse,\n WorkflowTestResponse,\n} from './platform-types'\n\n/** The subset of `fetch` the client uses (so a fake can be injected in tests). */\nexport type FetchLike = (\n url: string,\n init?: { method?: string; headers?: Record<string, string>; body?: string }\n) => Promise<{\n ok: boolean\n status: number\n json(): Promise<unknown>\n text(): Promise<string>\n}>\n\n/** Options for {@link ConvilynClient}; unset fields fall back to {@link SDKConfig}. */\nexport interface ConvilynClientOptions {\n /** Full API base incl. `/api/v1`; defaults to `${platformUrl}/api/v1`. */\n baseUrl?: string\n /** `cvl_` developer key; defaults to `CONVILYN_API_KEY`. */\n apiKey?: string\n /** Injected `fetch` (defaults to the global). */\n fetch?: FetchLike\n config?: SDKConfig\n}\n\nfunction withApiV1(platformUrl: string): string {\n const trimmed = platformUrl.replace(/\\/+$/, '')\n return trimmed.endsWith('/api/v1') ? trimmed : `${trimmed}/api/v1`\n}\n\n/** The consumer data-plane key prefix — NOT an author/developer-portal token. */\nconst CONSUMER_KEY_PREFIX = 'ck_' // pragma: allowlist secret\n\n/** True when `key` is a consumer data-plane key pasted in by mistake. */\nfunction isConsumerKey(key: string): boolean {\n return key.startsWith(CONSUMER_KEY_PREFIX)\n}\n\n/** Mask a secret for safe display: `ck_a…9f` (or `***` when too short). */\nfunction maskKey(key: string): string {\n return key.length <= 8 ? '***' : `${key.slice(0, 4)}…${key.slice(-2)}`\n}\n\n/** Fetch-based client for the Developer Portal author/publish endpoints. */\nexport class ConvilynClient {\n readonly baseUrl: string\n #apiKey: string\n readonly #fetch: FetchLike\n\n constructor(options: ConvilynClientOptions = {}) {\n const config = options.config ?? SDKConfig.fromEnv()\n this.baseUrl = options.baseUrl ?? withApiV1(config.platformUrl)\n this.#apiKey = options.apiKey ?? config.apiKey\n // Reject a consumer ck_ key pasted into the Author SDK up front with a\n // precise error, instead of the developer portal answering with an opaque\n // 401 later. An empty key is fine — register() mints a cvl_ one. Any other\n // prefix is accepted (forward-compat). Mirror of the consumer SDKs' inverse\n // guard (see consumer-ts auth.ts).\n if (this.#apiKey && isConsumerKey(this.#apiKey)) {\n throw new ConvilynAuthorError(\n `${maskKey(this.#apiKey)} looks like a Convilyn consumer API key (\"${CONSUMER_KEY_PREFIX}\"), ` +\n `not an Author SDK / developer-portal token. The Author SDK authenticates with a ` +\n `cvl_ developer key — call register() to mint one, or set CONVILYN_API_KEY to your ` +\n `cvl_ key. (Consumer keys call the data-plane API; they do not publish workflows / tools.)`\n )\n }\n this.#fetch = options.fetch ?? (globalThis.fetch as unknown as FetchLike)\n }\n\n /** The `cvl_` developer key currently in use (empty until set or registered). */\n get apiKey(): string {\n return this.#apiKey\n }\n\n #headers(auth: boolean): Record<string, string> {\n const headers: Record<string, string> = { 'content-type': 'application/json' }\n if (auth) {\n if (!this.#apiKey) {\n throw new ConvilynAuthorError(\n 'No developer API key set. Provide `apiKey`, set CONVILYN_API_KEY to a ' +\n 'cvl_ developer key, or call register() first.'\n )\n }\n headers.authorization = `Bearer ${this.#apiKey}`\n }\n return headers\n }\n\n async #request<T>(method: string, path: string, body?: unknown, auth = true): Promise<T> {\n const res = await this.#fetch(`${this.baseUrl}${path}`, {\n method,\n headers: this.#headers(auth),\n body: body !== undefined ? JSON.stringify(body) : undefined,\n })\n if (!res.ok) {\n let parsed: unknown\n try {\n parsed = await res.json()\n } catch {\n parsed = undefined\n }\n throw new ConvilynApiError(\n res.status,\n `${method} ${path} failed (HTTP ${res.status})`,\n parsed\n )\n }\n if (res.status === 204) {\n return undefined as T\n }\n return (await res.json()) as T\n }\n\n // ── Developer registration ──────────────────────────────────────\n\n /**\n * `POST /developers/register` — create a developer account and mint a `cvl_`\n * key. No auth required. The returned key is captured on this client for\n * subsequent calls (and returned so the caller can persist it — it is shown\n * only once).\n */\n async register(request: DeveloperRegisterRequest): Promise<DeveloperRegisterResponse> {\n const result = await this.#request<DeveloperRegisterResponse>(\n 'POST',\n '/developers/register',\n request,\n false\n )\n if (result.api_key && !this.#apiKey) {\n this.#apiKey = result.api_key\n }\n return result\n }\n\n // ── Server operations ───────────────────────────────────────────\n\n /** `POST /developers/servers` — submit a tool-server manifest for verification. */\n async submitServer(request: ServerSubmitRequest): Promise<ServerSubmitResponse> {\n return this.#request<ServerSubmitResponse>('POST', '/developers/servers', request)\n }\n\n /** `GET /developers/servers` — list this developer's servers. */\n async listServers(): Promise<DeveloperServer[]> {\n return this.#request<DeveloperServer[]>('GET', '/developers/servers')\n }\n\n /** `GET /developers/servers/{id}/status` — verification status of a server. */\n async serverStatus(serverId: string): Promise<ServerStatusResponse> {\n return this.#request<ServerStatusResponse>(\n 'GET',\n `/developers/servers/${encodeURIComponent(serverId)}/status`\n )\n }\n\n /** `POST /developers/servers/{id}/test` — trigger a sandbox test run. */\n async testServer(\n serverId: string,\n slots: Record<string, unknown> = {}\n ): Promise<TestRunResponse> {\n return this.#request<TestRunResponse>(\n 'POST',\n `/developers/servers/${encodeURIComponent(serverId)}/test`,\n { slots }\n )\n }\n\n /** `DELETE /developers/servers/{id}` — deactivate a server. */\n async deactivateServer(serverId: string): Promise<void> {\n await this.#request<void>('DELETE', `/developers/servers/${encodeURIComponent(serverId)}`)\n }\n\n // ── Workflow operations ─────────────────────────────────────────\n\n /** `POST /developers/workflows` — submit a compiled workflow spec + its server ids. */\n async submitWorkflow(request: WorkflowSubmitRequest): Promise<WorkflowSubmitResponse> {\n return this.#request<WorkflowSubmitResponse>('POST', '/developers/workflows', request)\n }\n\n /** `GET /developers/workflows` — list this developer's workflows. */\n async listWorkflows(): Promise<WorkflowListItem[]> {\n return this.#request<WorkflowListItem[]>('GET', '/developers/workflows')\n }\n\n /** `GET /developers/workflows/{id}/status` — verification status of a workflow. */\n async workflowStatus(workflowId: string): Promise<WorkflowStatusResponse> {\n return this.#request<WorkflowStatusResponse>(\n 'GET',\n `/developers/workflows/${encodeURIComponent(workflowId)}/status`\n )\n }\n\n /** `POST /developers/workflows/{id}/test` — sandbox-test a submitted workflow. */\n async testWorkflow(\n workflowId: string,\n testInput: Record<string, unknown> = {}\n ): Promise<WorkflowTestResponse> {\n return this.#request<WorkflowTestResponse>(\n 'POST',\n `/developers/workflows/${encodeURIComponent(workflowId)}/test`,\n { test_input: testInput }\n )\n }\n\n /** `DELETE /developers/workflows/{id}` — deactivate a workflow. */\n async deactivateWorkflow(workflowId: string): Promise<void> {\n await this.#request<void>('DELETE', `/developers/workflows/${encodeURIComponent(workflowId)}`)\n }\n\n // ── Convilyn-Hosted Author Runtime (port of the Python client) ─────────────\n\n /**\n * `POST /developers/runtimes/hosted` — deploy a tool server into the\n * Convilyn-Hosted Author Runtime. Counterpart to {@link submitServer}:\n * instead of registering a caller-deployed endpoint, the platform\n * provisions a sandboxed Lambda and returns its public endpoint URL.\n *\n * Backends without the hosted stack answer 503 `HOSTED_NOT_AVAILABLE`\n * (older builds: 501); environments with the router unmounted answer 404.\n * All surface as {@link ConvilynApiError} — catch and fall back to\n * `push --endpoint-url` (BYO) when a hard guarantee is needed.\n */\n async deployHostedRuntime(\n manifest: Record<string, unknown>,\n options: { region: string; workflowSpec?: Record<string, unknown> }\n ): Promise<DeployHostedResponse> {\n const body: Record<string, unknown> = { manifest, region: options.region }\n if (options.workflowSpec !== undefined) {\n body.workflow_spec = options.workflowSpec\n }\n return this.#request<DeployHostedResponse>('POST', '/developers/runtimes/hosted', body)\n }\n\n /**\n * `POST /developers/runtimes/{id}/rollback` — atomically flip the runtime\n * back to its previous active version.\n */\n async rollbackHostedRuntime(runtimeId: string): Promise<RollbackResponse> {\n return this.#request<RollbackResponse>(\n 'POST',\n `/developers/runtimes/${encodeURIComponent(runtimeId)}/rollback`\n )\n }\n\n /**\n * `GET /developers/runtimes/{id}/logs` — recent runtime log lines.\n * `since` is an ISO-8601 timestamp or relative shorthand (`\"5m\"`, `\"1h\"`)\n * interpreted server-side; `limit` defaults to 100 (server caps ~1000).\n * Accepts either a bare list or an `{entries: [...]}` envelope (mirror of\n * the Python client) so the SDK survives the wire shape stabilising.\n */\n async getHostedRuntimeLogs(\n runtimeId: string,\n options: { since?: string; limit?: number } = {}\n ): Promise<RuntimeLogEntry[]> {\n const limit = Math.trunc(options.limit ?? 100)\n let path = `/developers/runtimes/${encodeURIComponent(runtimeId)}/logs?limit=${limit}`\n if (options.since) {\n path = `${path}&since=${encodeURIComponent(options.since)}`\n }\n const result = await this.#request<unknown>('GET', path)\n if (Array.isArray(result)) {\n return result as RuntimeLogEntry[]\n }\n if (\n typeof result === 'object' &&\n result !== null &&\n Array.isArray((result as Record<string, unknown>).entries)\n ) {\n return (result as { entries: RuntimeLogEntry[] }).entries\n }\n return []\n }\n}\n","/**\n * JSON-RPC 2.0 envelope types + constructors for the `/mcp` runtime. The wire\n * shape matches the `mcp-shared` framework and the Python / Go author SDKs so a\n * TS-authored server is interchangeable behind the same gateway:\n *\n * request { jsonrpc:\"2.0\", method:\"tools/call\", params:{ name, arguments, context? }, id }\n * response { jsonrpc:\"2.0\", result?, error?:{ code, message, data? }, id }\n *\n * Tool-level outcomes (validation failures, tool errors) ride inside `result`\n * as a ToolResult envelope — only protocol-level faults use the `error` member.\n */\n\n/** JSON-RPC protocol version string. */\nexport const JSONRPC_VERSION = '2.0'\n\n/** Standard JSON-RPC 2.0 error codes (the only ones the `/mcp` runtime emits). */\nexport const PARSE_ERROR = -32700\nexport const INVALID_REQUEST = -32600\nexport const METHOD_NOT_FOUND = -32601\nexport const INVALID_PARAMS = -32602\nexport const INTERNAL_ERROR = -32603\n\n/** The single method the runtime dispatches. */\nexport const TOOLS_CALL = 'tools/call'\n\n/** An inbound JSON-RPC request. */\nexport interface JSONRPCRequest {\n jsonrpc: string\n method: string\n params?: Record<string, unknown>\n id?: string | number | null\n}\n\n/** The `error` member of a JSON-RPC response. */\nexport interface JSONRPCErrorObject {\n code: number\n message: string\n data?: Record<string, unknown>\n}\n\n/** An outbound JSON-RPC response (exactly one of `result` / `error`). */\nexport interface JSONRPCResponse {\n jsonrpc: typeof JSONRPC_VERSION\n result?: unknown\n error?: JSONRPCErrorObject\n id: string | number | null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Coerce parsed JSON into a {@link JSONRPCRequest}, or `null` when it is not a\n * well-formed request object (missing/`non-string method). The `id` defaults to\n * `null` so a response can always echo it.\n */\nexport function asRpcRequest(parsed: unknown): JSONRPCRequest | null {\n if (!isRecord(parsed) || typeof parsed.method !== 'string') {\n return null\n }\n const id = typeof parsed.id === 'string' || typeof parsed.id === 'number' ? parsed.id : null\n return {\n jsonrpc: typeof parsed.jsonrpc === 'string' ? parsed.jsonrpc : JSONRPC_VERSION,\n method: parsed.method,\n params: isRecord(parsed.params) ? parsed.params : {},\n id,\n }\n}\n\n/** Build a success response echoing `id`. */\nexport function rpcResult(id: string | number | null, result: unknown): JSONRPCResponse {\n return { jsonrpc: JSONRPC_VERSION, result, id }\n}\n\n/** Build an error response echoing `id`. */\nexport function rpcError(\n id: string | number | null,\n code: number,\n message: string,\n data?: Record<string, unknown>\n): JSONRPCResponse {\n const error: JSONRPCErrorObject = data !== undefined ? { code, message, data } : { code, message }\n return { jsonrpc: JSONRPC_VERSION, error, id }\n}\n","/**\n * Node `http` runtime for a {@link ToolServer}. Exposes the three endpoints the\n * gateway expects:\n *\n * GET /health → { status, server, version, tool_count }\n * GET /manifest → the server manifest (snake_case wire object)\n * POST /mcp → HMAC-verified JSON-RPC `tools/call` dispatch\n *\n * The HMAC signature covers the **raw request body bytes**, so the body buffer is\n * captured before any `JSON.parse`. Verification reuses {@link verifySignature}\n * (byte-for-byte parity with the gateway signer). No external dependencies.\n */\n\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport { verifySignature } from './auth'\nimport { ConvilynStartupError, InvalidSignatureError } from './errors'\nimport { SDKConfig } from './config'\nimport { VERSION } from './version'\nimport { asRpcRequest } from './jsonrpc'\nimport type { ToolServer } from './tool-server'\n\n/** Options for {@link serve}; unset fields fall back to {@link SDKConfig}. */\nexport interface ServeOptions {\n port?: number\n host?: string\n /** HMAC secret for `/mcp` verification. Required to accept signed requests. */\n hmacSecret?: string\n toleranceSeconds?: number\n /**\n * Explicit INSECURE local-development opt-in: with no secret configured,\n * `serve` refuses to start unless this is `true` (set by `convilyn-author\n * dev`) or `CONVILYN_DEV_INSECURE=1` is in the environment. A configured\n * secret always wins — the opt-in never bypasses verification.\n */\n allowInsecure?: boolean\n /** Pre-built config; defaults to {@link SDKConfig.fromEnv}. */\n config?: SDKConfig\n}\n\n/**\n * Environment variable that explicitly opts a bare `serve()` process into\n * INSECURE local development (no inbound signature verification). Port of the\n * Python `ENV_DEV_INSECURE` / Go `EnvDevInsecure`.\n */\nexport const ENV_DEV_INSECURE = 'CONVILYN_DEV_INSECURE'\n\nconst DEV_INSECURE_TRUTHY = new Set(['1', 'true', 'yes', 'on'])\n\n/**\n * True iff the operator explicitly opted into insecure local dev. Any other\n * value (including unset) is \"not opted in\" — the secure default is\n * fail-closed.\n */\nexport function devInsecureRequested(env: NodeJS.ProcessEnv = process.env): boolean {\n return DEV_INSECURE_TRUTHY.has((env[ENV_DEV_INSECURE] ?? '').trim().toLowerCase())\n}\n\nconst JSON_HEADERS = { 'content-type': 'application/json' } as const\n\nfunction sendJson(res: ServerResponse, statusCode: number, body: unknown): void {\n res.writeHead(statusCode, JSON_HEADERS)\n res.end(JSON.stringify(body))\n}\n\n/**\n * Inbound `/mcp` body cap (10 MB) — cross-SDK invariant shared with the\n * Python / Go author runtimes. Enforced while streaming, BEFORE signature\n * verification, so an unauthenticated caller cannot buffer unbounded bytes.\n */\nexport const MAX_BODY_BYTES = 10 * 1024 * 1024\n\n/** Thrown by {@link readBody} when the inbound body exceeds the cap. */\nclass BodyTooLargeError extends Error {\n constructor() {\n super(`Request body exceeds ${MAX_BODY_BYTES} bytes`)\n this.name = 'BodyTooLargeError'\n }\n}\n\n/** Collect the full request body as a Buffer (the bytes the HMAC signs). */\nfunction readBody(req: IncomingMessage, maxBytes: number = MAX_BODY_BYTES): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = []\n let total = 0\n req.on('data', (chunk: Buffer) => {\n total += chunk.length\n if (total > maxBytes) {\n // Stop buffering (later chunks are ignored) but keep the socket alive\n // so the caller can still answer 413 on the shared connection.\n chunks.length = 0\n reject(new BodyTooLargeError())\n return\n }\n chunks.push(chunk)\n })\n req.on('end', () => resolve(Buffer.concat(chunks)))\n req.on('error', reject)\n })\n}\n\nasync function handleMcp(\n server: ToolServer,\n req: IncomingMessage,\n res: ServerResponse,\n secret: string,\n toleranceSeconds: number,\n allowInsecure: boolean\n): Promise<void> {\n let body: Buffer\n try {\n body = await readBody(req)\n } catch (err) {\n if (err instanceof BodyTooLargeError) {\n // Answer first, then cut the connection once the response has flushed —\n // an endless streamer must not keep the socket (and kernel buffers) open.\n res.once('finish', () => req.destroy())\n sendJson(res, 413, {\n code: 'PAYLOAD_TOO_LARGE',\n message: 'Request body too large',\n })\n return\n }\n throw err\n }\n\n // Fail-closed: with no secret, only the explicit insecure-local opt-in\n // skips verification (serve() already warned loudly at startup). With a\n // secret configured the opt-in is ignored — verification always runs.\n if (secret === '' && allowInsecure) {\n await dispatchParsed(server, res, body)\n return\n }\n\n try {\n verifySignature(secret, body, req.headers as Record<string, string | undefined>, {\n toleranceSeconds,\n })\n } catch (err) {\n if (err instanceof InvalidSignatureError) {\n sendJson(res, 401, {\n code: 'INVALID_SIGNATURE',\n message: 'Request signature could not be verified',\n })\n return\n }\n throw err\n }\n\n await dispatchParsed(server, res, body)\n}\n\n/** Parse the (already-authorized) body and dispatch the JSON-RPC request. */\nasync function dispatchParsed(\n server: ToolServer,\n res: ServerResponse,\n body: Buffer\n): Promise<void> {\n let parsed: unknown\n try {\n parsed = JSON.parse(body.toString('utf8'))\n } catch {\n sendJson(res, 400, { error: 'Invalid JSON' })\n return\n }\n\n const request = asRpcRequest(parsed)\n if (request === null) {\n sendJson(res, 400, { error: 'Invalid JSON' })\n return\n }\n\n const response = await server.dispatch(request)\n sendJson(res, 200, response)\n}\n\n/**\n * Build and start an HTTP server for `toolServer`. Returns the listening\n * {@link Server}; await its `listening` event (and read `.address()`) for the\n * bound port when `port` is `0`.\n *\n * **Fail-closed:** unless an HMAC secret is configured, `serve` throws\n * {@link ConvilynStartupError} — independent of `CONVILYN_ENVIRONMENT` or the\n * bind host. Insecure local development must be opted into explicitly, either\n * via `allowInsecure: true` (passed by `convilyn-author dev`) or by setting\n * `CONVILYN_DEV_INSECURE=1`. Port of the Python `start_server`.\n */\nexport function serve(toolServer: ToolServer, options: ServeOptions = {}): Server {\n const config = options.config ?? SDKConfig.fromEnv()\n const host = options.host ?? config.serverHost\n const port = options.port ?? config.serverPort\n const secret = options.hmacSecret ?? config.hmacSecret\n const toleranceSeconds = options.toleranceSeconds ?? config.hmacToleranceSeconds\n const allowInsecure = options.allowInsecure ?? devInsecureRequested()\n\n if (secret === '' && !allowInsecure) {\n throw new ConvilynStartupError(\n 'CONVILYN_HMAC_SECRET is required to serve inbound /mcp traffic. ' +\n 'Refusing to start without signature verification. For local ' +\n `development use \\`convilyn-author dev\\` or set ${ENV_DEV_INSECURE}=1 ` +\n '(INSECURE — local only).'\n )\n }\n if (secret === '') {\n console.warn(\n 'convilyn-author: CONVILYN_HMAC_SECRET not set; serving /mcp WITHOUT ' +\n 'signature verification (insecure local dev only — do NOT deploy this configuration)'\n )\n }\n\n const httpServer = createServer((req, res) => {\n void route(toolServer, req, res, secret, toleranceSeconds, allowInsecure).catch(() => {\n if (!res.headersSent) {\n sendJson(res, 500, { error: 'Internal server error' })\n }\n })\n })\n\n httpServer.listen(port, host)\n return httpServer\n}\n\nasync function route(\n toolServer: ToolServer,\n req: IncomingMessage,\n res: ServerResponse,\n secret: string,\n toleranceSeconds: number,\n allowInsecure: boolean\n): Promise<void> {\n const path = (req.url ?? '').split('?')[0]\n const method = req.method ?? 'GET'\n\n if (method === 'GET' && path === '/health') {\n sendJson(res, 200, {\n status: 'healthy',\n server: toolServer.server.name,\n version: VERSION,\n tool_count: toolServer.toolCount,\n })\n return\n }\n\n if (method === 'GET' && path === '/manifest') {\n sendJson(res, 200, toolServer.manifest().toWire())\n return\n }\n\n if (method === 'POST' && path === '/mcp') {\n await handleMcp(toolServer, req, res, secret, toleranceSeconds, allowInsecure)\n return\n }\n\n sendJson(res, 404, { error: 'Not found' })\n}\n","/**\n * `ToolServer` — the registry of an author's tools and the transport-free\n * JSON-RPC dispatcher behind the `/mcp` endpoint. {@link ToolServer.dispatch} is\n * pure (request in, response out), so it is unit-testable without sockets; the\n * Node `http` wiring lives in `http-runtime.ts`.\n *\n * Dispatch contract (matches the `mcp-shared` framework):\n * - only `tools/call` is supported; any other method → `-32601`.\n * - missing `params.name` → `-32602`; unknown tool → `-32601`.\n * - input that fails the tool's Zod schema → a `validation_error` ToolResult\n * envelope inside `result` (NOT a JSON-RPC error).\n * - a handler that throws → `-32603`.\n * - the built-in `get_tool_data` resolves a `ref_id` from the DataStore; it is\n * not listed in the manifest (the platform injects it globally).\n */\n\nimport { ConvilynManifest } from './manifest'\nimport { InMemoryDataStore, type DataStore } from './datastore'\nimport { createToolContext } from './context'\nimport {\n rpcError,\n rpcResult,\n INTERNAL_ERROR,\n INVALID_PARAMS,\n METHOD_NOT_FOUND,\n TOOLS_CALL,\n type JSONRPCRequest,\n type JSONRPCResponse,\n} from './jsonrpc'\nimport {\n rawOkEnvelope,\n rawToolErrorEnvelope,\n toWireEnvelope,\n validationErrorEnvelope,\n type ValidationIssueWire,\n} from './tool-result-wire'\nimport type { ServerSpec } from './types'\nimport type { ToolDefinition } from './tool'\nimport { ConvilynAuthorError } from './errors'\n\n/** The built-in tool that resolves an offloaded `ref_id` to its full payload. */\nexport const GET_TOOL_DATA = 'get_tool_data'\n\n/** Options for constructing a {@link ToolServer}. */\nexport interface ToolServerOptions {\n tools?: ToolDefinition[]\n capabilities?: string[]\n /** Backing store for `ref_id` offload + retrieval; defaults to in-memory. */\n dataStore?: DataStore\n sdkVersion?: string\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** A minimal view of a Zod issue (avoids importing zod at runtime). */\ninterface ZodIssueLike {\n path: ReadonlyArray<string | number>\n message: string\n code?: string\n}\n\nfunction toValidationIssues(issues: ReadonlyArray<ZodIssueLike>): ValidationIssueWire[] {\n return issues.map((issue) => {\n const field = issue.path.length > 0 ? issue.path.join('.') : '.'\n const wire: ValidationIssueWire = { field, issue: issue.message }\n if (issue.code) {\n wire.expected = issue.code\n }\n return wire\n })\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The registry of an author's tools plus the JSON-RPC dispatcher. */\nexport class ToolServer {\n readonly server: ServerSpec\n readonly dataStore: DataStore\n readonly #tools = new Map<string, ToolDefinition>()\n readonly #capabilities: string[]\n readonly #sdkVersion?: string\n\n constructor(server: ServerSpec, options: ToolServerOptions = {}) {\n this.server = server\n this.dataStore = options.dataStore ?? new InMemoryDataStore()\n this.#capabilities = [...(options.capabilities ?? [])]\n this.#sdkVersion = options.sdkVersion\n for (const tool of options.tools ?? []) {\n this.register(tool)\n }\n }\n\n /** Register a tool. Throws on a duplicate name. Chainable. */\n register(tool: ToolDefinition): this {\n if (tool.name === GET_TOOL_DATA) {\n throw new ConvilynAuthorError(`tool name \"${GET_TOOL_DATA}\" is reserved`)\n }\n if (this.#tools.has(tool.name)) {\n throw new ConvilynAuthorError(`duplicate tool name: ${tool.name}`)\n }\n this.#tools.set(tool.name, tool)\n return this\n }\n\n /** Names of the registered (author) tools. */\n get toolNames(): string[] {\n return [...this.#tools.keys()]\n }\n\n /** Number of registered (author) tools — the `/health` `tool_count`. */\n get toolCount(): number {\n return this.#tools.size\n }\n\n /** The compiled manifest blueprint for this server. */\n manifest(): ConvilynManifest {\n const tools = [...this.#tools.values()].map((tool) => tool.toSpec())\n return new ConvilynManifest(this.server, {\n tools,\n capabilities: this.#capabilities,\n sdkVersion: this.#sdkVersion,\n })\n }\n\n /**\n * Dispatch one JSON-RPC request. Pure and transport-free: never throws for a\n * tool fault — protocol faults become a JSON-RPC `error`, tool/validation\n * faults become a ToolResult envelope inside `result`.\n */\n async dispatch(request: JSONRPCRequest): Promise<JSONRPCResponse> {\n const id = request.id ?? null\n\n if (request.method !== TOOLS_CALL) {\n return rpcError(id, METHOD_NOT_FOUND, `unsupported method: ${request.method}`)\n }\n\n const params = request.params ?? {}\n const name = params.name\n if (typeof name !== 'string' || name === '') {\n return rpcError(id, INVALID_PARAMS, 'params.name is required')\n }\n\n const args = isRecord(params.arguments) ? params.arguments : {}\n const ctx = createToolContext(this.dataStore, isRecord(params.context) ? params.context : {})\n\n if (name === GET_TOOL_DATA) {\n return this.#dispatchGetToolData(id, args)\n }\n\n const tool = this.#tools.get(name)\n if (!tool) {\n return rpcError(id, METHOD_NOT_FOUND, `unknown tool: ${name}`)\n }\n\n const parsed = tool.inputSchema.safeParse(args)\n if (!parsed.success) {\n const issues = toValidationIssues(parsed.error.issues as ReadonlyArray<ZodIssueLike>)\n return rpcResult(id, validationErrorEnvelope(issues))\n }\n\n try {\n const result = await tool.handler(parsed.data, ctx)\n const envelope = await toWireEnvelope(result, this.dataStore)\n return rpcResult(id, envelope)\n } catch (err) {\n return rpcError(id, INTERNAL_ERROR, errorMessage(err))\n }\n }\n\n async #dispatchGetToolData(\n id: string | number | null,\n args: Record<string, unknown>\n ): Promise<JSONRPCResponse> {\n const refId = args.ref_id\n if (typeof refId !== 'string' || refId === '') {\n return rpcResult(\n id,\n rawToolErrorEnvelope(\n 'INPUT_VALIDATION_ERROR',\n 'get_tool_data requires a string ref_id',\n 'Invalid input: ref_id is required'\n )\n )\n }\n const stored = await this.dataStore.get(refId)\n if (stored === null) {\n return rpcResult(\n id,\n rawToolErrorEnvelope(\n 'DEPENDENCY_NOT_FOUND',\n `no data stored for ref_id ${refId}`,\n `No data for ${refId}`\n )\n )\n }\n return rpcResult(id, rawOkEnvelope(stored, `Retrieved data for ${refId}`))\n }\n}\n","/**\n * Local, offline compliance checks for a {@link ToolServer} — the producer of\n * the {@link ComplianceReport} the `convilyn-author test` command (and the A5\n * local harness) report. No platform calls; nothing leaves the process.\n *\n * Checks are deliberately non-invasive: schemas and the runtime plumbing are\n * exercised, but author tool handlers are NOT blindly invoked (they may have\n * real side effects / external calls). `get_tool_data` is exercised against a\n * value the harness stores itself.\n */\n\nimport type { ToolServer } from './tool-server'\nimport { GET_TOOL_DATA } from './tool-server'\nimport { TOOLS_CALL } from './jsonrpc'\nimport type { ComplianceReport, ComplianceResult } from './types'\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction pass(checkName: string, message: string): ComplianceResult {\n return { passed: true, checkName, message }\n}\n\nfunction fail(checkName: string, message: string): ComplianceResult {\n return { passed: false, checkName, message }\n}\n\nfunction checkServerMetadata(server: ToolServer): ComplianceResult {\n const { name, version, description } = server.server\n if (!name || !version || !description) {\n return fail('server_metadata', 'server name, version, and description must all be non-empty')\n }\n return pass('server_metadata', 'server metadata is complete')\n}\n\nfunction checkToolsExist(server: ToolServer): ComplianceResult {\n return server.toolCount > 0\n ? pass('tools_exist', `server has ${server.toolCount} tool(s)`)\n : fail('tools_exist', 'server has no registered tools')\n}\n\nfunction checkToolSchemas(server: ToolServer): ComplianceResult {\n for (const tool of server.manifest().tools) {\n if (!tool.name || !tool.description) {\n return fail('tool_schemas', `tool \"${tool.name}\" is missing a name or description`)\n }\n if (!isRecord(tool.inputSchema) || tool.inputSchema.type !== 'object') {\n return fail('tool_schemas', `tool \"${tool.name}\" input_schema is not a JSON-Schema object`)\n }\n }\n return pass('tool_schemas', 'all tool schemas are valid')\n}\n\nfunction checkManifestSynth(server: ToolServer): ComplianceResult {\n try {\n const wire = server.manifest().toWire()\n return isRecord(wire)\n ? pass('manifest_synth', 'manifest compiles to a wire object')\n : fail('manifest_synth', 'manifest did not compile to an object')\n } catch (err) {\n return fail('manifest_synth', `manifest synth threw: ${(err as Error).message}`)\n }\n}\n\nasync function checkRefIdPattern(server: ToolServer): Promise<ComplianceResult> {\n const refId = await server.dataStore.store({ __compliance_probe__: true })\n return /^td_[0-9a-f]{12}$/.test(refId)\n ? pass('ref_id_pattern', 'data store returns a td_<12-hex> ref_id')\n : fail('ref_id_pattern', `ref_id \"${refId}\" does not match td_<12-hex>`)\n}\n\nasync function checkGetToolData(server: ToolServer): Promise<ComplianceResult> {\n const refId = await server.dataStore.store({ probe: 1 })\n const response = await server.dispatch({\n jsonrpc: '2.0',\n method: TOOLS_CALL,\n params: { name: GET_TOOL_DATA, arguments: { ref_id: refId } },\n id: 'compliance',\n })\n const result = response.result\n if (isRecord(result) && result.status === 'ok') {\n return pass('get_tool_data', 'built-in get_tool_data resolves a stored ref_id')\n }\n return fail('get_tool_data', 'built-in get_tool_data did not resolve a stored ref_id')\n}\n\n/**\n * Run the local compliance suite against a server, returning a\n * {@link ComplianceReport}. Use {@link allChecksPassed} / {@link failedChecks}\n * (from `./types`) to interpret it.\n */\nexport async function runComplianceChecks(server: ToolServer): Promise<ComplianceReport> {\n const results: ComplianceResult[] = [\n checkServerMetadata(server),\n checkToolsExist(server),\n checkToolSchemas(server),\n checkManifestSynth(server),\n await checkRefIdPattern(server),\n await checkGetToolData(server),\n ]\n return { results }\n}\n","/**\n * Core logic for each `convilyn-author` subcommand, kept transport- and\n * process-free so it is unit-testable: each returns a value (or throws) and the\n * commander action layer (`program.ts`) handles printing + exit codes.\n *\n * `synth` / `dev` / `test` are fully local. `push` submits a server + workflow\n * to the **Developer Portal** (`/api/v1/developers/*`) via {@link ConvilynClient}\n * — the wire contract lives at `docs/contracts/developer_portal/` and the\n * behaviour mirrors the Python SDK's `ConvilynClient.push`. `deploy` /\n * `rollback` / `logs` drive the Convilyn-Hosted Author Runtime\n * (`/developers/runtimes/*`), ported from the Python CLI.\n */\n\nimport { stat } from 'node:fs/promises'\nimport type { Server } from 'node:http'\nimport { loadToolServer } from './load-server'\nimport { loadWorkflowSpec } from './load-workflow'\nimport { ConvilynClient } from '../client'\nimport { serve } from '../http-runtime'\nimport { runComplianceChecks } from '../compliance'\nimport type { ComplianceReport } from '../types'\nimport type { RollbackResponse, RuntimeLogEntry } from '../platform-types'\n\nconst DEFAULT_SERVER_FILE = 'server.js'\nconst DEFAULT_WORKFLOW_FILE = 'workflow.spec.json'\nconst DEFAULT_MANIFEST_OUTPUT = 'convilyn.manifest.json'\n\n/** `synth`: load the server and write its manifest. */\nexport async function runSynth(options: {\n file?: string\n output?: string\n}): Promise<{ path: string; toolCount: number; toolNames: string[] }> {\n const server = await loadToolServer(options.file ?? DEFAULT_SERVER_FILE)\n const manifest = server.manifest()\n const path = await manifest.save(options.output ?? DEFAULT_MANIFEST_OUTPUT)\n return { path, toolCount: manifest.tools.length, toolNames: manifest.tools.map((t) => t.name) }\n}\n\n/** `dev`: load the server and start the local JSON-RPC `/mcp` runtime. */\nexport async function runDev(options: {\n file?: string\n host?: string\n port?: number\n hmacSecret?: string\n}): Promise<Server> {\n const server = await loadToolServer(options.file ?? DEFAULT_SERVER_FILE)\n return serve(server, {\n host: options.host,\n port: options.port,\n hmacSecret: options.hmacSecret,\n // `dev` IS the explicit insecure-local opt-in (mirror of the Python\n // CLI's run(dev=True)). A configured secret still wins — the opt-in\n // never bypasses verification.\n allowInsecure: true,\n })\n}\n\n/** `test`: load the server and run the local compliance suite. */\nexport async function runTest(options: { file?: string }): Promise<ComplianceReport> {\n const server = await loadToolServer(options.file ?? DEFAULT_SERVER_FILE)\n return runComplianceChecks(server)\n}\n\n/** Combined result of a successful `push` (server + workflow submission). */\nexport interface PushResult {\n serverId: string\n serverName: string\n serverStatus: string\n workflowId: string\n workflowSpecId: string\n workflowStatus: string\n}\n\n/**\n * `push`: submit a tool server + workflow to the Developer Portal in one call.\n *\n * Mirrors the Python SDK's `ConvilynClient.push`: synth the manifest → submit\n * the server (registering the caller-hosted `endpoint_url`) → compile the\n * workflow → submit it referencing the new server id. The {@link ConvilynClient}\n * is injectable so this is unit-testable against a fake `fetch` with no network.\n *\n * @throws if `--endpoint-url` is missing, if the server/workflow cannot be\n * loaded, or if the portal rejects a submission (`ConvilynApiError`).\n */\nexport async function runPush(options: {\n file?: string\n workflowFile?: string\n endpointUrl?: string\n client?: ConvilynClient\n}): Promise<PushResult> {\n if (!options.endpointUrl) {\n throw new Error(\n 'push requires --endpoint-url <https://...> — the HTTPS URL where your tool ' +\n 'server is deployed. Use `deploy --hosted` for a Convilyn-hosted server.'\n )\n }\n\n const server = await loadToolServer(options.file ?? DEFAULT_SERVER_FILE)\n const workflow = await loadWorkflowSpec(options.workflowFile ?? DEFAULT_WORKFLOW_FILE)\n const client = options.client ?? new ConvilynClient()\n\n const manifest = server.manifest().toWire()\n const serverResult = await client.submitServer({\n manifest,\n endpoint_url: options.endpointUrl,\n })\n\n const workflowResult = await client.submitWorkflow({\n // CompilableWorkflow.compile() is typed `unknown` (the file loader duck-types\n // both a built WorkflowSpec and a pre-compiled JSON blueprint).\n workflow_spec: workflow.compile() as Record<string, unknown>,\n server_ids: [serverResult.server_id],\n })\n\n return {\n serverId: serverResult.server_id,\n serverName: serverResult.server_name,\n serverStatus: serverResult.status,\n workflowId: workflowResult.workflow_id,\n workflowSpecId: workflowResult.spec_id,\n workflowStatus: workflowResult.status,\n }\n}\n\n/** Result of a successful `deploy --hosted`. */\nexport interface DeployResult {\n runtimeId: string\n endpointUrl: string | null\n status: string\n region: string\n version: number\n workflowId?: string\n workflowIncluded: boolean\n}\n\n/**\n * `deploy --hosted`: hand the server manifest (plus the compiled workflow\n * spec, when the workflow file exists) to the platform, which provisions a\n * sandboxed runtime in Convilyn's cloud (mirror of the Python CLI `deploy`).\n *\n * Without `--hosted` the command errors and points at `push` — BYO\n * deployments stay on `push --endpoint-url` so one subcommand never has two\n * meanings. The workflow file is optional and silently skipped when absent\n * (Python-CLI parity).\n */\nexport async function runDeploy(options: {\n file?: string\n workflowFile?: string\n hosted?: boolean\n region?: string\n client?: ConvilynClient\n}): Promise<DeployResult> {\n if (!options.hosted) {\n throw new Error(\n 'deploy currently requires --hosted. Use ' +\n '`convilyn-author push --endpoint-url <https://...>` for ' +\n 'caller-deployed (BYO) servers.'\n )\n }\n\n const server = await loadToolServer(options.file ?? DEFAULT_SERVER_FILE)\n const manifest = server.manifest().toWire()\n\n const workflowFile = options.workflowFile ?? DEFAULT_WORKFLOW_FILE\n let workflowSpec: Record<string, unknown> | undefined\n if (\n await stat(workflowFile).then(\n () => true,\n () => false\n )\n ) {\n const workflow = await loadWorkflowSpec(workflowFile)\n workflowSpec = workflow.compile() as Record<string, unknown>\n }\n\n const client = options.client ?? new ConvilynClient()\n const result = await client.deployHostedRuntime(manifest, {\n region: options.region ?? 'us-east-1',\n ...(workflowSpec !== undefined ? { workflowSpec } : {}),\n })\n\n return {\n runtimeId: result.runtime_id,\n endpointUrl: result.endpoint_url ?? null,\n status: result.status,\n region: result.region,\n version: result.version,\n ...(result.workflow_id != null ? { workflowId: result.workflow_id } : {}),\n workflowIncluded: workflowSpec !== undefined,\n }\n}\n\n/** `rollback <runtimeId>`: flip a hosted runtime to its previous version. */\nexport async function runRollback(options: {\n runtimeId: string\n client?: ConvilynClient\n}): Promise<RollbackResponse> {\n const client = options.client ?? new ConvilynClient()\n return client.rollbackHostedRuntime(options.runtimeId)\n}\n\n/** `logs <runtimeId>`: fetch recent log lines for a hosted runtime. */\nexport async function runLogs(options: {\n runtimeId: string\n since?: string\n limit?: number\n client?: ConvilynClient\n}): Promise<RuntimeLogEntry[]> {\n const client = options.client ?? new ConvilynClient()\n return client.getHostedRuntimeLogs(options.runtimeId, {\n ...(options.since !== undefined ? { since: options.since } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n })\n}\n","/**\n * Builds the `convilyn-author` commander program. Kept separate from the `bin`\n * entry (`../cli.ts`) so it can be constructed with an injected {@link Printer}\n * and parsed in tests without touching the real process streams.\n *\n * Command cores live in `./commands`; the actions here only translate their\n * return values into printed output + exit codes.\n */\n\nimport { Command } from 'commander'\nimport { VERSION } from '../version'\nimport { ConvilynApiError } from '../errors'\nimport { allChecksPassed } from '../types'\nimport { consolePrinter, type Printer } from './print'\nimport { scaffoldProject } from './scaffold'\nimport { runDeploy, runDev, runLogs, runPush, runRollback, runSynth, runTest } from './commands'\n\nfunction fail(printer: Printer, err: unknown): void {\n printer.err(`error: ${(err as Error).message}`)\n process.exitCode = 1\n}\n\n/** Hosted-runtime error printer: 501/503 get the BYO-fallback hint (Python parity). */\nfunction failHosted(printer: Printer, err: unknown): void {\n if (err instanceof ConvilynApiError && (err.status === 501 || err.status === 503)) {\n printer.err(\n `error: hosted runtime not yet available on this platform (${err.message}). ` +\n 'Use `convilyn-author push --endpoint-url ...` as a BYO fallback.'\n )\n process.exitCode = 1\n return\n }\n fail(printer, err)\n}\n\n/** Construct the CLI program. `printer` defaults to real stdout/stderr. */\nexport function buildProgram(printer: Printer = consolePrinter): Command {\n const program = new Command()\n program\n .name('convilyn-author')\n .description('Author and run Convilyn tool servers.')\n .version(VERSION)\n\n program\n .command('init')\n .description('Scaffold a new tool-server project.')\n .argument('<name>', 'project name (letters, digits, hyphens, underscores)')\n .option('--dir <dir>', 'target directory (default ./<name>)')\n .action(async (name: string, opts: { dir?: string }) => {\n try {\n const result = await scaffoldProject({ name, dir: opts.dir })\n printer.out(`Project created: ${result.path}`)\n printer.out(` ${result.files.join(', ')}`)\n printer.out(` cd ${name} && npm install && npm run build && npx convilyn-author dev`)\n } catch (err) {\n fail(printer, err)\n }\n })\n\n program\n .command('synth')\n .description('Compile the server manifest to JSON.')\n .option('--file <file>', 'built server module (default server.js)')\n .option('--output <output>', 'manifest output path (default convilyn.manifest.json)')\n .action(async (opts: { file?: string; output?: string }) => {\n try {\n const result = await runSynth(opts)\n printer.out(`Found ${result.toolCount} tool(s): ${result.toolNames.join(', ')}`)\n printer.out(`Manifest written: ${result.path}`)\n } catch (err) {\n fail(printer, err)\n }\n })\n\n program\n .command('dev')\n .description('Run the JSON-RPC /mcp server locally.')\n .option('--file <file>', 'built server module (default server.js)')\n .option('--host <host>', 'bind host (default from CONVILYN_HOST)')\n .option('--port <port>', 'bind port (default from CONVILYN_PORT)', (v) => parseInt(v, 10))\n .action(async (opts: { file?: string; host?: string; port?: number }) => {\n try {\n await runDev(opts)\n printer.out('convilyn-author dev: serving /mcp (Ctrl+C to stop)')\n } catch (err) {\n fail(printer, err)\n }\n })\n\n program\n .command('test')\n .description('Run local compliance checks (no platform calls).')\n .option('--file <file>', 'built server module (default server.js)')\n .action(async (opts: { file?: string }) => {\n try {\n const report = await runTest(opts)\n for (const r of report.results) {\n printer.out(` [${r.passed ? 'PASS' : 'FAIL'}] ${r.checkName}: ${r.message}`)\n }\n if (allChecksPassed(report)) {\n printer.out(`All ${report.results.length} checks passed`)\n } else {\n const failed = report.results.filter((r) => !r.passed).length\n printer.err(`${failed} of ${report.results.length} checks failed`)\n process.exitCode = 1\n }\n } catch (err) {\n fail(printer, err)\n }\n })\n\n program\n .command('push')\n .description('Submit a server + workflow to the Developer Portal.')\n .option('--file <file>', 'built server module (default server.js)')\n .option(\n '--workflow-file <file>',\n 'compiled workflow spec or built module (default workflow.spec.json)'\n )\n .option('--endpoint-url <url>', 'HTTPS URL of your deployed server (required)')\n .action(async (opts: { file?: string; workflowFile?: string; endpointUrl?: string }) => {\n try {\n const result = await runPush(opts)\n printer.out(`Server submitted: ${result.serverId} (${result.serverStatus})`)\n printer.out(`Workflow submitted: ${result.workflowId} (${result.workflowStatus})`)\n printer.out('Check verification with the ConvilynClient serverStatus() / workflowStatus().')\n } catch (err) {\n fail(printer, err)\n }\n })\n\n program\n .command('deploy')\n .description('Deploy a tool server to the Convilyn-Hosted Author Runtime.')\n .option('--file <file>', 'built server module (default server.js)')\n .option(\n '--workflow-file <file>',\n 'compiled workflow spec (default workflow.spec.json; optional — skipped when absent)'\n )\n .option('--hosted', 'use the managed runtime (required — BYO uses push)')\n .option('--region <region>', 'AWS region the hosted Lambda is provisioned in', 'us-east-1')\n .action(\n async (opts: { file?: string; workflowFile?: string; hosted?: boolean; region?: string }) => {\n try {\n printer.out(`Deploying to Convilyn-Hosted Runtime in ${opts.region ?? 'us-east-1'}...`)\n const result = await runDeploy(opts)\n printer.out(`Runtime provisioned: ${result.runtimeId} (${result.status})`)\n printer.out(`Endpoint URL: ${result.endpointUrl ?? 'pending (provisioning)'}`)\n if (result.workflowId != null) {\n printer.out(`Workflow registered: ${result.workflowId}`)\n }\n printer.out(\n `Use 'convilyn-author logs ${result.runtimeId}' to follow runtime logs, ` +\n `'convilyn-author rollback ${result.runtimeId}' to revert.`\n )\n } catch (err) {\n failHosted(printer, err)\n }\n }\n )\n\n program\n .command('rollback')\n .description('Roll a hosted runtime back to its previous active version.')\n .argument('<runtimeId>', 'runtime id returned by deploy --hosted')\n .action(async (runtimeId: string) => {\n try {\n printer.out(`Rolling back ${runtimeId}...`)\n const result = await runRollback({ runtimeId })\n printer.out(`Rollback complete: now-active version ${result.version} (${result.status})`)\n } catch (err) {\n fail(printer, err)\n }\n })\n\n program\n .command('logs')\n .description('Fetch recent logs for a hosted runtime.')\n .argument('<runtimeId>', 'runtime id returned by deploy --hosted')\n .option('--since <since>', \"relative window (e.g. '5m', '1h') or ISO-8601 timestamp\")\n .option('--limit <limit>', 'maximum log entries to fetch', (v) => parseInt(v, 10))\n .action(async (runtimeId: string, opts: { since?: string; limit?: number }) => {\n try {\n const entries = await runLogs({ runtimeId, ...opts })\n if (entries.length === 0) {\n printer.out(`No log entries for ${runtimeId} in the requested window.`)\n return\n }\n for (const entry of entries) {\n printer.out(`[${entry.timestamp}] ${entry.level} ${entry.message}`)\n }\n } catch (err) {\n fail(printer, err)\n }\n })\n\n return program\n}\n","#!/usr/bin/env node\n/**\n * `convilyn-author` CLI entry (the package `bin`). Thin by design: it builds the\n * commander program (see `./cli/program`) and parses argv. All logic lives in\n * `./cli/*` so it is unit-testable without spawning a process.\n */\n\nimport { buildProgram } from './cli/program'\n\n// No top-level await: the bin is emitted as CJS (dist/cli.cjs), where TLA is illegal.\nbuildProgram()\n .parseAsync(process.argv)\n .catch((err: unknown) => {\n process.stderr.write(`error: ${(err as Error).message}\\n`)\n process.exitCode = 1\n })\n"]}
1
+ {"version":3,"sources":["../src/version.ts","../src/errors.ts","../src/types.ts","../src/cli/print.ts","../src/cli/scaffold.ts","../src/cli/load-server.ts","../src/workflow.ts","../src/cli/load-workflow.ts","../src/auth.ts","../src/config.ts","../src/client.ts","../src/jsonrpc.ts","../src/http-runtime.ts","../src/tool-server.ts","../src/compliance.ts","../src/cli/commands.ts","../src/cli/program.ts","../src/cli.ts"],"names":["readdir","path","resolve","mkdir","writeFile","join","pathToFileURL","readFile","extname","createHmac","timingSafeEqual","createServer","isRecord","stat","fail","Command"],"mappings":";;;;;;;;;;;AACO,IAAM,OAAA,GAAU,OAAA;;;ACkBvB,IAAM,2BAAA,mBAA8B,MAAA,CAAO,GAAA,CAAI,0CAA0C,CAAA;AAGlF,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA;AAAA,EAE7C,CAAU,2BAA2B,IAAI,IAAA;AAAA,EAEzC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF,CAAA;AA6BO,IAAM,qBAAA,GAAN,cAAoC,mBAAA,CAAoB;AAAA,EACpD,MAAA;AAAA,EAET,WAAA,CAAY,QAAgC,OAAA,EAAiB;AAC3D,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AACF,CAAA;AAQO,IAAM,oBAAA,GAAN,cA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IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AACxB,QAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,mBAAA,EAAsB,SAAS,CAAA,yBAAA,CAA2B,CAAA;AACtE,QAAA;AAAA,MACF;AACA,MAAA,KAAA,MAAW,SAAS,OAAA,EAAS;AAC3B,QAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,CAAA,EAAI,KAAA,CAAM,SAAS,CAAA,EAAA,EAAK,MAAM,KAAK,CAAA,CAAA,EAAI,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,MACpE;AAAA,IACF,SAAS,GAAA,EAAK;AACZ,MAAAA,KAAAA,CAAK,SAAS,GAAG,CAAA;AAAA,IACnB;AAAA,EACF,CAAC,CAAA;AAEH,EAAA,OAAO,OAAA;AACT;;;AC3LA,YAAA,GACG,UAAA,CAAW,OAAA,CAAQ,IAAI,CAAA,CACvB,KAAA,CAAM,CAAC,GAAA,KAAiB;AACvB,EAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,OAAA,EAAW,GAAA,CAAc,OAAO;AAAA,CAAI,CAAA;AACzD,EAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AACrB,CAAC,CAAA","file":"cli.cjs","sourcesContent":["/** The SDK release version (independent of the manifest schema version). */\nexport const VERSION = '0.9.0'\n\n/**\n * The schema version stamped into a compiled manifest's `sdk_version` field —\n * kept in lockstep with the Python / Go author SDKs' manifest format.\n */\nexport const MANIFEST_SDK_VERSION = '1.0.0'\n","/**\n * Typed errors raised by the Author SDK — a faithful port of the Python / Go\n * author SDKs.\n *\n * ConvilynAuthorError base; everything the SDK throws\n * ├── InvalidSignatureError inbound HMAC verification failed\n * ├── ConvilynStartupError server cannot safely start (fail-closed gate)\n * └── ConfirmationInvalidError confirmation-handshake token rejected\n */\n\n/**\n * Well-known brand for {@link ConvilynAuthorError}. `Symbol.for` resolves to the\n * *same* symbol from the global registry regardless of which module instance\n * (ESM vs. CJS) created it, so {@link isConvilynAuthorError} stays reliable even\n * when a process ends up loading both entry points of this package (a classic\n * Node.js dual-package hazard where `instanceof` across the two module graphs\n * can false-negative). Prefer the guard function over `instanceof` unless you\n * can guarantee a single module graph.\n */\nconst CONVILYN_AUTHOR_ERROR_BRAND = Symbol.for('@convilyn/sdk-author.ConvilynAuthorError')\n\n/** Base class for every error the Author SDK throws. */\nexport class ConvilynAuthorError extends Error {\n /** @internal brand marker — see {@link isConvilynAuthorError} */\n readonly [CONVILYN_AUTHOR_ERROR_BRAND] = true\n\n constructor(message: string) {\n super(message)\n this.name = 'ConvilynAuthorError'\n }\n}\n\n/**\n * Reliable `err instanceof ConvilynAuthorError` replacement across module\n * graphs. Use this (not `instanceof`) when the error may have crossed an\n * ESM/CJS boundary — e.g. a dependency `require()`s this package while your\n * own code `import`s it.\n */\nexport function isConvilynAuthorError(err: unknown): err is ConvilynAuthorError {\n return (\n typeof err === 'object' &&\n err !== null &&\n (err as Record<PropertyKey, unknown>)[CONVILYN_AUTHOR_ERROR_BRAND] === true\n )\n}\n\n/** Stable machine-readable reason for an {@link InvalidSignatureError}. */\nexport type InvalidSignatureReason =\n | 'missing_secret'\n | 'missing_header'\n | 'invalid_timestamp'\n | 'timestamp_out_of_range'\n | 'signature_mismatch'\n\n/**\n * Raised when an inbound HMAC signature fails verification. `reason` is a stable\n * machine-readable code; `message` is human-readable and safe to log. Reasons\n * are intentionally coarse to avoid leaking signing details to attackers.\n */\nexport class InvalidSignatureError extends ConvilynAuthorError {\n readonly reason: InvalidSignatureReason\n\n constructor(reason: InvalidSignatureReason, message: string) {\n super(message)\n this.name = 'InvalidSignatureError'\n this.reason = reason\n }\n}\n\n/**\n * Raised when the server cannot safely start — e.g. `serve()` without\n * `CONVILYN_HMAC_SECRET` and without the explicit insecure-local-dev opt-in.\n * Port of the Python / Go `ConvilynStartupError` (fail-closed startup\n * contract).\n */\nexport class ConvilynStartupError extends ConvilynAuthorError {\n constructor(message: string) {\n super(message)\n this.name = 'ConvilynStartupError'\n }\n}\n\n/**\n * Raised when a platform API call (via {@link ConvilynClient}) returns a non-2xx\n * response. `status` is the HTTP status; `body` is the parsed JSON (or text) the\n * server returned.\n */\nexport class ConvilynApiError extends ConvilynAuthorError {\n readonly status: number\n readonly body: unknown\n\n constructor(status: number, message: string, body: unknown) {\n super(message)\n this.name = 'ConvilynApiError'\n this.status = status\n this.body = body\n }\n}\n\n/** Stable machine-readable reason for a {@link ConfirmationInvalidError}. */\nexport type ConfirmationInvalidReason =\n 'malformed' | 'expired' | 'digest_mismatch' | 'signature_mismatch'\n\n/**\n * Raised when a confirmation-handshake token fails verification. `reason` is a\n * stable machine-readable code (maps to the framework's `CONFIRMATION_INVALID`).\n */\nexport class ConfirmationInvalidError extends ConvilynAuthorError {\n readonly reason: ConfirmationInvalidReason\n\n constructor(reason: ConfirmationInvalidReason, message: string) {\n super(message)\n this.name = 'ConfirmationInvalidError'\n this.reason = reason\n }\n}\n","/**\n * Core value types shared across the Author SDK — tool results, error details,\n * data references, and the manifest schema rows. Mirrors the Go SDK's `types.go`\n * and the Python `types.py`. Domain fields are camelCase; the snake_case wire\n * mapping lives in `manifest.ts` (and, later, the JSON-RPC runtime).\n */\n\n/** Reference to data stored in the ToolDataStore (the LLM sees only the summary). */\nexport interface ToolDataRef {\n refId: string\n summary: string\n}\n\n/** Structured error detail for a failed tool execution. */\nexport interface ToolError {\n code: string\n message: string\n details?: Record<string, unknown>\n}\n\n/** Result returned from a tool execution. Build via {@link ToolResult.ok} / `.fail`. */\nexport interface ToolResult {\n success: boolean\n data?: Record<string, unknown>\n error?: ToolError\n executionTimeMs?: number\n /**\n * Optional LLM-facing one-line summary. When set it becomes the wire\n * envelope's required `summary`; otherwise the JSON-RPC runtime derives one.\n * (Added in A3; omitting it preserves the A1 `ok` / `fail` shapes exactly.)\n */\n summary?: string\n}\n\n/** Constructors for {@link ToolResult} (mirrors Python `ToolResult.ok` / `.fail`). */\nexport const ToolResult = {\n ok(data: Record<string, unknown>, summary?: string): ToolResult {\n return summary !== undefined ? { success: true, data, summary } : { success: true, data }\n },\n fail(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n summary?: string\n ): ToolResult {\n const error: ToolError = details ? { code, message, details } : { code, message }\n return summary !== undefined ? { success: false, error, summary } : { success: false, error }\n },\n}\n\n/** Manifest schema for a single tool. */\nexport interface ToolSpec {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n idempotent: boolean\n outputSchema?: Record<string, unknown>\n}\n\n/** Manifest schema for the server section. */\nexport interface ServerSpec {\n name: string\n version: string\n description: string\n mcpServerName?: string\n}\n\n/** One line of a compliance report. */\nexport interface ComplianceResult {\n passed: boolean\n checkName: string\n message: string\n details?: Record<string, unknown>\n}\n\n/** Full report from a local compliance run. */\nexport interface ComplianceReport {\n results: ComplianceResult[]\n}\n\n/** True when every check in the report passed. */\nexport function allChecksPassed(report: ComplianceReport): boolean {\n return report.results.every((result) => result.passed)\n}\n\n/** Just the failing checks of a report. */\nexport function failedChecks(report: ComplianceReport): ComplianceResult[] {\n return report.results.filter((result) => !result.passed)\n}\n","/**\n * A tiny output seam for the CLI so command cores stay testable (inject a\n * capturing {@link Printer} in tests) and the package keeps no raw `console.log`.\n */\n\nexport interface Printer {\n out(line: string): void\n err(line: string): void\n}\n\n/** Default {@link Printer} writing to the real stdout / stderr. */\nexport const consolePrinter: Printer = {\n out: (line) => {\n process.stdout.write(`${line}\\n`)\n },\n err: (line) => {\n process.stderr.write(`${line}\\n`)\n },\n}\n","/**\n * `convilyn-author init` — scaffold a new tool-server project. Pure local file\n * writes; no platform calls. Refuses to write into a non-empty directory.\n *\n * The scaffold authors in TypeScript and builds to `dist/server.js`; the\n * generated `synth` / `dev` / `test` scripts point the CLI at that built module\n * (the CLI loads JS, not TS — no TS runtime is pulled in).\n */\n\nimport { mkdir, readdir, writeFile } from 'node:fs/promises'\nimport { resolve, join } from 'node:path'\nimport { VERSION } from '../version'\n\nconst NAME_RE = /^[a-zA-Z0-9_-]+$/\n\n/** Validate a project name (alphanumeric, hyphen, underscore). */\nexport function isValidProjectName(name: string): boolean {\n return NAME_RE.test(name)\n}\n\nfunction serverTs(name: string): string {\n return `import { defineTool, ToolServer, ToolResult } from '@convilyn/sdk-author'\nimport { z } from 'zod'\n\nconst echo = defineTool({\n name: 'echo',\n description: 'Echo the input text back.',\n input: z.object({ text: z.string().min(1) }),\n idempotent: true,\n handler: (args) => ToolResult.ok({ echoed: args.text }, \\`Echoed \\${args.text.length} chars\\`),\n})\n\nexport const server = new ToolServer(\n { name: '${name}', version: '0.1.0', description: 'A Convilyn tool server.' },\n { tools: [echo] }\n)\n\nexport default server\n`\n}\n\nfunction packageJson(name: string): string {\n return `${JSON.stringify(\n {\n name,\n version: '0.1.0',\n private: true,\n type: 'module',\n scripts: {\n build: 'tsc',\n synth: 'convilyn-author synth --file dist/server.js',\n dev: 'convilyn-author dev --file dist/server.js',\n test: 'convilyn-author test --file dist/server.js',\n },\n dependencies: {\n '@convilyn/sdk-author': `^${VERSION}`,\n zod: '^3.23.0',\n },\n devDependencies: {\n typescript: '^5.7.2',\n },\n },\n null,\n 2\n )}\\n`\n}\n\nconst TSCONFIG = `${JSON.stringify(\n {\n compilerOptions: {\n target: 'ES2022',\n module: 'NodeNext',\n moduleResolution: 'NodeNext',\n outDir: 'dist',\n strict: true,\n skipLibCheck: true,\n declaration: false,\n },\n include: ['server.ts'],\n },\n null,\n 2\n)}\\n`\n\nconst GITIGNORE = `node_modules/\ndist/\nconvilyn.manifest.json\n.env\n`\n\nconst ENV_EXAMPLE = `# Inbound HMAC secret (enables POST /mcp signature verification)\nCONVILYN_HMAC_SECRET=\n# Local dev server port\nCONVILYN_PORT=8080\n# Platform API (used by push/deploy once those land)\nCONVILYN_PLATFORM_URL=https://api.convilyn.corenovus.com\nCONVILYN_API_KEY=\n`\n\nfunction readme(name: string): string {\n return `# ${name}\n\nA Convilyn tool server, scaffolded by \\`convilyn-author init\\`.\n\n## Develop\n\n\\`\\`\\`bash\nnpm install\nnpm run build # server.ts -> dist/server.js\nnpx convilyn-author dev # run the JSON-RPC /mcp server locally\nnpx convilyn-author synth # write convilyn.manifest.json\nnpx convilyn-author test # local compliance checks\n\\`\\`\\`\n\nEdit \\`server.ts\\` to add tools with \\`defineTool\\`.\n`\n}\n\n/** The files {@link scaffoldProject} writes, keyed by their relative path. */\nexport function projectFiles(name: string): Record<string, string> {\n return {\n 'server.ts': serverTs(name),\n 'package.json': packageJson(name),\n 'tsconfig.json': TSCONFIG,\n '.gitignore': GITIGNORE,\n '.env.example': ENV_EXAMPLE,\n 'README.md': readme(name),\n }\n}\n\nasync function isNonEmptyDir(dir: string): Promise<boolean> {\n try {\n const entries = await readdir(dir)\n return entries.length > 0\n } catch {\n return false // does not exist yet\n }\n}\n\n/** Result of {@link scaffoldProject}. */\nexport interface ScaffoldResult {\n path: string\n files: string[]\n}\n\n/**\n * Scaffold a project named `name` into `dir` (default `./<name>`). Throws on an\n * invalid name or a non-empty target directory.\n */\nexport async function scaffoldProject(options: {\n name: string\n dir?: string\n}): Promise<ScaffoldResult> {\n const { name } = options\n if (!isValidProjectName(name)) {\n throw new Error(\n `Invalid project name \"${name}\": use letters, digits, hyphens, underscores only.`\n )\n }\n const path = resolve(options.dir ?? `./${name}`)\n if (await isNonEmptyDir(path)) {\n throw new Error(`Target directory \"${path}\" is not empty — refusing to overwrite.`)\n }\n await mkdir(path, { recursive: true })\n const files = projectFiles(name)\n const written: string[] = []\n for (const [rel, content] of Object.entries(files)) {\n await writeFile(join(path, rel), content, 'utf8')\n written.push(rel)\n }\n return { path, files: written.sort() }\n}\n","/**\n * Locate and load the author's {@link ToolServer} from a built JS module. Used by\n * the `synth` / `dev` / `test` commands.\n *\n * The export is **duck-typed**, never `instanceof`-checked: the CLI binary bundles\n * its own copy of `ToolServer`, while the author's instance comes from *their*\n * installed `@convilyn/sdk-author` — two distinct class identities. We therefore\n * recognise a server by the shape the commands actually use (`server` metadata +\n * `manifest()` + `dispatch()`).\n *\n * The author points at a built `.js`/`.mjs`/`.cjs` module (default `server.js`)\n * exporting the server as the default export or a named `server` export.\n */\n\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { ToolServer } from '../tool-server'\n\nfunction isToolServerLike(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return false\n }\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.manifest === 'function' &&\n typeof candidate.dispatch === 'function' &&\n typeof candidate.server === 'object' &&\n candidate.server !== null\n )\n}\n\nfunction pickServer(mod: Record<string, unknown>): unknown {\n if (isToolServerLike(mod.default)) {\n return mod.default\n }\n if (isToolServerLike(mod.server)) {\n return mod.server\n }\n for (const value of Object.values(mod)) {\n if (isToolServerLike(value)) {\n return value\n }\n }\n return undefined\n}\n\n/**\n * Import `file` and return the {@link ToolServer} it exports. Throws a\n * descriptive error when the module cannot be imported or exports no server.\n */\nexport async function loadToolServer(file: string): Promise<ToolServer> {\n const absolute = resolve(file)\n let mod: Record<string, unknown>\n try {\n mod = (await import(pathToFileURL(absolute).href)) as Record<string, unknown>\n } catch (err) {\n throw new Error(\n `Could not import server module \"${file}\": ${(err as Error).message}. ` +\n `Point --file at a built .js module (e.g. \"npm run build\" then --file dist/server.js).`\n )\n }\n const server = pickServer(mod)\n if (server === undefined) {\n throw new Error(\n `No ToolServer found in \"${file}\". Export it as the default export or as a named \"server\" export.`\n )\n }\n return server as ToolServer\n}\n","/**\n * `WorkflowSpec` — an immutable fluent builder for the portable workflow\n * authoring artifact the platform consumes.\n *\n * Two wire shapes, one method each (single responsibility per contract):\n *\n * - `compile()` emits the snake_case {@link WorkflowBlueprint} — the PUBLIC\n * publish artifact the Developer Portal's `submit_workflow` accepts, in\n * cross-SDK parity with the Python author SDK's `compile()`.\n * - `toExportPayload()` emits the camelCase {@link ExportPayload} — the\n * user_workflows authoring/canvas contract\n * (`docs/contracts/user_workflows/user_workflows_openapi.yaml`), which\n * carries UI-only metadata (positions, notes, canvasLayout) the blueprint\n * deliberately omits.\n *\n * Every `with*` / `add*` / `use*` method returns a NEW `WorkflowSpec` (the\n * receiver is never mutated), matching the project's immutability rule. Contract\n * constraints are enforced client-side so a bad spec fails fast with a clear\n * {@link ConvilynAuthorError} instead of a server 422.\n */\n\nimport { readFile, writeFile } from 'node:fs/promises'\nimport { ConvilynAuthorError } from './errors'\n\n/** Lifecycle visibility of a persisted workflow (set via the platform, not here). */\nexport type Visibility = 'private' | 'public' | 'archived'\n\n/** Provenance of a workflow's fork source. */\nexport type SourceType = 'curated' | 'user' | 'blank'\n\n/** 2D position on the Builder canvas — pure UI metadata, ignored by the agent. */\nexport interface Position {\n x: number\n y: number\n}\n\n/**\n * One tool the agent may call. `toolName` is the\n * `\"server-name:tool_name\"` form (e.g. `\"doc-parser-mcp:extract_text\"`).\n * `position` is UI-only and does not affect execution order.\n */\nexport interface ToolPaletteItem {\n toolName: string\n position: Position\n note?: string\n}\n\n/** Optional Builder-only canvas state. Ignored by the compiler and the agent. */\nexport interface CanvasLayout {\n edges?: Array<{ from: string; to: string }>\n viewport?: { zoom?: number; pan?: Position }\n}\n\n/** The camelCase user_workflows authoring/canvas artifact (`ExportPayload`). */\nexport interface ExportPayload {\n schemaVersion: string\n name: string\n description?: string\n systemPrompt: string\n toolPalette: ToolPaletteItem[]\n canvasLayout?: CanvasLayout\n tags: string[]\n}\n\n/**\n * Public blueprint schema version. The platform's translator is keyed on\n * this so its internal workflow contract can evolve without breaking an\n * already-published author SDK. Mirrors the Python SDK's `PUBLIC_SCHEMA_VERSION`.\n */\nexport const PUBLIC_SCHEMA_VERSION = '1'\n\n/** Public agent-mode knobs an author may set on a blueprint. */\nexport interface BlueprintAgentConfig {\n system_prompt?: string\n max_iterations?: number\n temperature?: number\n}\n\n/** MCP server and tool configuration (\"server:tool\" refs). */\nexport interface BlueprintMcpConfig {\n mcp_servers: string[]\n tools: string[]\n}\n\n/**\n * The compiled PUBLIC publish artifact — snake_case, in cross-SDK parity with\n * the Python author SDK's `WorkflowBlueprint`. This is what the Developer\n * Portal's `submit_workflow` accepts; platform-internal fields (category,\n * platform, prompt-template ids) are injected by the server-side translator.\n */\nexport interface WorkflowBlueprint {\n public_schema_version: string\n spec_id: string\n version: string\n name: string\n description?: string\n keywords?: string[]\n agent_config?: BlueprintAgentConfig\n mcp_config?: BlueprintMcpConfig\n}\n\n/** Cross-SDK alias — the Python SDK names its `compile()` output the same way. */\nexport type CompiledWorkflowSpec = WorkflowBlueprint\n\n// ── contract constraints (user_workflows_openapi.yaml) ───────────────────────\nconst DEFAULT_SCHEMA_VERSION = '1.0'\nconst MAX_NAME = 80\nconst MAX_DESCRIPTION = 500\nconst MAX_SYSTEM_PROMPT = 8000\nconst MAX_TOOLS = 20\nconst MAX_TOOL_NAME = 128\nconst MAX_NOTE = 200\nconst MAX_TAGS = 8\nconst MAX_TAG_LEN = 24\nconst ORIGIN: Position = { x: 0, y: 0 }\n/** Invariant I3: the pause-for-input tool is never allowed in a workflow palette. */\nconst FORBIDDEN_TOOL = 'request_user_input'\n\nconst DEFAULT_VERSION = '1.0.0'\nconst MAX_SPEC_ID = 128\nconst SEMVER_RE = /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/\n\ninterface WorkflowSpecState {\n name: string\n description?: string\n systemPrompt: string\n schemaVersion: string\n specId?: string\n version: string\n tags: string[]\n toolPalette: ToolPaletteItem[]\n canvasLayout?: CanvasLayout\n}\n\nfunction validateName(name: string): void {\n if (name.length < 1 || name.length > MAX_NAME) {\n throw new ConvilynAuthorError(`name must be 1–${MAX_NAME} characters (got ${name.length})`)\n }\n}\n\nfunction validateSpecId(specId: string): void {\n if (specId.length < 1 || specId.length > MAX_SPEC_ID || /\\s/.test(specId)) {\n throw new ConvilynAuthorError(\n `specId must be 1–${MAX_SPEC_ID} characters with no whitespace ` +\n `(the portal expects the \"dev_<developer-id>.<name>\" namespace)`\n )\n }\n}\n\nfunction validateVersion(version: string): void {\n if (!SEMVER_RE.test(version)) {\n throw new ConvilynAuthorError(`version must be valid semver (e.g. \"1.0.0\"; got \"${version}\")`)\n }\n}\n\nfunction validateDescription(description: string): void {\n if (description.length > MAX_DESCRIPTION) {\n throw new ConvilynAuthorError(`description must be ≤ ${MAX_DESCRIPTION} characters`)\n }\n}\n\nfunction validateSystemPrompt(systemPrompt: string): void {\n if (systemPrompt.length > MAX_SYSTEM_PROMPT) {\n throw new ConvilynAuthorError(`systemPrompt must be ≤ ${MAX_SYSTEM_PROMPT} characters`)\n }\n}\n\nfunction validateTag(tag: string): void {\n if (tag.length < 1 || tag.length > MAX_TAG_LEN) {\n throw new ConvilynAuthorError(`tag \"${tag}\" must be 1–${MAX_TAG_LEN} characters`)\n }\n}\n\nfunction validateTags(tags: string[]): void {\n if (tags.length > MAX_TAGS) {\n throw new ConvilynAuthorError(`at most ${MAX_TAGS} tags are allowed (got ${tags.length})`)\n }\n tags.forEach(validateTag)\n}\n\nfunction toolKey(toolName: string): string {\n // The forbidden tool may arrive bare or fully-qualified (\"server:request_user_input\").\n const parts = toolName.split(':')\n return parts[parts.length - 1] ?? toolName\n}\n\nfunction validateToolName(toolName: string): void {\n if (toolName.length < 1 || toolName.length > MAX_TOOL_NAME) {\n throw new ConvilynAuthorError(`toolName must be 1–${MAX_TOOL_NAME} characters`)\n }\n if (toolKey(toolName) === FORBIDDEN_TOOL) {\n throw new ConvilynAuthorError(\n `tool \"${FORBIDDEN_TOOL}\" is not permitted in a workflow palette ` +\n `(the agent cannot pause mid-execution)`\n )\n }\n}\n\n/** Immutable builder for a portable workflow spec. */\nexport class WorkflowSpec {\n #state: WorkflowSpecState\n\n constructor(name: string, options: { specId?: string; version?: string } = {}) {\n validateName(name)\n if (options.specId != null) {\n validateSpecId(options.specId)\n }\n const version = options.version ?? DEFAULT_VERSION\n validateVersion(version)\n this.#state = {\n name,\n systemPrompt: '',\n schemaVersion: DEFAULT_SCHEMA_VERSION,\n specId: options.specId,\n version,\n tags: [],\n toolPalette: [],\n }\n }\n\n #cloneWith(patch: Partial<WorkflowSpecState>): WorkflowSpec {\n const next = new WorkflowSpec(this.#state.name)\n next.#state = {\n ...this.#state,\n ...patch,\n tags: [...(patch.tags ?? this.#state.tags)],\n toolPalette: [...(patch.toolPalette ?? this.#state.toolPalette)],\n }\n return next\n }\n\n // ── read-only accessors (return copies to preserve immutability) ──────────\n get name(): string {\n return this.#state.name\n }\n get description(): string | undefined {\n return this.#state.description\n }\n get systemPrompt(): string {\n return this.#state.systemPrompt\n }\n get schemaVersion(): string {\n return this.#state.schemaVersion\n }\n get specId(): string | undefined {\n return this.#state.specId\n }\n get version(): string {\n return this.#state.version\n }\n get tags(): readonly string[] {\n return [...this.#state.tags]\n }\n get toolPalette(): readonly ToolPaletteItem[] {\n return this.#state.toolPalette.map((item) => ({ ...item, position: { ...item.position } }))\n }\n get canvasLayout(): CanvasLayout | undefined {\n return this.#state.canvasLayout\n }\n\n // ── builder methods ───────────────────────────────────────────────────────\n withName(name: string): WorkflowSpec {\n validateName(name)\n return this.#cloneWith({ name })\n }\n\n withDescription(description: string): WorkflowSpec {\n validateDescription(description)\n return this.#cloneWith({ description })\n }\n\n withSystemPrompt(systemPrompt: string): WorkflowSpec {\n validateSystemPrompt(systemPrompt)\n return this.#cloneWith({ systemPrompt })\n }\n\n withSchemaVersion(schemaVersion: string): WorkflowSpec {\n return this.#cloneWith({ schemaVersion })\n }\n\n /** Set the portal spec id (`dev_<developer-id>.<name>` namespace). */\n withSpecId(specId: string): WorkflowSpec {\n validateSpecId(specId)\n return this.#cloneWith({ specId })\n }\n\n /** Set the blueprint semver version (default `1.0.0`). */\n withVersion(version: string): WorkflowSpec {\n validateVersion(version)\n return this.#cloneWith({ version })\n }\n\n /** Replace the tag set. */\n withTags(tags: string[]): WorkflowSpec {\n validateTags(tags)\n return this.#cloneWith({ tags: [...tags] })\n }\n\n /** Append a tag (no-op if already present). */\n addTag(tag: string): WorkflowSpec {\n validateTag(tag)\n if (this.#state.tags.includes(tag)) {\n return this.#cloneWith({})\n }\n const tags = [...this.#state.tags, tag]\n validateTags(tags)\n return this.#cloneWith({ tags })\n }\n\n /**\n * Add (or replace, by `toolName`) one tool on the palette. Rejects the\n * `request_user_input` tool (invariant I3) and palettes larger than\n * {@link MAX_TOOLS}.\n */\n addTool(toolName: string, options: { position?: Position; note?: string } = {}): WorkflowSpec {\n validateToolName(toolName)\n if (options.note != null && options.note.length > MAX_NOTE) {\n throw new ConvilynAuthorError(`tool note must be ≤ ${MAX_NOTE} characters`)\n }\n const item: ToolPaletteItem = {\n toolName,\n position: options.position ? { ...options.position } : { ...ORIGIN },\n ...(options.note != null ? { note: options.note } : {}),\n }\n const existing = this.#state.toolPalette.findIndex((entry) => entry.toolName === toolName)\n const toolPalette =\n existing >= 0\n ? this.#state.toolPalette.map((entry, index) => (index === existing ? item : entry))\n : [...this.#state.toolPalette, item]\n if (toolPalette.length > MAX_TOOLS) {\n throw new ConvilynAuthorError(`at most ${MAX_TOOLS} tools are allowed`)\n }\n return this.#cloneWith({ toolPalette })\n }\n\n /** Add several tools by name (default canvas position), de-duplicated. */\n useTools(...toolNames: string[]): WorkflowSpec {\n return toolNames.reduce<WorkflowSpec>((spec, toolName) => spec.addTool(toolName), this)\n }\n\n withCanvasLayout(canvasLayout: CanvasLayout): WorkflowSpec {\n return this.#cloneWith({ canvasLayout })\n }\n\n // ── compile / serialize ───────────────────────────────────────────────────\n /**\n * The PUBLIC publish blueprint (snake_case; Python-SDK parity). This is the\n * shape `submitWorkflow` / `convilyn-author push` send to the Developer\n * Portal. Requires a `specId` (constructor option or {@link withSpecId}).\n *\n * Mirrors the Python SDK's `exclude_none` semantics: `agent_config` is\n * emitted only when a systemPrompt is set, `mcp_config` only when the\n * palette is non-empty. UI-only metadata (positions, notes, canvasLayout)\n * is deliberately NOT emitted — the portal's blueprint schema rejects\n * unknown fields; that data belongs to {@link toExportPayload}.\n */\n compile(): WorkflowBlueprint {\n const specId = this.#state.specId\n if (specId == null) {\n throw new ConvilynAuthorError(\n 'compile() requires a specId — pass it to the constructor ' +\n '(new WorkflowSpec(name, { specId })) or call withSpecId(). ' +\n 'The Developer Portal expects the \"dev_<developer-id>.<name>\" namespace.'\n )\n }\n const blueprint: WorkflowBlueprint = {\n public_schema_version: PUBLIC_SCHEMA_VERSION,\n spec_id: specId,\n version: this.#state.version,\n name: this.#state.name,\n keywords: [...this.#state.tags],\n }\n if (this.#state.description != null) {\n blueprint.description = this.#state.description\n }\n if (this.#state.systemPrompt !== '') {\n blueprint.agent_config = { system_prompt: this.#state.systemPrompt }\n }\n if (this.#state.toolPalette.length > 0) {\n const tools = this.#state.toolPalette.map((item) => item.toolName)\n const servers = [\n ...new Set(\n tools\n .filter((toolName) => toolName.includes(':'))\n .map((toolName) => toolName.split(':')[0] as string)\n ),\n ]\n blueprint.mcp_config = { mcp_servers: servers, tools }\n }\n return blueprint\n }\n\n /** The compiled blueprint serialised as 2-space-indented JSON. */\n compileJson(): string {\n return JSON.stringify(this.compile(), null, 2)\n }\n\n /** Write the compiled blueprint to a JSON file (default `workflow.spec.json`). */\n async save(path = 'workflow.spec.json'): Promise<string> {\n await writeFile(path, this.compileJson(), 'utf8')\n return path\n }\n\n /**\n * The camelCase user_workflows `ExportPayload` (canvas/authoring contract).\n * Carries the UI-only metadata (positions, notes, canvasLayout) that the\n * publish blueprint omits.\n */\n toExportPayload(): ExportPayload {\n const payload: ExportPayload = {\n schemaVersion: this.#state.schemaVersion,\n name: this.#state.name,\n systemPrompt: this.#state.systemPrompt,\n toolPalette: this.#state.toolPalette.map((item) => ({\n toolName: item.toolName,\n position: { ...item.position },\n ...(item.note != null ? { note: item.note } : {}),\n })),\n tags: [...this.#state.tags],\n }\n if (this.#state.description != null) {\n payload.description = this.#state.description\n }\n if (this.#state.canvasLayout != null) {\n payload.canvasLayout = this.#state.canvasLayout\n }\n return payload\n }\n\n /** Rebuild a {@link WorkflowSpec} from a user_workflows `ExportPayload`. */\n static fromExportPayload(payload: ExportPayload): WorkflowSpec {\n let spec = new WorkflowSpec(payload.name)\n .withSystemPrompt(payload.systemPrompt ?? '')\n .withSchemaVersion(payload.schemaVersion ?? DEFAULT_SCHEMA_VERSION)\n .withTags(payload.tags ?? [])\n if (payload.description != null) {\n spec = spec.withDescription(payload.description)\n }\n if (payload.canvasLayout != null) {\n spec = spec.withCanvasLayout(payload.canvasLayout)\n }\n for (const item of payload.toolPalette ?? []) {\n spec = spec.addTool(item.toolName, {\n position: item.position,\n ...(item.note != null ? { note: item.note } : {}),\n })\n }\n return spec\n }\n\n /**\n * Rebuild a {@link WorkflowSpec} from a publish blueprint. Lossy for canvas\n * metadata by design — that data lives in the `ExportPayload` contract.\n */\n static fromBlueprint(blueprint: WorkflowBlueprint): WorkflowSpec {\n let spec = new WorkflowSpec(blueprint.name, {\n specId: blueprint.spec_id,\n ...(blueprint.version != null ? { version: blueprint.version } : {}),\n })\n .withSystemPrompt(blueprint.agent_config?.system_prompt ?? '')\n .withTags(blueprint.keywords ?? [])\n if (blueprint.description != null) {\n spec = spec.withDescription(blueprint.description)\n }\n for (const toolName of blueprint.mcp_config?.tools ?? []) {\n spec = spec.addTool(toolName)\n }\n return spec\n }\n\n /**\n * Parse a spec from a JSON string. Shape-sniffs: objects carrying `spec_id`\n * or `public_schema_version` parse as a blueprint; anything else as an\n * `ExportPayload` — so `push --workflow-file` accepts both file formats.\n */\n static fromJson(data: string): WorkflowSpec {\n const parsed: unknown = JSON.parse(data)\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new ConvilynAuthorError('workflow spec JSON must be an object')\n }\n if ('spec_id' in parsed || 'public_schema_version' in parsed) {\n return WorkflowSpec.fromBlueprint(parsed as WorkflowBlueprint)\n }\n return WorkflowSpec.fromExportPayload(parsed as ExportPayload)\n }\n\n /** Read a saved spec from a JSON file (default `workflow.spec.json`). */\n static async load(path = 'workflow.spec.json'): Promise<WorkflowSpec> {\n return WorkflowSpec.fromJson(await readFile(path, 'utf8'))\n }\n}\n","/**\n * Locate and load the author's {@link WorkflowSpec} for the `push` command.\n *\n * Two shapes are accepted, mirroring how authors persist a spec:\n * - a compiled `.json` file written by `WorkflowSpec.save()` — loaded via\n * `WorkflowSpec.load()`;\n * - a built `.js`/`.mjs`/`.cjs` module exporting a `WorkflowSpec` as its\n * default or a named `workflow` export — duck-typed, never\n * `instanceof`-checked, because the CLI binary bundles its own copy of\n * `WorkflowSpec` while the author's instance comes from *their* installed\n * `@convilyn/sdk-author` (two distinct class identities). This matches the\n * `loadToolServer` contract for the server side.\n */\n\nimport { extname, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { WorkflowSpec } from '../workflow'\n\n/** The minimal surface `push` needs from a loaded workflow. */\nexport interface CompilableWorkflow {\n readonly name: string\n compile(): unknown\n}\n\nfunction isWorkflowSpecLike(value: unknown): value is CompilableWorkflow {\n if (typeof value !== 'object' || value === null) {\n return false\n }\n const candidate = value as Record<string, unknown>\n return typeof candidate.compile === 'function' && typeof candidate.name === 'string'\n}\n\nfunction pickWorkflow(mod: Record<string, unknown>): CompilableWorkflow | undefined {\n if (isWorkflowSpecLike(mod.default)) {\n return mod.default\n }\n if (isWorkflowSpecLike(mod.workflow)) {\n return mod.workflow\n }\n for (const value of Object.values(mod)) {\n if (isWorkflowSpecLike(value)) {\n return value\n }\n }\n return undefined\n}\n\n/**\n * Load the {@link WorkflowSpec} at `file`. A `.json` file is parsed as a\n * compiled spec; any other extension is imported as a built module. Throws a\n * descriptive error when the file cannot be loaded or exports no workflow.\n */\nexport async function loadWorkflowSpec(file: string): Promise<CompilableWorkflow> {\n const absolute = resolve(file)\n\n if (extname(absolute).toLowerCase() === '.json') {\n try {\n return await WorkflowSpec.load(absolute)\n } catch (err) {\n throw new Error(\n `Could not load workflow spec \"${file}\": ${(err as Error).message}. ` +\n `Point --workflow-file at a compiled spec JSON (from WorkflowSpec.save()) ` +\n `or a built .js module that exports a WorkflowSpec.`\n )\n }\n }\n\n let mod: Record<string, unknown>\n try {\n mod = (await import(pathToFileURL(absolute).href)) as Record<string, unknown>\n } catch (err) {\n throw new Error(\n `Could not import workflow module \"${file}\": ${(err as Error).message}. ` +\n `Point --workflow-file at a built .js module (e.g. \"npm run build\" then ` +\n `--workflow-file dist/workflow.js) or a compiled .spec.json.`\n )\n }\n const workflow = pickWorkflow(mod)\n if (workflow === undefined) {\n throw new Error(\n `No WorkflowSpec found in \"${file}\". Export it as the default export or as a named \"workflow\" export.`\n )\n }\n return workflow\n}\n","/**\n * Inbound HMAC verification for calls from the Convilyn gateway, plus the\n * matching signer. Mirrors the gateway's `mcp_gateway/hmac_signer.py` and the\n * Python / Go author SDKs **byte-for-byte**, so a TS-authored server is\n * interchangeable behind the same gateway.\n *\n * Wire format:\n * - `x-convilyn-signature` — HMAC-SHA256 hex digest\n * - `x-convilyn-timestamp` — Unix seconds (integer string)\n * - `x-convilyn-server-id` — server name, audit-only (NOT in the signed payload)\n *\n * Signed payload = `<timestamp>` bytes + `.` + raw body bytes. Comparison is\n * constant-time; a timestamp tolerance window defends against replay.\n *\n * This is a public author capability: a server using its own HTTP framework\n * (instead of the SDK's runtime) calls {@link verifySignature} to reject forged\n * requests.\n */\n\nimport { createHmac, timingSafeEqual } from 'node:crypto'\nimport { InvalidSignatureError } from './errors'\n\n/** HMAC header names (lowercase; match the gateway's signer). */\nexport const SIGNATURE_HEADER = 'x-convilyn-signature'\nexport const TIMESTAMP_HEADER = 'x-convilyn-timestamp'\nexport const SERVER_ID_HEADER = 'x-convilyn-server-id'\n\n/** Default replay window (seconds) vs the gateway clock. */\nexport const DEFAULT_HMAC_TOLERANCE_SECONDS = 300\n\n/**\n * Body accepted by the signer / verifier. The gateway signs the **raw body\n * bytes**, so a binary or non-UTF-8 body MUST be passed as `Uint8Array` — a\n * lossy-decoded `string` re-encodes as UTF-8 and will not reproduce the digest\n * (the request is rejected, never falsely accepted).\n */\nexport type RequestBody = string | Uint8Array\n\nfunction expectedSignature(secret: string, timestamp: string, body: RequestBody): string {\n return createHmac('sha256', secret).update(timestamp).update('.').update(body).digest('hex')\n}\n\n/**\n * Produce the `{ signature, timestamp }` pair for an outbound request, mirroring\n * the gateway's signer. Useful for tests and for clients calling a\n * developer-hosted server directly. `unixSeconds` is truncated to an integer.\n */\nexport function signRequest(\n secret: string,\n body: RequestBody,\n unixSeconds: number\n): { signature: string; timestamp: string } {\n const timestamp = String(Math.trunc(unixSeconds))\n return { signature: expectedSignature(secret, timestamp, body), timestamp }\n}\n\n/** Tunables for {@link verifySignature}. */\nexport interface VerifyOptions {\n /** Max clock skew (seconds) vs the gateway; `<= 0` uses the default 300. */\n toleranceSeconds?: number\n /** Override \"now\" (Unix seconds) for tests; defaults to the real clock. */\n now?: () => number\n}\n\nfunction constantTimeEqual(a: string, b: string): boolean {\n const aBuf = Buffer.from(a)\n const bBuf = Buffer.from(b)\n // timingSafeEqual throws on unequal length; a wrong-length digest is simply\n // not equal. The expected digest is a fixed 64-hex string, so the length\n // check leaks nothing useful.\n if (aBuf.length !== bBuf.length) {\n return false\n }\n return timingSafeEqual(aBuf, bBuf)\n}\n\n/**\n * Verify an inbound HMAC signature; throw {@link InvalidSignatureError} on any\n * failure (missing secret/headers, malformed or out-of-tolerance timestamp, or\n * digest mismatch). Header keys must be lowercased.\n */\nexport function verifySignature(\n secret: string,\n body: RequestBody,\n headers: Record<string, string | undefined>,\n options: VerifyOptions = {}\n): void {\n const tolerance =\n options.toleranceSeconds != null && options.toleranceSeconds > 0\n ? options.toleranceSeconds\n : DEFAULT_HMAC_TOLERANCE_SECONDS\n const now = options.now ?? (() => Math.floor(Date.now() / 1000))\n\n if (!secret) {\n throw new InvalidSignatureError('missing_secret', 'HMAC secret is not configured on the server')\n }\n\n const signature = headers[SIGNATURE_HEADER]\n const timestamp = headers[TIMESTAMP_HEADER]\n if (!signature || !timestamp) {\n throw new InvalidSignatureError(\n 'missing_header',\n 'Missing X-Convilyn-Signature or X-Convilyn-Timestamp'\n )\n }\n\n if (!/^[+-]?\\d+$/.test(timestamp)) {\n throw new InvalidSignatureError(\n 'invalid_timestamp',\n 'X-Convilyn-Timestamp must be an integer Unix-seconds value'\n )\n }\n const tsValue = Number(timestamp)\n\n if (Math.abs(now() - tsValue) > tolerance) {\n throw new InvalidSignatureError(\n 'timestamp_out_of_range',\n 'Request timestamp outside acceptable tolerance window'\n )\n }\n\n const expected = expectedSignature(secret, timestamp, body)\n if (!constantTimeEqual(expected, signature)) {\n throw new InvalidSignatureError(\n 'signature_mismatch',\n 'Signature did not match expected HMAC-SHA256 digest'\n )\n }\n}\n","/**\n * Environment-driven SDK configuration for a tool server. Port of the Go\n * `SDKConfig` / Python frozen `SDKConfig`. Read it with {@link SDKConfig.fromEnv};\n * construct directly (with explicit options) in tests.\n */\n\nimport { DEFAULT_HMAC_TOLERANCE_SECONDS } from './auth'\n\n/** Construction options for {@link SDKConfig}; each falls back to a default. */\nexport interface SDKConfigOptions {\n serverHost?: string\n serverPort?: number\n logLevel?: string\n awsRegion?: string\n dynamodbEndpoint?: string\n toolDataTable?: string\n environment?: string\n apiKey?: string\n platformUrl?: string\n hmacSecret?: string\n hmacToleranceSeconds?: number\n /** Secret for minting / verifying confirmation-handshake tokens. */\n toolConfirmationSecret?: string\n /** Whether the process runs in AWS Lambda (set by {@link SDKConfig.fromEnv}). */\n lambda?: boolean\n}\n\ntype EnvLike = Record<string, string | undefined>\n\nfunction envOr(env: EnvLike, key: string, fallback: string): string {\n const value = env[key]\n return value !== undefined && value !== '' ? value : fallback\n}\n\nfunction envIntOr(env: EnvLike, key: string, fallback: number): number {\n const value = env[key]\n if (value !== undefined && value !== '') {\n const parsed = Number(value)\n if (Number.isInteger(parsed)) {\n return parsed\n }\n }\n return fallback\n}\n\n/** Immutable SDK configuration. */\nexport class SDKConfig {\n readonly serverHost: string\n readonly serverPort: number\n readonly logLevel: string\n readonly awsRegion: string\n readonly dynamodbEndpoint: string\n readonly toolDataTable: string\n readonly environment: string\n readonly apiKey: string\n readonly platformUrl: string\n readonly hmacSecret: string\n readonly hmacToleranceSeconds: number\n readonly toolConfirmationSecret: string\n readonly #lambda: boolean\n\n constructor(options: SDKConfigOptions = {}) {\n this.serverHost = options.serverHost ?? '127.0.0.1'\n this.serverPort = options.serverPort ?? 8080\n this.logLevel = options.logLevel ?? 'INFO'\n this.awsRegion = options.awsRegion ?? 'ap-northeast-1'\n this.dynamodbEndpoint = options.dynamodbEndpoint ?? ''\n this.toolDataTable = options.toolDataTable ?? 'tool-data'\n this.environment = options.environment ?? 'local'\n this.apiKey = options.apiKey ?? ''\n this.platformUrl = options.platformUrl ?? 'https://api.convilyn.corenovus.com'\n this.hmacSecret = options.hmacSecret ?? ''\n this.hmacToleranceSeconds = options.hmacToleranceSeconds ?? DEFAULT_HMAC_TOLERANCE_SECONDS\n this.toolConfirmationSecret = options.toolConfirmationSecret ?? ''\n this.#lambda = options.lambda ?? false\n }\n\n /** True when running in AWS Lambda. */\n get isLambda(): boolean {\n return this.#lambda\n }\n\n /** True for a local/dev environment (relaxes HMAC). */\n get isLocal(): boolean {\n if (this.environment === 'local') {\n return true\n }\n return !this.#lambda && (this.serverHost === '127.0.0.1' || this.serverHost === 'localhost')\n }\n\n /** Load configuration from environment variables, falling back to defaults. */\n static fromEnv(env: EnvLike = typeof process !== 'undefined' ? process.env : {}): SDKConfig {\n return new SDKConfig({\n serverHost: envOr(env, 'CONVILYN_HOST', '127.0.0.1'),\n serverPort: envIntOr(env, 'CONVILYN_PORT', 8080),\n logLevel: envOr(env, 'CONVILYN_LOG_LEVEL', 'INFO'),\n awsRegion: envOr(env, 'AWS_REGION', 'ap-northeast-1'),\n dynamodbEndpoint: envOr(env, 'DYNAMODB_ENDPOINT', ''),\n toolDataTable: envOr(env, 'TOOL_DATA_TABLE', 'tool-data'),\n environment: envOr(env, 'CONVILYN_ENVIRONMENT', 'local'),\n apiKey: envOr(env, 'CONVILYN_API_KEY', ''),\n platformUrl: envOr(env, 'CONVILYN_PLATFORM_URL', 'https://api.convilyn.corenovus.com'),\n hmacSecret: envOr(env, 'CONVILYN_HMAC_SECRET', ''),\n hmacToleranceSeconds: envIntOr(\n env,\n 'CONVILYN_HMAC_TOLERANCE_SECONDS',\n DEFAULT_HMAC_TOLERANCE_SECONDS\n ),\n toolConfirmationSecret: envOr(env, 'CONVILYN_TOOL_CONFIRMATION_SECRET', ''),\n lambda: Boolean(env['AWS_LAMBDA_FUNCTION_NAME']),\n })\n }\n}\n","/**\n * `ConvilynClient` — a fetch-based client for the **Developer Portal**\n * (`/api/v1/developers/*`), the platform's third-party author/publish surface.\n *\n * This is the TypeScript counterpart of the Python `convilyn_sdk.ConvilynClient`\n * (`sdk/author-python/src/convilyn_sdk/client.py`): the author BUILDS a tool\n * server + workflow spec locally (`ToolServer`, `WorkflowSpec`,\n * `runComplianceChecks`), then INTEGRATES its own artifacts by registering them\n * through the portal:\n *\n * POST /developers/register — mint a `cvl_` developer key (no auth)\n * POST /developers/servers — submit a tool-server manifest\n * GET /developers/servers — list\n * GET /developers/servers/{id}/status — verification status\n * POST /developers/servers/{id}/test — sandbox test\n * DELETE /developers/servers/{id} — deactivate\n * POST /developers/workflows — submit a compiled workflow spec\n * GET /developers/workflows — list\n * GET /developers/workflows/{id}/status — status\n * POST /developers/workflows/{id}/test — sandbox test\n * DELETE /developers/workflows/{id} — deactivate\n * POST /developers/runtimes/hosted — deploy to the hosted author runtime\n * POST /developers/runtimes/{id}/rollback — flip to the previous version\n * GET /developers/runtimes/{id}/logs — recent runtime log lines\n *\n * Auth: `Authorization: Bearer <cvl_ developer key>`, read from\n * `CONVILYN_API_KEY` (`config.ts`). This SDK deliberately does NOT call the\n * first-party console surfaces (`/user_workflows/*`, `/mcp/tools/catalog`) — those\n * are JWT/session endpoints owned by the web UI, not an author-publishing API.\n * Response bodies are snake_case, matching the platform's Developer Portal\n * API.\n */\n\nimport { SDKConfig } from './config'\nimport { ConvilynApiError, ConvilynAuthorError } from './errors'\nimport type {\n DeployHostedResponse,\n DeveloperRegisterRequest,\n DeveloperRegisterResponse,\n DeveloperServer,\n RollbackResponse,\n RuntimeLogEntry,\n ServerStatusResponse,\n ServerSubmitRequest,\n ServerSubmitResponse,\n TestRunResponse,\n WorkflowListItem,\n WorkflowStatusResponse,\n WorkflowSubmitRequest,\n WorkflowSubmitResponse,\n WorkflowTestResponse,\n} from './platform-types'\n\n/** The subset of `fetch` the client uses (so a fake can be injected in tests). */\nexport type FetchLike = (\n url: string,\n init?: { method?: string; headers?: Record<string, string>; body?: string }\n) => Promise<{\n ok: boolean\n status: number\n json(): Promise<unknown>\n text(): Promise<string>\n}>\n\n/** Options for {@link ConvilynClient}; unset fields fall back to {@link SDKConfig}. */\nexport interface ConvilynClientOptions {\n /** Full API base incl. `/api/v1`; defaults to `${platformUrl}/api/v1`. */\n baseUrl?: string\n /** `cvl_` developer key; defaults to `CONVILYN_API_KEY`. */\n apiKey?: string\n /** Injected `fetch` (defaults to the global). */\n fetch?: FetchLike\n config?: SDKConfig\n}\n\nfunction withApiV1(platformUrl: string): string {\n const trimmed = platformUrl.replace(/\\/+$/, '')\n return trimmed.endsWith('/api/v1') ? trimmed : `${trimmed}/api/v1`\n}\n\n/** The consumer data-plane key prefix — NOT an author/developer-portal token. */\nconst CONSUMER_KEY_PREFIX = 'ck_' // pragma: allowlist secret\n\n/** True when `key` is a consumer data-plane key pasted in by mistake. */\nfunction isConsumerKey(key: string): boolean {\n return key.startsWith(CONSUMER_KEY_PREFIX)\n}\n\n/** Mask a secret for safe display: `ck_a…9f` (or `***` when too short). */\nfunction maskKey(key: string): string {\n return key.length <= 8 ? '***' : `${key.slice(0, 4)}…${key.slice(-2)}`\n}\n\n/** Fetch-based client for the Developer Portal author/publish endpoints. */\nexport class ConvilynClient {\n readonly baseUrl: string\n #apiKey: string\n readonly #fetch: FetchLike\n\n constructor(options: ConvilynClientOptions = {}) {\n const config = options.config ?? SDKConfig.fromEnv()\n this.baseUrl = options.baseUrl ?? withApiV1(config.platformUrl)\n this.#apiKey = options.apiKey ?? config.apiKey\n // Reject a consumer ck_ key pasted into the Author SDK up front with a\n // precise error, instead of the developer portal answering with an opaque\n // 401 later. An empty key is fine — register() mints a cvl_ one. Any other\n // prefix is accepted (forward-compat). Mirror of the consumer SDKs' inverse\n // guard (see consumer-ts auth.ts).\n if (this.#apiKey && isConsumerKey(this.#apiKey)) {\n throw new ConvilynAuthorError(\n `${maskKey(this.#apiKey)} looks like a Convilyn consumer API key (\"${CONSUMER_KEY_PREFIX}\"), ` +\n `not an Author SDK / developer-portal token. The Author SDK authenticates with a ` +\n `cvl_ developer key — call register() to mint one, or set CONVILYN_API_KEY to your ` +\n `cvl_ key. (Consumer keys call the data-plane API; they do not publish workflows / tools.)`\n )\n }\n this.#fetch = options.fetch ?? (globalThis.fetch as unknown as FetchLike)\n }\n\n /** The `cvl_` developer key currently in use (empty until set or registered). */\n get apiKey(): string {\n return this.#apiKey\n }\n\n #headers(auth: boolean): Record<string, string> {\n const headers: Record<string, string> = { 'content-type': 'application/json' }\n if (auth) {\n if (!this.#apiKey) {\n throw new ConvilynAuthorError(\n 'No developer API key set. Provide `apiKey`, set CONVILYN_API_KEY to a ' +\n 'cvl_ developer key, or call register() first.'\n )\n }\n headers.authorization = `Bearer ${this.#apiKey}`\n }\n return headers\n }\n\n async #request<T>(method: string, path: string, body?: unknown, auth = true): Promise<T> {\n const res = await this.#fetch(`${this.baseUrl}${path}`, {\n method,\n headers: this.#headers(auth),\n body: body !== undefined ? JSON.stringify(body) : undefined,\n })\n if (!res.ok) {\n let parsed: unknown\n try {\n parsed = await res.json()\n } catch {\n parsed = undefined\n }\n throw new ConvilynApiError(\n res.status,\n `${method} ${path} failed (HTTP ${res.status})`,\n parsed\n )\n }\n if (res.status === 204) {\n return undefined as T\n }\n return (await res.json()) as T\n }\n\n // ── Developer registration ──────────────────────────────────────\n\n /**\n * `POST /developers/register` — create a developer account and mint a `cvl_`\n * key. No auth required. The returned key is captured on this client for\n * subsequent calls (and returned so the caller can persist it — it is shown\n * only once).\n *\n * A 503 with code `REGISTRATION_STORE_UNAVAILABLE` means the platform's\n * registration store is temporarily unreachable — it is NOT a problem with\n * your request; retry in a few minutes. The error message spells this out.\n */\n async register(request: DeveloperRegisterRequest): Promise<DeveloperRegisterResponse> {\n let result: DeveloperRegisterResponse\n try {\n result = await this.#request<DeveloperRegisterResponse>(\n 'POST',\n '/developers/register',\n request,\n false\n )\n } catch (error) {\n if (\n error instanceof ConvilynApiError &&\n error.status === 503 &&\n extractErrorCode(error.body) === 'REGISTRATION_STORE_UNAVAILABLE'\n ) {\n throw new ConvilynApiError(\n 503,\n 'Developer registration is temporarily unavailable (registration ' +\n 'store unreachable). This is not a problem with your request — ' +\n 'retry in a few minutes. [REGISTRATION_STORE_UNAVAILABLE]',\n error.body\n )\n }\n throw error\n }\n if (result.api_key && !this.#apiKey) {\n this.#apiKey = result.api_key\n }\n return result\n }\n\n // ── Server operations ───────────────────────────────────────────\n\n /** `POST /developers/servers` — submit a tool-server manifest for verification. */\n async submitServer(request: ServerSubmitRequest): Promise<ServerSubmitResponse> {\n return this.#request<ServerSubmitResponse>('POST', '/developers/servers', request)\n }\n\n /** `GET /developers/servers` — list this developer's servers. */\n async listServers(): Promise<DeveloperServer[]> {\n return this.#request<DeveloperServer[]>('GET', '/developers/servers')\n }\n\n /** `GET /developers/servers/{id}/status` — verification status of a server. */\n async serverStatus(serverId: string): Promise<ServerStatusResponse> {\n return this.#request<ServerStatusResponse>(\n 'GET',\n `/developers/servers/${encodeURIComponent(serverId)}/status`\n )\n }\n\n /** `POST /developers/servers/{id}/test` — trigger a sandbox test run. */\n async testServer(\n serverId: string,\n slots: Record<string, unknown> = {}\n ): Promise<TestRunResponse> {\n return this.#request<TestRunResponse>(\n 'POST',\n `/developers/servers/${encodeURIComponent(serverId)}/test`,\n { slots }\n )\n }\n\n /** `DELETE /developers/servers/{id}` — deactivate a server. */\n async deactivateServer(serverId: string): Promise<void> {\n await this.#request<void>('DELETE', `/developers/servers/${encodeURIComponent(serverId)}`)\n }\n\n // ── Workflow operations ─────────────────────────────────────────\n\n /**\n * `POST /developers/workflows` — submit a compiled workflow spec + its\n * server ids. `server_ids` may be omitted for a server-less spec that uses\n * only platform built-in tools; the wire always carries an explicit array\n * (parity with the Python SDK's `list(server_ids)`).\n */\n async submitWorkflow(request: WorkflowSubmitRequest): Promise<WorkflowSubmitResponse> {\n return this.#request<WorkflowSubmitResponse>('POST', '/developers/workflows', {\n workflow_spec: request.workflow_spec,\n server_ids: request.server_ids ?? [],\n })\n }\n\n /** `GET /developers/workflows` — list this developer's workflows. */\n async listWorkflows(): Promise<WorkflowListItem[]> {\n return this.#request<WorkflowListItem[]>('GET', '/developers/workflows')\n }\n\n /** `GET /developers/workflows/{id}/status` — verification status of a workflow. */\n async workflowStatus(workflowId: string): Promise<WorkflowStatusResponse> {\n return this.#request<WorkflowStatusResponse>(\n 'GET',\n `/developers/workflows/${encodeURIComponent(workflowId)}/status`\n )\n }\n\n /** `POST /developers/workflows/{id}/test` — sandbox-test a submitted workflow. */\n async testWorkflow(\n workflowId: string,\n testInput: Record<string, unknown> = {}\n ): Promise<WorkflowTestResponse> {\n return this.#request<WorkflowTestResponse>(\n 'POST',\n `/developers/workflows/${encodeURIComponent(workflowId)}/test`,\n { test_input: testInput }\n )\n }\n\n /** `DELETE /developers/workflows/{id}` — deactivate a workflow. */\n async deactivateWorkflow(workflowId: string): Promise<void> {\n await this.#request<void>('DELETE', `/developers/workflows/${encodeURIComponent(workflowId)}`)\n }\n\n // ── Convilyn-Hosted Author Runtime (port of the Python client) ─────────────\n\n /**\n * `POST /developers/runtimes/hosted` — deploy a tool server into the\n * Convilyn-Hosted Author Runtime. Counterpart to {@link submitServer}:\n * instead of registering a caller-deployed endpoint, the platform\n * provisions a sandboxed Lambda and returns its public endpoint URL.\n *\n * Backends without the hosted stack answer 503 `HOSTED_NOT_AVAILABLE`\n * (older builds: 501); environments with the router unmounted answer 404.\n * All surface as {@link ConvilynApiError} — catch and fall back to\n * `push --endpoint-url` (BYO) when a hard guarantee is needed.\n */\n async deployHostedRuntime(\n manifest: Record<string, unknown>,\n options: { region: string; workflowSpec?: Record<string, unknown> }\n ): Promise<DeployHostedResponse> {\n const body: Record<string, unknown> = { manifest, region: options.region }\n if (options.workflowSpec !== undefined) {\n body.workflow_spec = options.workflowSpec\n }\n return this.#request<DeployHostedResponse>('POST', '/developers/runtimes/hosted', body)\n }\n\n /**\n * `POST /developers/runtimes/{id}/rollback` — atomically flip the runtime\n * back to its previous active version.\n */\n async rollbackHostedRuntime(runtimeId: string): Promise<RollbackResponse> {\n return this.#request<RollbackResponse>(\n 'POST',\n `/developers/runtimes/${encodeURIComponent(runtimeId)}/rollback`\n )\n }\n\n /**\n * `GET /developers/runtimes/{id}/logs` — recent runtime log lines.\n * `since` is an ISO-8601 timestamp or relative shorthand (`\"5m\"`, `\"1h\"`)\n * interpreted server-side; `limit` defaults to 100 (server caps ~1000).\n * Accepts either a bare list or an `{entries: [...]}` envelope (mirror of\n * the Python client) so the SDK survives the wire shape stabilising.\n */\n async getHostedRuntimeLogs(\n runtimeId: string,\n options: { since?: string; limit?: number } = {}\n ): Promise<RuntimeLogEntry[]> {\n const limit = Math.trunc(options.limit ?? 100)\n let path = `/developers/runtimes/${encodeURIComponent(runtimeId)}/logs?limit=${limit}`\n if (options.since) {\n path = `${path}&since=${encodeURIComponent(options.since)}`\n }\n const result = await this.#request<unknown>('GET', path)\n if (Array.isArray(result)) {\n return result as RuntimeLogEntry[]\n }\n if (\n typeof result === 'object' &&\n result !== null &&\n Array.isArray((result as Record<string, unknown>).entries)\n ) {\n return (result as { entries: RuntimeLogEntry[] }).entries\n }\n return []\n }\n}\n\n/**\n * Pull a machine-readable error code out of an API error body. The backend\n * emits either a flat `{code, message}` object or a FastAPI `{detail: {code,\n * message}}` envelope — tolerate both.\n */\nfunction extractErrorCode(body: unknown): string | null {\n if (typeof body !== 'object' || body === null) {\n return null\n }\n const record = body as Record<string, unknown>\n if (typeof record.code === 'string') {\n return record.code\n }\n const detail = record.detail\n if (typeof detail === 'object' && detail !== null) {\n const code = (detail as Record<string, unknown>).code\n if (typeof code === 'string') {\n return code\n }\n }\n return null\n}\n","/**\n * JSON-RPC 2.0 envelope types + constructors for the `/mcp` runtime. The wire\n * shape matches the `mcp-shared` framework and the Python / Go author SDKs so a\n * TS-authored server is interchangeable behind the same gateway:\n *\n * request { jsonrpc:\"2.0\", method:\"tools/call\", params:{ name, arguments, context? }, id }\n * response { jsonrpc:\"2.0\", result?, error?:{ code, message, data? }, id }\n *\n * Tool-level outcomes (validation failures, tool errors) ride inside `result`\n * as a ToolResult envelope — only protocol-level faults use the `error` member.\n */\n\n/** JSON-RPC protocol version string. */\nexport const JSONRPC_VERSION = '2.0'\n\n/** Standard JSON-RPC 2.0 error codes (the only ones the `/mcp` runtime emits). */\nexport const PARSE_ERROR = -32700\nexport const INVALID_REQUEST = -32600\nexport const METHOD_NOT_FOUND = -32601\nexport const INVALID_PARAMS = -32602\nexport const INTERNAL_ERROR = -32603\n\n/** The single method the runtime dispatches. */\nexport const TOOLS_CALL = 'tools/call'\n\n/** An inbound JSON-RPC request. */\nexport interface JSONRPCRequest {\n jsonrpc: string\n method: string\n params?: Record<string, unknown>\n id?: string | number | null\n}\n\n/** The `error` member of a JSON-RPC response. */\nexport interface JSONRPCErrorObject {\n code: number\n message: string\n data?: Record<string, unknown>\n}\n\n/** An outbound JSON-RPC response (exactly one of `result` / `error`). */\nexport interface JSONRPCResponse {\n jsonrpc: typeof JSONRPC_VERSION\n result?: unknown\n error?: JSONRPCErrorObject\n id: string | number | null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Coerce parsed JSON into a {@link JSONRPCRequest}, or `null` when it is not a\n * well-formed request object (missing/`non-string method). The `id` defaults to\n * `null` so a response can always echo it.\n */\nexport function asRpcRequest(parsed: unknown): JSONRPCRequest | null {\n if (!isRecord(parsed) || typeof parsed.method !== 'string') {\n return null\n }\n const id = typeof parsed.id === 'string' || typeof parsed.id === 'number' ? parsed.id : null\n return {\n jsonrpc: typeof parsed.jsonrpc === 'string' ? parsed.jsonrpc : JSONRPC_VERSION,\n method: parsed.method,\n params: isRecord(parsed.params) ? parsed.params : {},\n id,\n }\n}\n\n/** Build a success response echoing `id`. */\nexport function rpcResult(id: string | number | null, result: unknown): JSONRPCResponse {\n return { jsonrpc: JSONRPC_VERSION, result, id }\n}\n\n/** Build an error response echoing `id`. */\nexport function rpcError(\n id: string | number | null,\n code: number,\n message: string,\n data?: Record<string, unknown>\n): JSONRPCResponse {\n const error: JSONRPCErrorObject = data !== undefined ? { code, message, data } : { code, message }\n return { jsonrpc: JSONRPC_VERSION, error, id }\n}\n","/**\n * Node `http` runtime for a {@link ToolServer}. Exposes the three endpoints the\n * gateway expects:\n *\n * GET /health → { status, server, version, tool_count }\n * GET /manifest → the server manifest (snake_case wire object)\n * POST /mcp → HMAC-verified JSON-RPC `tools/call` dispatch\n *\n * The HMAC signature covers the **raw request body bytes**, so the body buffer is\n * captured before any `JSON.parse`. Verification reuses {@link verifySignature}\n * (byte-for-byte parity with the gateway signer). No external dependencies.\n */\n\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport { verifySignature } from './auth'\nimport { ConvilynStartupError, InvalidSignatureError } from './errors'\nimport { SDKConfig } from './config'\nimport { VERSION } from './version'\nimport { asRpcRequest } from './jsonrpc'\nimport type { ToolServer } from './tool-server'\n\n/** Options for {@link serve}; unset fields fall back to {@link SDKConfig}. */\nexport interface ServeOptions {\n port?: number\n host?: string\n /** HMAC secret for `/mcp` verification. Required to accept signed requests. */\n hmacSecret?: string\n toleranceSeconds?: number\n /**\n * Explicit INSECURE local-development opt-in: with no secret configured,\n * `serve` refuses to start unless this is `true` (set by `convilyn-author\n * dev`) or `CONVILYN_DEV_INSECURE=1` is in the environment. A configured\n * secret always wins — the opt-in never bypasses verification.\n */\n allowInsecure?: boolean\n /** Pre-built config; defaults to {@link SDKConfig.fromEnv}. */\n config?: SDKConfig\n}\n\n/**\n * Environment variable that explicitly opts a bare `serve()` process into\n * INSECURE local development (no inbound signature verification). Port of the\n * Python `ENV_DEV_INSECURE` / Go `EnvDevInsecure`.\n */\nexport const ENV_DEV_INSECURE = 'CONVILYN_DEV_INSECURE'\n\nconst DEV_INSECURE_TRUTHY = new Set(['1', 'true', 'yes', 'on'])\n\n/**\n * True iff the operator explicitly opted into insecure local dev. Any other\n * value (including unset) is \"not opted in\" — the secure default is\n * fail-closed.\n */\nexport function devInsecureRequested(env: NodeJS.ProcessEnv = process.env): boolean {\n return DEV_INSECURE_TRUTHY.has((env[ENV_DEV_INSECURE] ?? '').trim().toLowerCase())\n}\n\nconst JSON_HEADERS = { 'content-type': 'application/json' } as const\n\nfunction sendJson(res: ServerResponse, statusCode: number, body: unknown): void {\n res.writeHead(statusCode, JSON_HEADERS)\n res.end(JSON.stringify(body))\n}\n\n/**\n * Inbound `/mcp` body cap (10 MB) — cross-SDK invariant shared with the\n * Python / Go author runtimes. Enforced while streaming, BEFORE signature\n * verification, so an unauthenticated caller cannot buffer unbounded bytes.\n */\nexport const MAX_BODY_BYTES = 10 * 1024 * 1024\n\n/** Thrown by {@link readBody} when the inbound body exceeds the cap. */\nclass BodyTooLargeError extends Error {\n constructor() {\n super(`Request body exceeds ${MAX_BODY_BYTES} bytes`)\n this.name = 'BodyTooLargeError'\n }\n}\n\n/** Collect the full request body as a Buffer (the bytes the HMAC signs). */\nfunction readBody(req: IncomingMessage, maxBytes: number = MAX_BODY_BYTES): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = []\n let total = 0\n req.on('data', (chunk: Buffer) => {\n total += chunk.length\n if (total > maxBytes) {\n // Stop buffering (later chunks are ignored) but keep the socket alive\n // so the caller can still answer 413 on the shared connection.\n chunks.length = 0\n reject(new BodyTooLargeError())\n return\n }\n chunks.push(chunk)\n })\n req.on('end', () => resolve(Buffer.concat(chunks)))\n req.on('error', reject)\n })\n}\n\nasync function handleMcp(\n server: ToolServer,\n req: IncomingMessage,\n res: ServerResponse,\n secret: string,\n toleranceSeconds: number,\n allowInsecure: boolean\n): Promise<void> {\n let body: Buffer\n try {\n body = await readBody(req)\n } catch (err) {\n if (err instanceof BodyTooLargeError) {\n // Answer first, then cut the connection once the response has flushed —\n // an endless streamer must not keep the socket (and kernel buffers) open.\n res.once('finish', () => req.destroy())\n sendJson(res, 413, {\n code: 'PAYLOAD_TOO_LARGE',\n message: 'Request body too large',\n })\n return\n }\n throw err\n }\n\n // Fail-closed: with no secret, only the explicit insecure-local opt-in\n // skips verification (serve() already warned loudly at startup). With a\n // secret configured the opt-in is ignored — verification always runs.\n if (secret === '' && allowInsecure) {\n await dispatchParsed(server, res, body)\n return\n }\n\n try {\n verifySignature(secret, body, req.headers as Record<string, string | undefined>, {\n toleranceSeconds,\n })\n } catch (err) {\n if (err instanceof InvalidSignatureError) {\n sendJson(res, 401, {\n code: 'INVALID_SIGNATURE',\n message: 'Request signature could not be verified',\n })\n return\n }\n throw err\n }\n\n await dispatchParsed(server, res, body)\n}\n\n/** Parse the (already-authorized) body and dispatch the JSON-RPC request. */\nasync function dispatchParsed(\n server: ToolServer,\n res: ServerResponse,\n body: Buffer\n): Promise<void> {\n let parsed: unknown\n try {\n parsed = JSON.parse(body.toString('utf8'))\n } catch {\n sendJson(res, 400, { error: 'Invalid JSON' })\n return\n }\n\n const request = asRpcRequest(parsed)\n if (request === null) {\n sendJson(res, 400, { error: 'Invalid JSON' })\n return\n }\n\n const response = await server.dispatch(request)\n sendJson(res, 200, response)\n}\n\n/**\n * Build and start an HTTP server for `toolServer`. Returns the listening\n * {@link Server}; await its `listening` event (and read `.address()`) for the\n * bound port when `port` is `0`.\n *\n * **Fail-closed:** unless an HMAC secret is configured, `serve` throws\n * {@link ConvilynStartupError} — independent of `CONVILYN_ENVIRONMENT` or the\n * bind host. Insecure local development must be opted into explicitly, either\n * via `allowInsecure: true` (passed by `convilyn-author dev`) or by setting\n * `CONVILYN_DEV_INSECURE=1`. Port of the Python `start_server`.\n */\nexport function serve(toolServer: ToolServer, options: ServeOptions = {}): Server {\n const config = options.config ?? SDKConfig.fromEnv()\n const host = options.host ?? config.serverHost\n const port = options.port ?? config.serverPort\n const secret = options.hmacSecret ?? config.hmacSecret\n const toleranceSeconds = options.toleranceSeconds ?? config.hmacToleranceSeconds\n const allowInsecure = options.allowInsecure ?? devInsecureRequested()\n\n if (secret === '' && !allowInsecure) {\n throw new ConvilynStartupError(\n 'CONVILYN_HMAC_SECRET is required to serve inbound /mcp traffic. ' +\n 'Refusing to start without signature verification. For local ' +\n `development use \\`convilyn-author dev\\` or set ${ENV_DEV_INSECURE}=1 ` +\n '(INSECURE — local only).'\n )\n }\n if (secret === '') {\n console.warn(\n 'convilyn-author: CONVILYN_HMAC_SECRET not set; serving /mcp WITHOUT ' +\n 'signature verification (insecure local dev only — do NOT deploy this configuration)'\n )\n }\n\n const httpServer = createServer((req, res) => {\n void route(toolServer, req, res, secret, toleranceSeconds, allowInsecure).catch(() => {\n if (!res.headersSent) {\n sendJson(res, 500, { error: 'Internal server error' })\n }\n })\n })\n\n httpServer.listen(port, host)\n return httpServer\n}\n\nasync function route(\n toolServer: ToolServer,\n req: IncomingMessage,\n res: ServerResponse,\n secret: string,\n toleranceSeconds: number,\n allowInsecure: boolean\n): Promise<void> {\n const path = (req.url ?? '').split('?')[0]\n const method = req.method ?? 'GET'\n\n if (method === 'GET' && path === '/health') {\n sendJson(res, 200, {\n status: 'healthy',\n server: toolServer.server.name,\n version: VERSION,\n tool_count: toolServer.toolCount,\n })\n return\n }\n\n if (method === 'GET' && path === '/manifest') {\n sendJson(res, 200, toolServer.manifest().toWire())\n return\n }\n\n if (method === 'POST' && path === '/mcp') {\n await handleMcp(toolServer, req, res, secret, toleranceSeconds, allowInsecure)\n return\n }\n\n sendJson(res, 404, { error: 'Not found' })\n}\n","/**\n * `ToolServer` — the registry of an author's tools and the transport-free\n * JSON-RPC dispatcher behind the `/mcp` endpoint. {@link ToolServer.dispatch} is\n * pure (request in, response out), so it is unit-testable without sockets; the\n * Node `http` wiring lives in `http-runtime.ts`.\n *\n * Dispatch contract (matches the `mcp-shared` framework):\n * - only `tools/call` is supported; any other method → `-32601`.\n * - missing `params.name` → `-32602`; unknown tool → `-32601`.\n * - input that fails the tool's Zod schema → a `validation_error` ToolResult\n * envelope inside `result` (NOT a JSON-RPC error).\n * - a handler that throws → `-32603`.\n * - the built-in `get_tool_data` resolves a `ref_id` from the DataStore; it is\n * not listed in the manifest (the platform injects it globally).\n */\n\nimport { ConvilynManifest } from './manifest'\nimport { InMemoryDataStore, type DataStore } from './datastore'\nimport { createToolContext } from './context'\nimport {\n rpcError,\n rpcResult,\n INTERNAL_ERROR,\n INVALID_PARAMS,\n METHOD_NOT_FOUND,\n TOOLS_CALL,\n type JSONRPCRequest,\n type JSONRPCResponse,\n} from './jsonrpc'\nimport {\n rawOkEnvelope,\n rawToolErrorEnvelope,\n toWireEnvelope,\n validationErrorEnvelope,\n type ValidationIssueWire,\n} from './tool-result-wire'\nimport type { ServerSpec } from './types'\nimport type { ToolDefinition } from './tool'\nimport { ConvilynAuthorError } from './errors'\n\n/** The built-in tool that resolves an offloaded `ref_id` to its full payload. */\nexport const GET_TOOL_DATA = 'get_tool_data'\n\n/** Options for constructing a {@link ToolServer}. */\nexport interface ToolServerOptions {\n tools?: ToolDefinition[]\n capabilities?: string[]\n /** Backing store for `ref_id` offload + retrieval; defaults to in-memory. */\n dataStore?: DataStore\n sdkVersion?: string\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** A minimal view of a Zod issue (avoids importing zod at runtime). */\ninterface ZodIssueLike {\n path: ReadonlyArray<string | number>\n message: string\n code?: string\n}\n\nfunction toValidationIssues(issues: ReadonlyArray<ZodIssueLike>): ValidationIssueWire[] {\n return issues.map((issue) => {\n const field = issue.path.length > 0 ? issue.path.join('.') : '.'\n const wire: ValidationIssueWire = { field, issue: issue.message }\n if (issue.code) {\n wire.expected = issue.code\n }\n return wire\n })\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The registry of an author's tools plus the JSON-RPC dispatcher. */\nexport class ToolServer {\n readonly server: ServerSpec\n readonly dataStore: DataStore\n readonly #tools = new Map<string, ToolDefinition>()\n readonly #capabilities: string[]\n readonly #sdkVersion?: string\n\n constructor(server: ServerSpec, options: ToolServerOptions = {}) {\n this.server = server\n this.dataStore = options.dataStore ?? new InMemoryDataStore()\n this.#capabilities = [...(options.capabilities ?? [])]\n this.#sdkVersion = options.sdkVersion\n for (const tool of options.tools ?? []) {\n this.register(tool)\n }\n }\n\n /** Register a tool. Throws on a duplicate name. Chainable. */\n register(tool: ToolDefinition): this {\n if (tool.name === GET_TOOL_DATA) {\n throw new ConvilynAuthorError(`tool name \"${GET_TOOL_DATA}\" is reserved`)\n }\n if (this.#tools.has(tool.name)) {\n throw new ConvilynAuthorError(`duplicate tool name: ${tool.name}`)\n }\n this.#tools.set(tool.name, tool)\n return this\n }\n\n /** Names of the registered (author) tools. */\n get toolNames(): string[] {\n return [...this.#tools.keys()]\n }\n\n /** Number of registered (author) tools — the `/health` `tool_count`. */\n get toolCount(): number {\n return this.#tools.size\n }\n\n /** The compiled manifest blueprint for this server. */\n manifest(): ConvilynManifest {\n const tools = [...this.#tools.values()].map((tool) => tool.toSpec())\n return new ConvilynManifest(this.server, {\n tools,\n capabilities: this.#capabilities,\n sdkVersion: this.#sdkVersion,\n })\n }\n\n /**\n * Dispatch one JSON-RPC request. Pure and transport-free: never throws for a\n * tool fault — protocol faults become a JSON-RPC `error`, tool/validation\n * faults become a ToolResult envelope inside `result`.\n */\n async dispatch(request: JSONRPCRequest): Promise<JSONRPCResponse> {\n const id = request.id ?? null\n\n if (request.method !== TOOLS_CALL) {\n return rpcError(id, METHOD_NOT_FOUND, `unsupported method: ${request.method}`)\n }\n\n const params = request.params ?? {}\n const name = params.name\n if (typeof name !== 'string' || name === '') {\n return rpcError(id, INVALID_PARAMS, 'params.name is required')\n }\n\n const args = isRecord(params.arguments) ? params.arguments : {}\n const ctx = createToolContext(this.dataStore, isRecord(params.context) ? params.context : {})\n\n if (name === GET_TOOL_DATA) {\n return this.#dispatchGetToolData(id, args)\n }\n\n const tool = this.#tools.get(name)\n if (!tool) {\n return rpcError(id, METHOD_NOT_FOUND, `unknown tool: ${name}`)\n }\n\n const parsed = tool.inputSchema.safeParse(args)\n if (!parsed.success) {\n const issues = toValidationIssues(parsed.error.issues as ReadonlyArray<ZodIssueLike>)\n return rpcResult(id, validationErrorEnvelope(issues))\n }\n\n try {\n const result = await tool.handler(parsed.data, ctx)\n const envelope = await toWireEnvelope(result, this.dataStore)\n return rpcResult(id, envelope)\n } catch (err) {\n return rpcError(id, INTERNAL_ERROR, errorMessage(err))\n }\n }\n\n async #dispatchGetToolData(\n id: string | number | null,\n args: Record<string, unknown>\n ): Promise<JSONRPCResponse> {\n const refId = args.ref_id\n if (typeof refId !== 'string' || refId === '') {\n return rpcResult(\n id,\n rawToolErrorEnvelope(\n 'INPUT_VALIDATION_ERROR',\n 'get_tool_data requires a string ref_id',\n 'Invalid input: ref_id is required'\n )\n )\n }\n const stored = await this.dataStore.get(refId)\n if (stored === null) {\n return rpcResult(\n id,\n rawToolErrorEnvelope(\n 'DEPENDENCY_NOT_FOUND',\n `no data stored for ref_id ${refId}`,\n `No data for ${refId}`\n )\n )\n }\n return rpcResult(id, rawOkEnvelope(stored, `Retrieved data for ${refId}`))\n }\n}\n","/**\n * Local, offline compliance checks for a {@link ToolServer} — the producer of\n * the {@link ComplianceReport} the `convilyn-author test` command (and the A5\n * local harness) report. No platform calls; nothing leaves the process.\n *\n * Checks are deliberately non-invasive: schemas and the runtime plumbing are\n * exercised, but author tool handlers are NOT blindly invoked (they may have\n * real side effects / external calls). `get_tool_data` is exercised against a\n * value the harness stores itself.\n */\n\nimport type { ToolServer } from './tool-server'\nimport { GET_TOOL_DATA } from './tool-server'\nimport { TOOLS_CALL } from './jsonrpc'\nimport type { ComplianceReport, ComplianceResult } from './types'\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction pass(checkName: string, message: string): ComplianceResult {\n return { passed: true, checkName, message }\n}\n\nfunction fail(checkName: string, message: string): ComplianceResult {\n return { passed: false, checkName, message }\n}\n\nfunction checkServerMetadata(server: ToolServer): ComplianceResult {\n const { name, version, description } = server.server\n if (!name || !version || !description) {\n return fail('server_metadata', 'server name, version, and description must all be non-empty')\n }\n return pass('server_metadata', 'server metadata is complete')\n}\n\nfunction checkToolsExist(server: ToolServer): ComplianceResult {\n return server.toolCount > 0\n ? pass('tools_exist', `server has ${server.toolCount} tool(s)`)\n : fail('tools_exist', 'server has no registered tools')\n}\n\nfunction checkToolSchemas(server: ToolServer): ComplianceResult {\n for (const tool of server.manifest().tools) {\n if (!tool.name || !tool.description) {\n return fail('tool_schemas', `tool \"${tool.name}\" is missing a name or description`)\n }\n if (!isRecord(tool.inputSchema) || tool.inputSchema.type !== 'object') {\n return fail('tool_schemas', `tool \"${tool.name}\" input_schema is not a JSON-Schema object`)\n }\n }\n return pass('tool_schemas', 'all tool schemas are valid')\n}\n\nfunction checkManifestSynth(server: ToolServer): ComplianceResult {\n try {\n const wire = server.manifest().toWire()\n return isRecord(wire)\n ? pass('manifest_synth', 'manifest compiles to a wire object')\n : fail('manifest_synth', 'manifest did not compile to an object')\n } catch (err) {\n return fail('manifest_synth', `manifest synth threw: ${(err as Error).message}`)\n }\n}\n\nasync function checkRefIdPattern(server: ToolServer): Promise<ComplianceResult> {\n const refId = await server.dataStore.store({ __compliance_probe__: true })\n return /^td_[0-9a-f]{12}$/.test(refId)\n ? pass('ref_id_pattern', 'data store returns a td_<12-hex> ref_id')\n : fail('ref_id_pattern', `ref_id \"${refId}\" does not match td_<12-hex>`)\n}\n\nasync function checkGetToolData(server: ToolServer): Promise<ComplianceResult> {\n const refId = await server.dataStore.store({ probe: 1 })\n const response = await server.dispatch({\n jsonrpc: '2.0',\n method: TOOLS_CALL,\n params: { name: GET_TOOL_DATA, arguments: { ref_id: refId } },\n id: 'compliance',\n })\n const result = response.result\n if (isRecord(result) && result.status === 'ok') {\n return pass('get_tool_data', 'built-in get_tool_data resolves a stored ref_id')\n }\n return fail('get_tool_data', 'built-in get_tool_data did not resolve a stored ref_id')\n}\n\n/**\n * Run the local compliance suite against a server, returning a\n * {@link ComplianceReport}. Use {@link allChecksPassed} / {@link failedChecks}\n * (from `./types`) to interpret it.\n */\nexport async function runComplianceChecks(server: ToolServer): Promise<ComplianceReport> {\n const results: ComplianceResult[] = [\n checkServerMetadata(server),\n checkToolsExist(server),\n checkToolSchemas(server),\n checkManifestSynth(server),\n await checkRefIdPattern(server),\n await checkGetToolData(server),\n ]\n return { results }\n}\n","/**\n * Core logic for each `convilyn-author` subcommand, kept transport- and\n * process-free so it is unit-testable: each returns a value (or throws) and the\n * commander action layer (`program.ts`) handles printing + exit codes.\n *\n * `synth` / `dev` / `test` are fully local. `push` submits a server + workflow\n * to the **Developer Portal** (`/api/v1/developers/*`) via {@link ConvilynClient}\n * — the wire contract lives at `docs/contracts/developer_portal/` and the\n * behaviour mirrors the Python SDK's `ConvilynClient.push`. `deploy` /\n * `rollback` / `logs` drive the Convilyn-Hosted Author Runtime\n * (`/developers/runtimes/*`), ported from the Python CLI.\n */\n\nimport { stat } from 'node:fs/promises'\nimport type { Server } from 'node:http'\nimport { loadToolServer } from './load-server'\nimport { loadWorkflowSpec } from './load-workflow'\nimport { ConvilynClient } from '../client'\nimport { serve } from '../http-runtime'\nimport { runComplianceChecks } from '../compliance'\nimport type { ComplianceReport } from '../types'\nimport type { RollbackResponse, RuntimeLogEntry } from '../platform-types'\n\nconst DEFAULT_SERVER_FILE = 'server.js'\nconst DEFAULT_WORKFLOW_FILE = 'workflow.spec.json'\nconst DEFAULT_MANIFEST_OUTPUT = 'convilyn.manifest.json'\n\n/** `synth`: load the server and write its manifest. */\nexport async function runSynth(options: {\n file?: string\n output?: string\n}): Promise<{ path: string; toolCount: number; toolNames: string[] }> {\n const server = await loadToolServer(options.file ?? DEFAULT_SERVER_FILE)\n const manifest = server.manifest()\n const path = await manifest.save(options.output ?? DEFAULT_MANIFEST_OUTPUT)\n return { path, toolCount: manifest.tools.length, toolNames: manifest.tools.map((t) => t.name) }\n}\n\n/** `dev`: load the server and start the local JSON-RPC `/mcp` runtime. */\nexport async function runDev(options: {\n file?: string\n host?: string\n port?: number\n hmacSecret?: string\n}): Promise<Server> {\n const server = await loadToolServer(options.file ?? DEFAULT_SERVER_FILE)\n return serve(server, {\n host: options.host,\n port: options.port,\n hmacSecret: options.hmacSecret,\n // `dev` IS the explicit insecure-local opt-in (mirror of the Python\n // CLI's run(dev=True)). A configured secret still wins — the opt-in\n // never bypasses verification.\n allowInsecure: true,\n })\n}\n\n/** `test`: load the server and run the local compliance suite. */\nexport async function runTest(options: { file?: string }): Promise<ComplianceReport> {\n const server = await loadToolServer(options.file ?? DEFAULT_SERVER_FILE)\n return runComplianceChecks(server)\n}\n\n/** Combined result of a successful `push` (server + workflow submission). */\nexport interface PushResult {\n serverId: string\n serverName: string\n serverStatus: string\n workflowId: string\n workflowSpecId: string\n workflowStatus: string\n}\n\n/**\n * `push`: submit a tool server + workflow to the Developer Portal in one call.\n *\n * Mirrors the Python SDK's `ConvilynClient.push`: synth the manifest → submit\n * the server (registering the caller-hosted `endpoint_url`) → compile the\n * workflow → submit it referencing the new server id. The {@link ConvilynClient}\n * is injectable so this is unit-testable against a fake `fetch` with no network.\n *\n * @throws if `--endpoint-url` is missing, if the server/workflow cannot be\n * loaded, or if the portal rejects a submission (`ConvilynApiError`).\n */\nexport async function runPush(options: {\n file?: string\n workflowFile?: string\n endpointUrl?: string\n client?: ConvilynClient\n}): Promise<PushResult> {\n if (!options.endpointUrl) {\n throw new Error(\n 'push requires --endpoint-url <https://...> — the HTTPS URL where your tool ' +\n 'server is deployed. Use `deploy --hosted` for a Convilyn-hosted server.'\n )\n }\n\n const server = await loadToolServer(options.file ?? DEFAULT_SERVER_FILE)\n const workflow = await loadWorkflowSpec(options.workflowFile ?? DEFAULT_WORKFLOW_FILE)\n const client = options.client ?? new ConvilynClient()\n\n const manifest = server.manifest().toWire()\n const serverResult = await client.submitServer({\n manifest,\n endpoint_url: options.endpointUrl,\n })\n\n const workflowResult = await client.submitWorkflow({\n // CompilableWorkflow.compile() is typed `unknown` (the file loader duck-types\n // both a built WorkflowSpec and a pre-compiled JSON blueprint).\n workflow_spec: workflow.compile() as Record<string, unknown>,\n server_ids: [serverResult.server_id],\n })\n\n return {\n serverId: serverResult.server_id,\n serverName: serverResult.server_name,\n serverStatus: serverResult.status,\n workflowId: workflowResult.workflow_id,\n workflowSpecId: workflowResult.spec_id,\n workflowStatus: workflowResult.status,\n }\n}\n\n/** Result of a successful `deploy --hosted`. */\nexport interface DeployResult {\n runtimeId: string\n endpointUrl: string | null\n status: string\n region: string\n version: number\n workflowId?: string\n workflowIncluded: boolean\n}\n\n/**\n * `deploy --hosted`: hand the server manifest (plus the compiled workflow\n * spec, when the workflow file exists) to the platform, which provisions a\n * sandboxed runtime in Convilyn's cloud (mirror of the Python CLI `deploy`).\n *\n * Without `--hosted` the command errors and points at `push` — BYO\n * deployments stay on `push --endpoint-url` so one subcommand never has two\n * meanings. The workflow file is optional and silently skipped when absent\n * (Python-CLI parity).\n */\nexport async function runDeploy(options: {\n file?: string\n workflowFile?: string\n hosted?: boolean\n region?: string\n client?: ConvilynClient\n}): Promise<DeployResult> {\n if (!options.hosted) {\n throw new Error(\n 'deploy currently requires --hosted. Use ' +\n '`convilyn-author push --endpoint-url <https://...>` for ' +\n 'caller-deployed (BYO) servers.'\n )\n }\n\n const server = await loadToolServer(options.file ?? DEFAULT_SERVER_FILE)\n const manifest = server.manifest().toWire()\n\n const workflowFile = options.workflowFile ?? DEFAULT_WORKFLOW_FILE\n let workflowSpec: Record<string, unknown> | undefined\n if (\n await stat(workflowFile).then(\n () => true,\n () => false\n )\n ) {\n const workflow = await loadWorkflowSpec(workflowFile)\n workflowSpec = workflow.compile() as Record<string, unknown>\n }\n\n const client = options.client ?? new ConvilynClient()\n const result = await client.deployHostedRuntime(manifest, {\n region: options.region ?? 'us-east-1',\n ...(workflowSpec !== undefined ? { workflowSpec } : {}),\n })\n\n return {\n runtimeId: result.runtime_id,\n endpointUrl: result.endpoint_url ?? null,\n status: result.status,\n region: result.region,\n version: result.version,\n ...(result.workflow_id != null ? { workflowId: result.workflow_id } : {}),\n workflowIncluded: workflowSpec !== undefined,\n }\n}\n\n/** `rollback <runtimeId>`: flip a hosted runtime to its previous version. */\nexport async function runRollback(options: {\n runtimeId: string\n client?: ConvilynClient\n}): Promise<RollbackResponse> {\n const client = options.client ?? new ConvilynClient()\n return client.rollbackHostedRuntime(options.runtimeId)\n}\n\n/** `logs <runtimeId>`: fetch recent log lines for a hosted runtime. */\nexport async function runLogs(options: {\n runtimeId: string\n since?: string\n limit?: number\n client?: ConvilynClient\n}): Promise<RuntimeLogEntry[]> {\n const client = options.client ?? new ConvilynClient()\n return client.getHostedRuntimeLogs(options.runtimeId, {\n ...(options.since !== undefined ? { since: options.since } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n })\n}\n","/**\n * Builds the `convilyn-author` commander program. Kept separate from the `bin`\n * entry (`../cli.ts`) so it can be constructed with an injected {@link Printer}\n * and parsed in tests without touching the real process streams.\n *\n * Command cores live in `./commands`; the actions here only translate their\n * return values into printed output + exit codes.\n */\n\nimport { Command } from 'commander'\nimport { VERSION } from '../version'\nimport { ConvilynApiError } from '../errors'\nimport { allChecksPassed } from '../types'\nimport { consolePrinter, type Printer } from './print'\nimport { scaffoldProject } from './scaffold'\nimport { runDeploy, runDev, runLogs, runPush, runRollback, runSynth, runTest } from './commands'\n\nfunction fail(printer: Printer, err: unknown): void {\n printer.err(`error: ${(err as Error).message}`)\n process.exitCode = 1\n}\n\n/** Hosted-runtime error printer: 501/503 get the BYO-fallback hint (Python parity). */\nfunction failHosted(printer: Printer, err: unknown): void {\n if (err instanceof ConvilynApiError && (err.status === 501 || err.status === 503)) {\n printer.err(\n `error: hosted runtime not yet available on this platform (${err.message}). ` +\n 'Use `convilyn-author push --endpoint-url ...` as a BYO fallback.'\n )\n process.exitCode = 1\n return\n }\n fail(printer, err)\n}\n\n/** Construct the CLI program. `printer` defaults to real stdout/stderr. */\nexport function buildProgram(printer: Printer = consolePrinter): Command {\n const program = new Command()\n program\n .name('convilyn-author')\n .description('Author and run Convilyn tool servers.')\n .version(VERSION)\n\n program\n .command('init')\n .description('Scaffold a new tool-server project.')\n .argument('<name>', 'project name (letters, digits, hyphens, underscores)')\n .option('--dir <dir>', 'target directory (default ./<name>)')\n .action(async (name: string, opts: { dir?: string }) => {\n try {\n const result = await scaffoldProject({ name, dir: opts.dir })\n printer.out(`Project created: ${result.path}`)\n printer.out(` ${result.files.join(', ')}`)\n printer.out(` cd ${name} && npm install && npm run build && npx convilyn-author dev`)\n } catch (err) {\n fail(printer, err)\n }\n })\n\n program\n .command('synth')\n .description('Compile the server manifest to JSON.')\n .option('--file <file>', 'built server module (default server.js)')\n .option('--output <output>', 'manifest output path (default convilyn.manifest.json)')\n .action(async (opts: { file?: string; output?: string }) => {\n try {\n const result = await runSynth(opts)\n printer.out(`Found ${result.toolCount} tool(s): ${result.toolNames.join(', ')}`)\n printer.out(`Manifest written: ${result.path}`)\n } catch (err) {\n fail(printer, err)\n }\n })\n\n program\n .command('dev')\n .description('Run the JSON-RPC /mcp server locally.')\n .option('--file <file>', 'built server module (default server.js)')\n .option('--host <host>', 'bind host (default from CONVILYN_HOST)')\n .option('--port <port>', 'bind port (default from CONVILYN_PORT)', (v) => parseInt(v, 10))\n .action(async (opts: { file?: string; host?: string; port?: number }) => {\n try {\n await runDev(opts)\n printer.out('convilyn-author dev: serving /mcp (Ctrl+C to stop)')\n } catch (err) {\n fail(printer, err)\n }\n })\n\n program\n .command('test')\n .description('Run local compliance checks (no platform calls).')\n .option('--file <file>', 'built server module (default server.js)')\n .action(async (opts: { file?: string }) => {\n try {\n const report = await runTest(opts)\n for (const r of report.results) {\n printer.out(` [${r.passed ? 'PASS' : 'FAIL'}] ${r.checkName}: ${r.message}`)\n }\n if (allChecksPassed(report)) {\n printer.out(`All ${report.results.length} checks passed`)\n } else {\n const failed = report.results.filter((r) => !r.passed).length\n printer.err(`${failed} of ${report.results.length} checks failed`)\n process.exitCode = 1\n }\n } catch (err) {\n fail(printer, err)\n }\n })\n\n program\n .command('push')\n .description('Submit a server + workflow to the Developer Portal.')\n .option('--file <file>', 'built server module (default server.js)')\n .option(\n '--workflow-file <file>',\n 'compiled workflow spec or built module (default workflow.spec.json)'\n )\n .option('--endpoint-url <url>', 'HTTPS URL of your deployed server (required)')\n .action(async (opts: { file?: string; workflowFile?: string; endpointUrl?: string }) => {\n try {\n const result = await runPush(opts)\n printer.out(`Server submitted: ${result.serverId} (${result.serverStatus})`)\n printer.out(`Workflow submitted: ${result.workflowId} (${result.workflowStatus})`)\n printer.out('Check verification with the ConvilynClient serverStatus() / workflowStatus().')\n } catch (err) {\n fail(printer, err)\n }\n })\n\n program\n .command('deploy')\n .description('Deploy a tool server to the Convilyn-Hosted Author Runtime.')\n .option('--file <file>', 'built server module (default server.js)')\n .option(\n '--workflow-file <file>',\n 'compiled workflow spec (default workflow.spec.json; optional — skipped when absent)'\n )\n .option('--hosted', 'use the managed runtime (required — BYO uses push)')\n .option('--region <region>', 'AWS region the hosted Lambda is provisioned in', 'us-east-1')\n .action(\n async (opts: { file?: string; workflowFile?: string; hosted?: boolean; region?: string }) => {\n try {\n printer.out(`Deploying to Convilyn-Hosted Runtime in ${opts.region ?? 'us-east-1'}...`)\n const result = await runDeploy(opts)\n printer.out(`Runtime provisioned: ${result.runtimeId} (${result.status})`)\n printer.out(`Endpoint URL: ${result.endpointUrl ?? 'pending (provisioning)'}`)\n if (result.workflowId != null) {\n printer.out(`Workflow registered: ${result.workflowId}`)\n }\n printer.out(\n `Use 'convilyn-author logs ${result.runtimeId}' to follow runtime logs, ` +\n `'convilyn-author rollback ${result.runtimeId}' to revert.`\n )\n } catch (err) {\n failHosted(printer, err)\n }\n }\n )\n\n program\n .command('rollback')\n .description('Roll a hosted runtime back to its previous active version.')\n .argument('<runtimeId>', 'runtime id returned by deploy --hosted')\n .action(async (runtimeId: string) => {\n try {\n printer.out(`Rolling back ${runtimeId}...`)\n const result = await runRollback({ runtimeId })\n printer.out(`Rollback complete: now-active version ${result.version} (${result.status})`)\n } catch (err) {\n fail(printer, err)\n }\n })\n\n program\n .command('logs')\n .description('Fetch recent logs for a hosted runtime.')\n .argument('<runtimeId>', 'runtime id returned by deploy --hosted')\n .option('--since <since>', \"relative window (e.g. '5m', '1h') or ISO-8601 timestamp\")\n .option('--limit <limit>', 'maximum log entries to fetch', (v) => parseInt(v, 10))\n .action(async (runtimeId: string, opts: { since?: string; limit?: number }) => {\n try {\n const entries = await runLogs({ runtimeId, ...opts })\n if (entries.length === 0) {\n printer.out(`No log entries for ${runtimeId} in the requested window.`)\n return\n }\n for (const entry of entries) {\n printer.out(`[${entry.timestamp}] ${entry.level} ${entry.message}`)\n }\n } catch (err) {\n fail(printer, err)\n }\n })\n\n return program\n}\n","#!/usr/bin/env node\n/**\n * `convilyn-author` CLI entry (the package `bin`). Thin by design: it builds the\n * commander program (see `./cli/program`) and parses argv. All logic lives in\n * `./cli/*` so it is unit-testable without spawning a process.\n */\n\nimport { buildProgram } from './cli/program'\n\n// No top-level await: the bin is emitted as CJS (dist/cli.cjs), where TLA is illegal.\nbuildProgram()\n .parseAsync(process.argv)\n .catch((err: unknown) => {\n process.stderr.write(`error: ${(err as Error).message}\\n`)\n process.exitCode = 1\n })\n"]}