apcore-cli 0.2.0 → 0.2.1

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/CHANGELOG.md CHANGED
@@ -5,6 +5,23 @@ All notable changes to apcore-cli (TypeScript SDK) will be documented in this fi
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.2.1] - 2026-03-19
9
+
10
+ ### Changed
11
+ - Help text truncation limit increased from 200 to 1000 characters (configurable via `cli.help_text_max_length` config key)
12
+ - `extractHelp`: added `maxLength` parameter (default 1000) (`schema-parser.ts`)
13
+ - `schemaToCliOptions`: added `maxHelpLength` parameter (default 1000) (`schema-parser.ts`)
14
+ - `buildModuleCommand`: added `helpTextMaxLength` parameter (default 1000), threaded through to schema parser (`main.ts`)
15
+ - `LazyModuleGroup`: constructor accepts `helpTextMaxLength` (default 1000), passes to `buildModuleCommand` (`cli.ts`)
16
+
17
+ ### Added
18
+ - `cli.help_text_max_length` config key (default: 1000) in `DEFAULTS` (`config.ts`)
19
+ - `APCORE_CLI_HELP_TEXT_MAX_LENGTH` environment variable support
20
+ - Test: "truncates help text at 1000 chars (default)"
21
+ - Test: "does not truncate text within default limit"
22
+ - Test: "truncates at custom maxLength"
23
+ - 183 tests (up from 181)
24
+
8
25
  ## [0.2.0] - 2026-03-18
9
26
 
10
27
  ### Added
package/README.md CHANGED
@@ -8,7 +8,7 @@ Terminal adapter for apcore. Execute AI-Perceivable modules from the command lin
8
8
 
9
9
  [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
10
10
  [![Node](https://img.shields.io/badge/node-18%2B-blue.svg)](https://nodejs.org)
11
- [![Tests](https://img.shields.io/badge/tests-181%20passed-brightgreen.svg)]()
11
+ [![Tests](https://img.shields.io/badge/tests-183%20passed-brightgreen.svg)]()
12
12
 
13
13
  | | |
14
14
  |---|---|
@@ -207,6 +207,7 @@ apcore-cli uses a 4-tier configuration precedence:
207
207
  | `APCORE_LOGGING_LEVEL` | Global apcore log level (fallback when `APCORE_CLI_LOGGING_LEVEL` is unset) | `WARNING` |
208
208
  | `APCORE_AUTH_API_KEY` | API key for remote registry authentication | *(unset)* |
209
209
  | `APCORE_CLI_SANDBOX` | Set to `1` to enable subprocess sandboxing | *(unset)* |
210
+ | `APCORE_CLI_HELP_TEXT_MAX_LENGTH` | Maximum characters for CLI option help text before truncation | `1000` |
210
211
 
211
212
  ### Config File (`apcore.yaml`)
212
213
 
@@ -217,6 +218,8 @@ logging:
217
218
  level: DEBUG
218
219
  sandbox:
219
220
  enabled: false
221
+ cli:
222
+ help_text_max_length: 1000
220
223
  ```
221
224
 
222
225
  ## Features
@@ -281,7 +284,7 @@ apcore Registry + Executor (your modules, unchanged)
281
284
  git clone https://github.com/aipartnerup/apcore-cli-typescript.git
282
285
  cd apcore-cli-typescript
283
286
  pnpm install
284
- pnpm test # 181 tests
287
+ pnpm test # 183 tests
285
288
  pnpm build # compile TypeScript
286
289
  ```
287
290
 
@@ -4,11 +4,11 @@ var __esm = (fn, res) => function __init() {
4
4
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
5
  };
6
6
 
7
- // node_modules/.pnpm/tsup@8.5.1_postcss@8.5.8_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js
7
+ // node_modules/tsup/assets/esm_shims.js
8
8
  import path from "path";
9
9
  import { fileURLToPath } from "url";
10
10
  var init_esm_shims = __esm({
11
- "node_modules/.pnpm/tsup@8.5.1_postcss@8.5.8_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js"() {
11
+ "node_modules/tsup/assets/esm_shims.js"() {
12
12
  "use strict";
13
13
  }
14
14
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.8_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js","../../src/errors.ts","../../bin/apcore-cli.ts","../../src/main.ts","../../src/ref-resolver.ts","../../src/schema-parser.ts","../../src/approval.ts","../../src/output.ts","../../src/logger.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Error classes and exit code mapping for apcore-cli.\n *\n * Protocol spec: Error handling & exit codes\n */\n\n// ---------------------------------------------------------------------------\n// Error classes\n// ---------------------------------------------------------------------------\n\n/** Thrown when the user does not approve module execution within the timeout. */\nexport class ApprovalTimeoutError extends Error {\n constructor(message = \"Approval timed out\") {\n super(message);\n this.name = \"ApprovalTimeoutError\";\n }\n}\n\n/** Thrown when API key authentication fails or is missing. */\nexport class AuthenticationError extends Error {\n constructor(message = \"Authentication failed\") {\n super(message);\n this.name = \"AuthenticationError\";\n }\n}\n\n/** Thrown when encrypted config cannot be decrypted. */\nexport class ConfigDecryptionError extends Error {\n constructor(message = \"Config decryption failed\") {\n super(message);\n this.name = \"ConfigDecryptionError\";\n }\n}\n\n/** Thrown when module execution fails. */\nexport class ModuleExecutionError extends Error {\n constructor(message = \"Module execution failed\") {\n super(message);\n this.name = \"ModuleExecutionError\";\n }\n}\n\n/** Thrown when approval is denied by the user. */\nexport class ApprovalDeniedError extends Error {\n constructor(message = \"Approval denied\") {\n super(message);\n this.name = \"ApprovalDeniedError\";\n }\n}\n\n/** Thrown when schema validation fails. */\nexport class SchemaValidationError extends Error {\n constructor(message = \"Schema validation failed\") {\n super(message);\n this.name = \"SchemaValidationError\";\n }\n}\n\n/** Thrown when a module is not found. */\nexport class ModuleNotFoundError extends Error {\n constructor(message = \"Module not found\") {\n super(message);\n this.name = \"ModuleNotFoundError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Exit code map\n// ---------------------------------------------------------------------------\n\nexport const EXIT_CODES = {\n SUCCESS: 0,\n MODULE_EXECUTE_ERROR: 1,\n MODULE_TIMEOUT: 1,\n INVALID_CLI_INPUT: 2,\n MODULE_NOT_FOUND: 44,\n MODULE_LOAD_ERROR: 44,\n MODULE_DISABLED: 44,\n SCHEMA_VALIDATION_ERROR: 45,\n APPROVAL_DENIED: 46,\n APPROVAL_TIMEOUT: 46,\n CONFIG_NOT_FOUND: 47,\n CONFIG_INVALID: 47,\n SCHEMA_CIRCULAR_REF: 48,\n ACL_DENIED: 77,\n KEYBOARD_INTERRUPT: 130,\n} as const;\n\nexport type ExitCode = (typeof EXIT_CODES)[keyof typeof EXIT_CODES];\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Map a caught error to the appropriate process exit code.\n * Also checks for apcore error codes on the error object.\n */\nexport function exitCodeForError(error: unknown): ExitCode {\n if (error instanceof ApprovalTimeoutError) {\n return EXIT_CODES.APPROVAL_TIMEOUT;\n }\n if (error instanceof ApprovalDeniedError) {\n return EXIT_CODES.APPROVAL_DENIED;\n }\n if (error instanceof AuthenticationError) {\n return EXIT_CODES.ACL_DENIED;\n }\n if (error instanceof ConfigDecryptionError) {\n return EXIT_CODES.CONFIG_INVALID;\n }\n if (error instanceof SchemaValidationError) {\n return EXIT_CODES.SCHEMA_VALIDATION_ERROR;\n }\n if (error instanceof ModuleNotFoundError) {\n return EXIT_CODES.MODULE_NOT_FOUND;\n }\n if (error instanceof ModuleExecutionError) {\n return EXIT_CODES.MODULE_EXECUTE_ERROR;\n }\n\n // Check for apcore error codes on the error object\n if (error instanceof Error) {\n const code = (error as unknown as Record<string, unknown>).code as string | undefined;\n const codeMap: Record<string, ExitCode> = {\n MODULE_NOT_FOUND: EXIT_CODES.MODULE_NOT_FOUND,\n MODULE_LOAD_ERROR: EXIT_CODES.MODULE_LOAD_ERROR,\n MODULE_DISABLED: EXIT_CODES.MODULE_DISABLED,\n SCHEMA_VALIDATION_ERROR: EXIT_CODES.SCHEMA_VALIDATION_ERROR,\n SCHEMA_CIRCULAR_REF: EXIT_CODES.SCHEMA_CIRCULAR_REF,\n APPROVAL_DENIED: EXIT_CODES.APPROVAL_DENIED,\n APPROVAL_TIMEOUT: EXIT_CODES.APPROVAL_TIMEOUT,\n CONFIG_NOT_FOUND: EXIT_CODES.CONFIG_NOT_FOUND,\n CONFIG_INVALID: EXIT_CODES.CONFIG_INVALID,\n MODULE_EXECUTE_ERROR: EXIT_CODES.MODULE_EXECUTE_ERROR,\n MODULE_TIMEOUT: EXIT_CODES.MODULE_TIMEOUT,\n ACL_DENIED: EXIT_CODES.ACL_DENIED,\n };\n if (code && code in codeMap) {\n return codeMap[code];\n }\n }\n\n return EXIT_CODES.MODULE_EXECUTE_ERROR;\n}\n","#!/usr/bin/env node\n/**\n * apcore-cli — Shebang entry point.\n *\n * This file is the bin target. It bootstraps the CLI and delegates to main().\n */\n\nimport { main } from \"../src/main.js\";\n\nmain(\"apcore-cli\");\n","/**\n * CLI entry point — createCli / main equivalents.\n *\n * Protocol spec: CLI bootstrapping & command registration\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport * as path from \"node:path\";\nimport { Command, CommanderError } from \"commander\";\nimport { EXIT_CODES, exitCodeForError } from \"./errors.js\";\nimport { resolveRefs } from \"./ref-resolver.js\";\nimport { schemaToCliOptions } from \"./schema-parser.js\";\nimport { checkApproval } from \"./approval.js\";\nimport { formatExecResult } from \"./output.js\";\nimport { setLogLevel } from \"./logger.js\";\nimport type { Executor, ModuleDescriptor } from \"./cli.js\";\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(path.resolve(__dirname, \"../package.json\"), \"utf-8\"));\nconst VERSION: string = pkg.version;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Configuration for a single Commander option derived from a JSON Schema property. */\nexport interface OptionConfig {\n /** The property name from the schema. */\n name: string;\n /** Commander flags string (e.g. \"--my-flag <value>\" or \"--flag, --no-flag\"). */\n flags: string;\n /** Help text for the option. */\n description: string;\n /** Default value. */\n defaultValue?: unknown;\n /** Whether the field is required (for display only). */\n required: boolean;\n /** Enum choices (string values). */\n choices?: string[];\n /** Whether this is a boolean flag pair (--flag/--no-flag). */\n isBooleanFlag?: boolean;\n /** Maps string enum value → original type name (\"int\", \"float\", \"bool\"). */\n enumOriginalTypes?: Record<string, string>;\n /** Parser function for Commander (e.g. parseInt, parseFloat). */\n parseArg?: (value: string) => unknown;\n}\n\n// ---------------------------------------------------------------------------\n// createCli\n// ---------------------------------------------------------------------------\n\n/**\n * Build and return the top-level Commander program.\n *\n * @param extensionsDir Path to the extensions directory (default: ./extensions)\n * @param progName Program name shown in help (default: apcore-cli)\n */\nexport function createCli(\n extensionsDir?: string,\n progName?: string,\n): Command {\n // Resolve program name\n const resolvedProgName = progName ?? path.basename(process.argv[1] ?? \"apcore-cli\") ?? \"apcore-cli\";\n\n // Resolve log level\n const cliLogLevel = process.env.APCORE_CLI_LOGGING_LEVEL ?? process.env.APCORE_LOGGING_LEVEL ?? \"WARNING\";\n setLogLevel(cliLogLevel);\n\n const program = new Command(resolvedProgName)\n .exitOverride()\n .version(VERSION, \"--version\", `Show ${resolvedProgName} version`)\n .description(\"apcore CLI — execute apcore modules from the command line\")\n .option(\"--extensions-dir <path>\", \"Path to extensions directory\")\n .option(\"--log-level <level>\", \"Logging level (DEBUG|INFO|WARNING|ERROR)\", \"WARNING\");\n\n // NOTE: Full registry/executor wiring requires apcore-js to be available.\n // For now, extensions-dir is accepted but not wired to a real registry.\n void extensionsDir;\n\n return program;\n}\n\n// ---------------------------------------------------------------------------\n// main\n// ---------------------------------------------------------------------------\n\n/**\n * Parse argv and run the CLI. Handles top-level error catching and exit codes.\n */\nexport function main(progName?: string): void {\n const program = createCli(undefined, progName);\n\n try {\n program.parse(process.argv);\n } catch (error: unknown) {\n if (error instanceof CommanderError) {\n // Commander already printed the error message\n process.exit(error.exitCode);\n }\n const code = exitCodeForError(error);\n if (error instanceof Error) {\n process.stderr.write(`Error: ${error.message}\\n`);\n }\n process.exit(code);\n }\n}\n\n// ---------------------------------------------------------------------------\n// buildModuleCommand\n// ---------------------------------------------------------------------------\n\n/**\n * Build a Commander Command for a single apcore module.\n */\nexport function buildModuleCommand(\n moduleDef: ModuleDescriptor,\n executor: Executor,\n): Command {\n const moduleId = moduleDef.id;\n let resolvedSchema: Record<string, unknown> = {};\n let schemaOptions: OptionConfig[] = [];\n\n // Resolve schema\n const inputSchema = moduleDef.inputSchema;\n if (inputSchema && typeof inputSchema === \"object\" && inputSchema.properties) {\n try {\n resolvedSchema = resolveRefs(inputSchema, 32, moduleId);\n } catch {\n resolvedSchema = inputSchema;\n }\n schemaOptions = schemaToCliOptions(resolvedSchema);\n }\n\n const cmd = new Command(moduleId).description(moduleDef.description);\n\n // Built-in options\n cmd.option(\"--input <source>\", \"Read input from STDIN ('-')\");\n cmd.option(\"-y, --yes\", \"Bypass approval prompts\", false);\n cmd.option(\"--large-input\", \"Allow STDIN input larger than 10MB\", false);\n cmd.option(\"--format <format>\", \"Output format (json|table)\");\n cmd.option(\"--sandbox\", \"Run module in subprocess sandbox\", false);\n\n // Schema-generated options\n for (const opt of schemaOptions) {\n if (opt.parseArg) {\n cmd.option(opt.flags, opt.description, opt.parseArg, opt.defaultValue);\n } else {\n cmd.option(opt.flags, opt.description, opt.defaultValue as string | boolean | undefined);\n }\n }\n\n // Action callback\n cmd.action(async (options: Record<string, unknown>) => {\n // Pop built-in options\n const stdinFlag = options.input as string | undefined;\n const autoApprove = options.yes as boolean;\n const largeInput = options.largeInput as boolean;\n const outputFormat = options.format as string | undefined;\n const sandboxEnabled = options.sandbox as boolean;\n\n // Remove built-in keys from options to get schema kwargs\n const schemaKwargs: Record<string, unknown> = {};\n const builtinKeys = new Set([\"input\", \"yes\", \"largeInput\", \"format\", \"sandbox\"]);\n for (const [k, v] of Object.entries(options)) {\n if (!builtinKeys.has(k)) {\n schemaKwargs[k] = v;\n }\n }\n\n try {\n // Collect and merge input\n const merged = await collectInput(stdinFlag, schemaKwargs, largeInput);\n\n // Reconvert enum values\n const reconverted = reconvertEnumValues(merged, schemaOptions);\n\n // Check approval\n await checkApproval(moduleDef, autoApprove);\n\n // Execute with timing\n const { Sandbox } = await import(\"./security/index.js\");\n const sandbox = new Sandbox(sandboxEnabled);\n const startTime = performance.now();\n const result = await sandbox.execute(moduleId, reconverted, executor);\n const durationMs = Math.round(performance.now() - startTime);\n\n // Audit log (success)\n const { getAuditLogger } = await import(\"./security/audit.js\");\n const auditLogger = getAuditLogger();\n if (auditLogger) {\n auditLogger.logExecution(moduleId, reconverted, \"success\", 0, durationMs);\n }\n\n // Format output\n formatExecResult(result, outputFormat);\n } catch (err: unknown) {\n // Audit log (error)\n const { getAuditLogger } = await import(\"./security/audit.js\");\n const auditLogger = getAuditLogger();\n const code = exitCodeForError(err);\n if (auditLogger) {\n auditLogger.logExecution(moduleId, {}, \"error\", code, 0);\n }\n\n if (err instanceof Error) {\n process.stderr.write(`Error: ${err.message}\\n`);\n }\n process.exit(code);\n }\n });\n\n return cmd;\n}\n\n// ---------------------------------------------------------------------------\n// validateModuleId\n// ---------------------------------------------------------------------------\n\n/**\n * Validate that a module ID conforms to the expected format.\n * Pattern: [a-z][a-z0-9_]*(.[a-z][a-z0-9_])* — max 128 chars.\n */\nexport function validateModuleId(moduleId: string): void {\n if (moduleId.length > 128) {\n process.stderr.write(\n `Error: Invalid module ID format: '${moduleId}'. Maximum length is 128 characters.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n if (!/^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)*$/.test(moduleId)) {\n process.stderr.write(\n `Error: Invalid module ID format: '${moduleId}'.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n}\n\n// ---------------------------------------------------------------------------\n// collectInput\n// ---------------------------------------------------------------------------\n\n/**\n * Collect module input from stdin and/or CLI keyword arguments.\n */\nexport async function collectInput(\n stdinFlag?: string,\n cliKwargs: Record<string, unknown> = {},\n largeInput?: boolean,\n): Promise<Record<string, unknown>> {\n // Remove null/undefined values from CLI kwargs\n const cliKwargsNonNull: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(cliKwargs)) {\n if (v !== null && v !== undefined) {\n cliKwargsNonNull[k] = v;\n }\n }\n\n if (!stdinFlag) {\n return cliKwargsNonNull;\n }\n\n if (stdinFlag === \"-\") {\n const raw = await readStdin();\n const rawSize = Buffer.byteLength(raw, \"utf-8\");\n\n if (rawSize > 10_485_760 && !largeInput) {\n process.stderr.write(\n \"Error: STDIN input exceeds 10MB limit. Use --large-input to override.\\n\",\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n if (!raw) {\n return cliKwargsNonNull;\n }\n\n let stdinData: unknown;\n try {\n stdinData = JSON.parse(raw);\n } catch {\n process.stderr.write(\n \"Error: STDIN does not contain valid JSON.\\n\",\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n if (typeof stdinData !== \"object\" || stdinData === null || Array.isArray(stdinData)) {\n process.stderr.write(\n `Error: STDIN JSON must be an object, got ${Array.isArray(stdinData) ? \"array\" : typeof stdinData}.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n // CLI flags override STDIN for duplicate keys\n return { ...(stdinData as Record<string, unknown>), ...cliKwargsNonNull };\n }\n\n return cliKwargsNonNull;\n}\n\n/**\n * Read all data from stdin with proper cleanup.\n */\nfunction readStdin(): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n const onData = (chunk: Buffer) => chunks.push(chunk);\n const onEnd = () => {\n cleanup();\n resolve(Buffer.concat(chunks).toString(\"utf-8\"));\n };\n const onError = (err: Error) => {\n cleanup();\n reject(err);\n };\n const cleanup = () => {\n process.stdin.removeListener(\"data\", onData);\n process.stdin.removeListener(\"end\", onEnd);\n process.stdin.removeListener(\"error\", onError);\n };\n process.stdin.on(\"data\", onData);\n process.stdin.on(\"end\", onEnd);\n process.stdin.on(\"error\", onError);\n process.stdin.resume();\n });\n}\n\n// ---------------------------------------------------------------------------\n// reconvertEnumValues\n// ---------------------------------------------------------------------------\n\n/**\n * Re-convert CLI string values back to their schema-typed equivalents\n * based on the option configs.\n */\nexport function reconvertEnumValues(\n kwargs: Record<string, unknown>,\n options: OptionConfig[],\n): Record<string, unknown> {\n const result = { ...kwargs };\n for (const opt of options) {\n if (!opt.enumOriginalTypes) continue;\n const paramName = opt.name;\n if (!(paramName in result) || result[paramName] === null || result[paramName] === undefined) {\n continue;\n }\n const strVal = String(result[paramName]);\n const origType = opt.enumOriginalTypes[strVal];\n if (origType === \"int\") {\n result[paramName] = parseInt(strVal, 10);\n } else if (origType === \"float\") {\n result[paramName] = parseFloat(strVal);\n } else if (origType === \"bool\") {\n result[paramName] = strVal.toLowerCase() === \"true\";\n }\n }\n return result;\n}\n","/**\n * JSON Schema $ref resolver.\n *\n * Protocol spec: Schema resolution & $ref handling\n */\n\nimport { EXIT_CODES } from \"./errors.js\";\n\n// ---------------------------------------------------------------------------\n// resolveRefs\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve all $ref references in a JSON Schema.\n * Returns a fully inlined schema with $defs/definitions removed.\n */\nexport function resolveRefs(\n schema: Record<string, unknown>,\n maxDepth = 32,\n moduleId = \"\",\n): Record<string, unknown> {\n const cloned = structuredClone(schema);\n const defs = (cloned.$defs ?? cloned.definitions ?? {}) as Record<\n string,\n unknown\n >;\n const result = resolveNode(\n cloned,\n defs,\n new Set<string>(),\n 0,\n maxDepth,\n moduleId,\n ) as Record<string, unknown>;\n\n // Remove definition keys\n delete result.$defs;\n delete result.definitions;\n return result;\n}\n\nfunction resolveNode(\n node: unknown,\n defs: Record<string, unknown>,\n visited: Set<string>,\n depth: number,\n maxDepth: number,\n moduleId: string,\n): unknown {\n if (typeof node !== \"object\" || node === null || Array.isArray(node)) {\n return node;\n }\n\n const obj = node as Record<string, unknown>;\n\n // Handle $ref\n if (\"$ref\" in obj) {\n const refPath = obj.$ref as string;\n\n if (depth >= maxDepth) {\n process.stderr.write(\n `Error: $ref resolution depth exceeded maximum of ${maxDepth} for module '${moduleId}'.\\n`,\n );\n process.exit(EXIT_CODES.SCHEMA_CIRCULAR_REF);\n }\n\n if (visited.has(refPath)) {\n process.stderr.write(\n `Error: Circular $ref detected in schema for module '${moduleId}' at path '${refPath}'.\\n`,\n );\n process.exit(EXIT_CODES.SCHEMA_CIRCULAR_REF);\n }\n\n // Parse ref target: extract key from \"#/$defs/Address\" → \"Address\"\n const parts = refPath.split(\"/\");\n const key = parts[parts.length - 1];\n\n if (!(key in defs)) {\n process.stderr.write(\n `Error: Unresolvable $ref '${refPath}' in schema for module '${moduleId}'.\\n`,\n );\n process.exit(EXIT_CODES.SCHEMA_VALIDATION_ERROR);\n }\n\n const newVisited = new Set(visited);\n newVisited.add(refPath);\n return resolveNode(defs[key], defs, newVisited, depth + 1, maxDepth, moduleId);\n }\n\n // Handle allOf\n if (\"allOf\" in obj && Array.isArray(obj.allOf)) {\n const merged: Record<string, unknown> = {\n properties: {},\n required: [] as string[],\n };\n for (const subSchema of obj.allOf as unknown[]) {\n const resolved = resolveNode(\n subSchema,\n defs,\n visited,\n depth + 1,\n maxDepth,\n moduleId,\n ) as Record<string, unknown>;\n if (resolved.properties) {\n Object.assign(\n merged.properties as Record<string, unknown>,\n resolved.properties,\n );\n }\n if (Array.isArray(resolved.required)) {\n (merged.required as string[]).push(...resolved.required);\n }\n }\n // Deduplicate required\n merged.required = [...new Set(merged.required as string[])];\n // Copy non-composition keys\n for (const [k, v] of Object.entries(obj)) {\n if (k !== \"allOf\" && !(k in merged)) {\n merged[k] = v;\n }\n }\n return merged;\n }\n\n // Handle anyOf / oneOf\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n if (keyword in obj && Array.isArray(obj[keyword])) {\n const merged: Record<string, unknown> = {\n properties: {},\n required: [] as string[],\n };\n const allRequiredSets: Set<string>[] = [];\n for (const subSchema of obj[keyword] as unknown[]) {\n const resolved = resolveNode(\n subSchema,\n defs,\n visited,\n depth + 1,\n maxDepth,\n moduleId,\n ) as Record<string, unknown>;\n if (resolved.properties) {\n Object.assign(\n merged.properties as Record<string, unknown>,\n resolved.properties,\n );\n }\n if (Array.isArray(resolved.required)) {\n allRequiredSets.push(new Set(resolved.required as string[]));\n }\n }\n // Required = intersection of all branches\n if (allRequiredSets.length > 0) {\n let intersection = allRequiredSets[0];\n for (let i = 1; i < allRequiredSets.length; i++) {\n intersection = new Set(\n [...intersection].filter((x) => allRequiredSets[i].has(x)),\n );\n }\n merged.required = [...intersection];\n } else {\n merged.required = [];\n }\n // Copy non-composition keys\n for (const [k, v] of Object.entries(obj)) {\n if (k !== keyword && !(k in merged)) {\n merged[k] = v;\n }\n }\n return merged;\n }\n }\n\n // Recursively process nested properties\n if (\"properties\" in obj && typeof obj.properties === \"object\" && obj.properties !== null) {\n const props = obj.properties as Record<string, unknown>;\n for (const [propName, propSchema] of Object.entries(props)) {\n props[propName] = resolveNode(\n propSchema,\n defs,\n visited,\n depth + 1,\n maxDepth,\n moduleId,\n );\n }\n }\n\n return obj;\n}\n","/**\n * JSON Schema -> Commander options mapping.\n *\n * Protocol spec: Schema-driven argument parsing\n */\n\nimport type { OptionConfig } from \"./main.js\";\nimport { EXIT_CODES } from \"./errors.js\";\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/** Sentinel type marker for boolean flags. */\nconst BOOLEAN_FLAG = Symbol(\"BOOLEAN_FLAG\");\n\ntype TypeResult = \"string\" | \"int\" | \"float\" | typeof BOOLEAN_FLAG | \"file\";\n\n/**\n * Map JSON Schema type to a type identifier.\n */\nexport function mapType(propName: string, propSchema: Record<string, unknown>): TypeResult {\n const schemaType = propSchema.type as string | undefined;\n\n // Check file convention\n if (\n schemaType === \"string\" &&\n (propName.endsWith(\"_file\") || propSchema[\"x-cli-file\"] === true)\n ) {\n return \"file\";\n }\n\n const typeMap: Record<string, TypeResult> = {\n string: \"string\",\n integer: \"int\",\n number: \"float\",\n boolean: BOOLEAN_FLAG,\n object: \"string\",\n array: \"string\",\n };\n\n if (!schemaType) {\n return \"string\";\n }\n\n return typeMap[schemaType] ?? \"string\";\n}\n\n/**\n * Extract help text from schema property, preferring x-llm-description.\n */\nexport function extractHelp(propSchema: Record<string, unknown>): string | undefined {\n let text = propSchema[\"x-llm-description\"] as string | undefined;\n if (!text) {\n text = propSchema.description as string | undefined;\n }\n if (!text) {\n return undefined;\n }\n if (text.length > 200) {\n return text.slice(0, 197) + \"...\";\n }\n return text;\n}\n\n// ---------------------------------------------------------------------------\n// schemaToCliOptions\n// ---------------------------------------------------------------------------\n\n/** Reserved CLI option names that cannot be used by schema properties. */\nconst RESERVED_NAMES = new Set([\"input\", \"yes\", \"large_input\", \"format\", \"sandbox\"]);\n\n/**\n * Convert a JSON Schema `properties` object into an array of\n * Commander option configurations.\n */\nexport function schemaToCliOptions(\n schema: Record<string, unknown>,\n): OptionConfig[] {\n const properties = (schema.properties ?? {}) as Record<\n string,\n Record<string, unknown>\n >;\n const requiredList = (schema.required ?? []) as string[];\n const options: OptionConfig[] = [];\n const flagNames: Record<string, string> = {};\n\n for (const [propName, propSchema] of Object.entries(properties)) {\n const flagName = \"--\" + propName.replace(/_/g, \"-\");\n\n // Collision detection\n if (flagName in flagNames) {\n process.stderr.write(\n `Error: Flag name collision: properties '${propName}' and '${flagNames[flagName]}' both map to '${flagName}'.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n flagNames[flagName] = propName;\n\n // Reserved name check\n if (RESERVED_NAMES.has(propName)) {\n process.stderr.write(\n `Error: Module schema property '${propName}' conflicts with a reserved CLI option name. Rename the property.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n const typeResult = mapType(propName, propSchema);\n const isRequired = requiredList.includes(propName);\n const helpBase = extractHelp(propSchema);\n const helpText = isRequired\n ? (helpBase ? helpBase + \" \" : \"\") + \"[required]\"\n : helpBase ?? \"\";\n const defaultValue = propSchema.default as unknown;\n\n if (typeResult === BOOLEAN_FLAG) {\n // Boolean flag pair: --flag/--no-flag\n const flagBase = propName.replace(/_/g, \"-\");\n const defaultVal = (propSchema.default as boolean) ?? false;\n options.push({\n name: propName,\n flags: `--${flagBase}, --no-${flagBase}`,\n description: helpText,\n defaultValue: defaultVal,\n required: false,\n isBooleanFlag: true,\n });\n } else if (\"enum\" in propSchema && Array.isArray(propSchema.enum)) {\n const enumValues = propSchema.enum as unknown[];\n if (enumValues.length === 0) {\n // Empty enum — fall back to plain string option\n options.push({\n name: propName,\n flags: `${flagName} <value>`,\n description: helpText,\n defaultValue,\n required: false,\n });\n } else {\n const stringValues = enumValues.map(String);\n const enumOriginalTypes: Record<string, string> = {};\n for (const v of enumValues) {\n if (typeof v === \"number\" && Number.isInteger(v)) {\n enumOriginalTypes[String(v)] = \"int\";\n } else if (typeof v === \"number\") {\n enumOriginalTypes[String(v)] = \"float\";\n } else if (typeof v === \"boolean\") {\n enumOriginalTypes[String(v)] = \"bool\";\n }\n }\n options.push({\n name: propName,\n flags: `${flagName} <value>`,\n description: helpText,\n defaultValue:\n defaultValue !== undefined ? String(defaultValue) : undefined,\n required: false,\n choices: stringValues,\n enumOriginalTypes:\n Object.keys(enumOriginalTypes).length > 0\n ? enumOriginalTypes\n : undefined,\n });\n }\n } else {\n // Standard option\n let parseArg: ((value: string) => unknown) | undefined;\n if (typeResult === \"int\") {\n parseArg = (v: string) => {\n const n = parseInt(v, 10);\n if (isNaN(n)) throw new Error(`Invalid integer: ${v}`);\n return n;\n };\n } else if (typeResult === \"float\") {\n parseArg = (v: string) => {\n const n = parseFloat(v);\n if (isNaN(n)) throw new Error(`Invalid number: ${v}`);\n return n;\n };\n }\n options.push({\n name: propName,\n flags: `${flagName} <value>`,\n description: helpText,\n defaultValue,\n required: false,\n parseArg,\n });\n }\n }\n\n return options;\n}\n","/**\n * Interactive approval prompts with timeout.\n *\n * Protocol spec: Approval workflow\n */\n\nimport * as readline from \"node:readline\";\nimport type { ModuleDescriptor } from \"./cli.js\";\nimport { ApprovalTimeoutError, EXIT_CODES } from \"./errors.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Get an annotation value from either a dict or an object.\n */\nfunction getAnnotation(\n annotations: unknown,\n key: string,\n defaultValue: unknown = undefined,\n): unknown {\n if (!annotations || typeof annotations !== \"object\") return defaultValue;\n const ann = annotations as Record<string, unknown>;\n return key in ann ? ann[key] : defaultValue;\n}\n\n// ---------------------------------------------------------------------------\n// checkApproval\n// ---------------------------------------------------------------------------\n\n/**\n * Check if module requires approval and handle accordingly.\n * Returns normally if approved (or approval not required).\n * Calls process.exit(46) if denied/timed out/non-TTY.\n */\nexport async function checkApproval(\n moduleDef: ModuleDescriptor,\n autoApprove: boolean,\n): Promise<void> {\n const annotations = moduleDef.annotations;\n\n // Check if approval is required\n let requiresApproval: boolean;\n if (moduleDef.requiresApproval !== undefined) {\n requiresApproval = moduleDef.requiresApproval;\n } else if (annotations) {\n requiresApproval = getAnnotation(annotations, \"requires_approval\", false) === true;\n } else {\n return; // No annotations, no approval needed\n }\n\n if (!requiresApproval) {\n return;\n }\n\n const moduleId = moduleDef.id;\n\n // Bypass: autoApprove flag (highest priority)\n if (autoApprove) {\n return;\n }\n\n // Bypass: APCORE_CLI_AUTO_APPROVE env var\n const envVal = process.env.APCORE_CLI_AUTO_APPROVE ?? \"\";\n if (envVal === \"1\") {\n return;\n }\n if (envVal !== \"\" && envVal !== \"1\") {\n process.stderr.write(\n `Warning: APCORE_CLI_AUTO_APPROVE is set to '${envVal}', expected '1'. Ignoring.\\n`,\n );\n }\n\n // Non-TTY check\n if (!process.stdin.isTTY) {\n process.stderr.write(\n `Error: Module '${moduleId}' requires approval but no interactive ` +\n \"terminal is available. Use --yes or set APCORE_CLI_AUTO_APPROVE=1 \" +\n \"to bypass.\\n\",\n );\n process.exit(EXIT_CODES.APPROVAL_DENIED);\n }\n\n // TTY prompt\n await promptWithTimeout(moduleDef, 60);\n}\n\n/**\n * Display approval prompt with timeout.\n */\nasync function promptWithTimeout(\n moduleDef: ModuleDescriptor,\n timeout: number,\n): Promise<void> {\n // Clamp timeout\n timeout = Math.max(1, Math.min(timeout, 3600));\n\n const moduleId = moduleDef.id;\n const annotations = moduleDef.annotations;\n const message =\n (annotations\n ? (getAnnotation(annotations, \"approval_message\") as string | undefined)\n : undefined) ??\n `Module '${moduleId}' requires approval to execute.`;\n\n process.stderr.write(message + \"\\n\");\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n try {\n const answer = await Promise.race([\n new Promise<string>((resolve) => {\n rl.question(\"Proceed? [y/N] \", (ans) => resolve(ans));\n }),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n reject(new ApprovalTimeoutError(\n `Approval prompt timed out after ${timeout} seconds.`,\n ));\n }, timeout * 1000);\n }),\n ]);\n\n // Clear the timeout — prompt resolved before timeout fired\n if (timer) clearTimeout(timer);\n\n const normalized = answer.trim().toLowerCase();\n if (normalized === \"y\" || normalized === \"yes\") {\n return;\n }\n\n process.stderr.write(\"Error: Approval denied.\\n\");\n process.exit(EXIT_CODES.APPROVAL_DENIED);\n } catch (err) {\n if (timer) clearTimeout(timer);\n if (err instanceof ApprovalTimeoutError) {\n process.stderr.write(\n `Error: Approval prompt timed out after ${timeout} seconds.\\n`,\n );\n process.exit(EXIT_CODES.APPROVAL_TIMEOUT);\n }\n throw err;\n } finally {\n rl.close();\n }\n}\n","/**\n * TTY-adaptive output formatting (table/json).\n *\n * Protocol spec: Output formatting\n */\n\nimport type { ModuleDescriptor } from \"./cli.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve output format with TTY-adaptive default.\n */\nexport function resolveFormat(explicitFormat?: string): string {\n if (explicitFormat !== undefined) {\n return explicitFormat;\n }\n return process.stdout.isTTY ? \"table\" : \"json\";\n}\n\n/**\n * Truncate text to maxLength, appending '...' if needed.\n */\nexport function truncate(text: string, maxLength = 80): string {\n if (text.length <= maxLength) {\n return text;\n }\n return text.slice(0, maxLength - 3) + \"...\";\n}\n\n/**\n * Render a simple plain-text table with column headers.\n */\nfunction formatTable(\n headers: string[],\n rows: string[][],\n): string {\n // Calculate column widths\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)),\n );\n\n const sep = colWidths.map((w) => \"-\".repeat(w)).join(\" \");\n const headerLine = headers\n .map((h, i) => h.padEnd(colWidths[i]))\n .join(\" \");\n const dataLines = rows.map((row) =>\n row.map((cell, i) => (cell ?? \"\").padEnd(colWidths[i])).join(\" \"),\n );\n\n return [headerLine, sep, ...dataLines].join(\"\\n\") + \"\\n\";\n}\n\n// ---------------------------------------------------------------------------\n// formatModuleList\n// ---------------------------------------------------------------------------\n\n/**\n * Format and print a list of modules.\n */\nexport function formatModuleList(\n modules: ModuleDescriptor[],\n format: string,\n filterTags?: string[],\n): void {\n if (format === \"table\") {\n if (modules.length === 0 && filterTags && filterTags.length > 0) {\n process.stdout.write(\n `No modules found matching tags: ${filterTags.join(\", \")}.\\n`,\n );\n return;\n }\n if (modules.length === 0) {\n process.stdout.write(\"No modules found.\\n\");\n return;\n }\n\n const headers = [\"ID\", \"Description\", \"Tags\"];\n const rows = modules.map((m) => [\n m.id,\n truncate(m.description, 80),\n (m.tags ?? []).join(\", \"),\n ]);\n process.stdout.write(formatTable(headers, rows));\n } else if (format === \"json\") {\n const result = modules.map((m) => ({\n id: m.id,\n description: m.description,\n tags: m.tags ?? [],\n }));\n process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// formatModuleDetail\n// ---------------------------------------------------------------------------\n\n/**\n * Convert annotations to a plain dict, filtering out falsy/default values.\n */\nfunction annotationsToDict(\n annotations: unknown,\n): Record<string, unknown> | null {\n if (!annotations) return null;\n if (typeof annotations !== \"object\" || Array.isArray(annotations)) return null;\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(annotations as Record<string, unknown>)) {\n if (v !== null && v !== undefined && v !== false && v !== 0 && !(Array.isArray(v) && v.length === 0)) {\n result[k] = v;\n }\n }\n return Object.keys(result).length > 0 ? result : null;\n}\n\n/**\n * Format and print full module metadata.\n */\nexport function formatModuleDetail(\n moduleDef: ModuleDescriptor,\n format: string,\n): void {\n if (format === \"table\") {\n process.stdout.write(`\\nModule: ${moduleDef.id}\\n`);\n process.stdout.write(`\\nDescription:\\n ${moduleDef.description}\\n`);\n\n if (moduleDef.inputSchema && Object.keys(moduleDef.inputSchema).length > 0) {\n process.stdout.write(\"\\nInput Schema:\\n\");\n process.stdout.write(JSON.stringify(moduleDef.inputSchema, null, 2) + \"\\n\");\n }\n\n if (moduleDef.outputSchema && Object.keys(moduleDef.outputSchema).length > 0) {\n process.stdout.write(\"\\nOutput Schema:\\n\");\n process.stdout.write(JSON.stringify(moduleDef.outputSchema, null, 2) + \"\\n\");\n }\n\n const annDict = annotationsToDict(\n moduleDef.annotations,\n );\n if (annDict) {\n process.stdout.write(\"\\nAnnotations:\\n\");\n for (const [k, v] of Object.entries(annDict)) {\n process.stdout.write(` ${k}: ${v}\\n`);\n }\n }\n\n // Extension metadata (x- prefixed)\n const metadata = moduleDef.metadata;\n if (metadata) {\n const xFields: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(metadata)) {\n if (k.startsWith(\"x-\") || k.startsWith(\"x_\")) {\n xFields[k] = v;\n }\n }\n if (Object.keys(xFields).length > 0) {\n process.stdout.write(\"\\nExtension Metadata:\\n\");\n for (const [k, v] of Object.entries(xFields)) {\n process.stdout.write(` ${k}: ${v}\\n`);\n }\n }\n }\n\n const tags = moduleDef.tags ?? [];\n if (tags.length > 0) {\n process.stdout.write(`\\nTags: ${tags.join(\", \")}\\n`);\n }\n } else if (format === \"json\") {\n const result: Record<string, unknown> = {\n id: moduleDef.id,\n description: moduleDef.description,\n };\n if (moduleDef.inputSchema) result.input_schema = moduleDef.inputSchema;\n if (moduleDef.outputSchema) result.output_schema = moduleDef.outputSchema;\n\n const annDict = annotationsToDict(\n moduleDef.annotations,\n );\n if (annDict) result.annotations = annDict;\n\n const tags = moduleDef.tags ?? [];\n if (tags.length > 0) result.tags = tags;\n\n // Extension metadata\n const metadata = moduleDef.metadata;\n if (metadata) {\n for (const [k, v] of Object.entries(metadata)) {\n if (k.startsWith(\"x-\") || k.startsWith(\"x_\")) {\n result[k] = v;\n }\n }\n }\n\n process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// formatExecResult\n// ---------------------------------------------------------------------------\n\n/**\n * Format and print module execution result.\n */\nexport function formatExecResult(\n result: unknown,\n format?: string,\n): void {\n if (result === null || result === undefined) {\n return;\n }\n const effective = resolveFormat(format);\n if (\n effective === \"table\" &&\n typeof result === \"object\" &&\n !Array.isArray(result)\n ) {\n // Key-value table\n const entries = Object.entries(result as Record<string, unknown>);\n const headers = [\"Key\", \"Value\"];\n const rows = entries.map(([k, v]) => [String(k), String(v)]);\n process.stdout.write(formatTable(headers, rows));\n } else if (typeof result === \"object\") {\n process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n } else if (typeof result === \"string\") {\n process.stdout.write(result + \"\\n\");\n } else {\n process.stdout.write(String(result) + \"\\n\");\n }\n}\n","/**\n * Simple structured logger respecting logging.level config.\n */\n\nconst LEVELS = { DEBUG: 0, INFO: 1, WARNING: 2, ERROR: 3 } as const;\ntype LogLevel = keyof typeof LEVELS;\n\nlet currentLevel: LogLevel = \"WARNING\";\n\nexport function setLogLevel(level: string): void {\n const upper = level.toUpperCase();\n if (upper in LEVELS) {\n currentLevel = upper as LogLevel;\n }\n}\n\nexport function getLogLevel(): LogLevel {\n return currentLevel;\n}\n\nfunction shouldLog(level: LogLevel): boolean {\n return LEVELS[level] >= LEVELS[currentLevel];\n}\n\nexport function debug(message: string): void {\n if (shouldLog(\"DEBUG\")) process.stderr.write(`DEBUG: ${message}\\n`);\n}\n\nexport function info(message: string): void {\n if (shouldLog(\"INFO\")) process.stderr.write(`INFO: ${message}\\n`);\n}\n\nexport function warn(message: string): void {\n if (shouldLog(\"WARNING\")) process.stderr.write(`WARNING: ${message}\\n`);\n}\n\nexport function error(message: string): void {\n if (shouldLog(\"ERROR\")) process.stderr.write(`ERROR: ${message}\\n`);\n}\n"],"mappings":";;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;;ACkGO,SAAS,iBAAiB,OAA0B;AACzD,MAAI,iBAAiB,sBAAsB;AACzC,WAAO,WAAW;AAAA,EACpB;AACA,MAAI,iBAAiB,qBAAqB;AACxC,WAAO,WAAW;AAAA,EACpB;AACA,MAAI,iBAAiB,qBAAqB;AACxC,WAAO,WAAW;AAAA,EACpB;AACA,MAAI,iBAAiB,uBAAuB;AAC1C,WAAO,WAAW;AAAA,EACpB;AACA,MAAI,iBAAiB,uBAAuB;AAC1C,WAAO,WAAW;AAAA,EACpB;AACA,MAAI,iBAAiB,qBAAqB;AACxC,WAAO,WAAW;AAAA,EACpB;AACA,MAAI,iBAAiB,sBAAsB;AACzC,WAAO,WAAW;AAAA,EACpB;AAGA,MAAI,iBAAiB,OAAO;AAC1B,UAAM,OAAQ,MAA6C;AAC3D,UAAM,UAAoC;AAAA,MACxC,kBAAkB,WAAW;AAAA,MAC7B,mBAAmB,WAAW;AAAA,MAC9B,iBAAiB,WAAW;AAAA,MAC5B,yBAAyB,WAAW;AAAA,MACpC,qBAAqB,WAAW;AAAA,MAChC,iBAAiB,WAAW;AAAA,MAC5B,kBAAkB,WAAW;AAAA,MAC7B,kBAAkB,WAAW;AAAA,MAC7B,gBAAgB,WAAW;AAAA,MAC3B,sBAAsB,WAAW;AAAA,MACjC,gBAAgB,WAAW;AA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AI;AACF,YAAQ,MAAM,QAAQ,IAAI;AAAA,EAC5B,SAAS,OAAgB;AACvB,QAAI,iBAAiB,gBAAgB;AAEnC,cAAQ,KAAK,MAAM,QAAQ;AAAA,IAC7B;AACA,UAAM,OAAO,iBAAiB,KAAK;AACnC,QAAI,iBAAiB,OAAO;AAC1B,cAAQ,OAAO,MAAM,UAAU,MAAM,OAAO;AAAA,CAAI;AAAA,IAClD;AACA,YAAQ,KAAK,IAAI;AAAA,EACnB;AACF;;;ADjGA,KAAK,YAAY;","names":["fileURLToPath","path","__dirname","fileURLToPath"]}
1
+ {"version":3,"sources":["../../node_modules/tsup/assets/esm_shims.js","../../src/errors.ts","../../bin/apcore-cli.ts","../../src/main.ts","../../src/ref-resolver.ts","../../src/schema-parser.ts","../../src/approval.ts","../../src/output.ts","../../src/logger.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Error classes and exit code mapping for apcore-cli.\n *\n * Protocol spec: Error handling & exit codes\n */\n\n// ---------------------------------------------------------------------------\n// Error classes\n// ---------------------------------------------------------------------------\n\n/** Thrown when the user does not approve module execution within the timeout. */\nexport class ApprovalTimeoutError extends Error {\n constructor(message = \"Approval timed out\") {\n super(message);\n this.name = \"ApprovalTimeoutError\";\n }\n}\n\n/** Thrown when API key authentication fails or is missing. */\nexport class AuthenticationError extends Error {\n constructor(message = \"Authentication failed\") {\n super(message);\n this.name = \"AuthenticationError\";\n }\n}\n\n/** Thrown when encrypted config cannot be decrypted. */\nexport class ConfigDecryptionError extends Error {\n constructor(message = \"Config decryption failed\") {\n super(message);\n this.name = \"ConfigDecryptionError\";\n }\n}\n\n/** Thrown when module execution fails. */\nexport class ModuleExecutionError extends Error {\n constructor(message = \"Module execution failed\") {\n super(message);\n this.name = \"ModuleExecutionError\";\n }\n}\n\n/** Thrown when approval is denied by the user. */\nexport class ApprovalDeniedError extends Error {\n constructor(message = \"Approval denied\") {\n super(message);\n this.name = \"ApprovalDeniedError\";\n }\n}\n\n/** Thrown when schema validation fails. */\nexport class SchemaValidationError extends Error {\n constructor(message = \"Schema validation failed\") {\n super(message);\n this.name = \"SchemaValidationError\";\n }\n}\n\n/** Thrown when a module is not found. */\nexport class ModuleNotFoundError extends Error {\n constructor(message = \"Module not found\") {\n super(message);\n this.name = \"ModuleNotFoundError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Exit code map\n// ---------------------------------------------------------------------------\n\nexport const EXIT_CODES = {\n SUCCESS: 0,\n MODULE_EXECUTE_ERROR: 1,\n MODULE_TIMEOUT: 1,\n INVALID_CLI_INPUT: 2,\n MODULE_NOT_FOUND: 44,\n MODULE_LOAD_ERROR: 44,\n MODULE_DISABLED: 44,\n SCHEMA_VALIDATION_ERROR: 45,\n APPROVAL_DENIED: 46,\n APPROVAL_TIMEOUT: 46,\n CONFIG_NOT_FOUND: 47,\n CONFIG_INVALID: 47,\n SCHEMA_CIRCULAR_REF: 48,\n ACL_DENIED: 77,\n KEYBOARD_INTERRUPT: 130,\n} as const;\n\nexport type ExitCode = (typeof EXIT_CODES)[keyof typeof EXIT_CODES];\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Map a caught error to the appropriate process exit code.\n * Also checks for apcore error codes on the error object.\n */\nexport function exitCodeForError(error: unknown): ExitCode {\n if (error instanceof ApprovalTimeoutError) {\n return EXIT_CODES.APPROVAL_TIMEOUT;\n }\n if (error instanceof ApprovalDeniedError) {\n return EXIT_CODES.APPROVAL_DENIED;\n }\n if (error instanceof AuthenticationError) {\n return EXIT_CODES.ACL_DENIED;\n }\n if (error instanceof ConfigDecryptionError) {\n return EXIT_CODES.CONFIG_INVALID;\n }\n if (error instanceof SchemaValidationError) {\n return EXIT_CODES.SCHEMA_VALIDATION_ERROR;\n }\n if (error instanceof ModuleNotFoundError) {\n return EXIT_CODES.MODULE_NOT_FOUND;\n }\n if (error instanceof ModuleExecutionError) {\n return EXIT_CODES.MODULE_EXECUTE_ERROR;\n }\n\n // Check for apcore error codes on the error object\n if (error instanceof Error) {\n const code = (error as unknown as Record<string, unknown>).code as string | undefined;\n const codeMap: Record<string, ExitCode> = {\n MODULE_NOT_FOUND: EXIT_CODES.MODULE_NOT_FOUND,\n MODULE_LOAD_ERROR: EXIT_CODES.MODULE_LOAD_ERROR,\n MODULE_DISABLED: EXIT_CODES.MODULE_DISABLED,\n SCHEMA_VALIDATION_ERROR: EXIT_CODES.SCHEMA_VALIDATION_ERROR,\n SCHEMA_CIRCULAR_REF: EXIT_CODES.SCHEMA_CIRCULAR_REF,\n APPROVAL_DENIED: EXIT_CODES.APPROVAL_DENIED,\n APPROVAL_TIMEOUT: EXIT_CODES.APPROVAL_TIMEOUT,\n CONFIG_NOT_FOUND: EXIT_CODES.CONFIG_NOT_FOUND,\n CONFIG_INVALID: EXIT_CODES.CONFIG_INVALID,\n MODULE_EXECUTE_ERROR: EXIT_CODES.MODULE_EXECUTE_ERROR,\n MODULE_TIMEOUT: EXIT_CODES.MODULE_TIMEOUT,\n ACL_DENIED: EXIT_CODES.ACL_DENIED,\n };\n if (code && code in codeMap) {\n return codeMap[code];\n }\n }\n\n return EXIT_CODES.MODULE_EXECUTE_ERROR;\n}\n","#!/usr/bin/env node\n/**\n * apcore-cli — Shebang entry point.\n *\n * This file is the bin target. It bootstraps the CLI and delegates to main().\n */\n\nimport { main } from \"../src/main.js\";\n\nmain(\"apcore-cli\");\n","/**\n * CLI entry point — createCli / main equivalents.\n *\n * Protocol spec: CLI bootstrapping & command registration\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport * as path from \"node:path\";\nimport { Command, CommanderError } from \"commander\";\nimport { EXIT_CODES, exitCodeForError } from \"./errors.js\";\nimport { resolveRefs } from \"./ref-resolver.js\";\nimport { schemaToCliOptions } from \"./schema-parser.js\";\nimport { checkApproval } from \"./approval.js\";\nimport { formatExecResult } from \"./output.js\";\nimport { setLogLevel } from \"./logger.js\";\nimport type { Executor, ModuleDescriptor } from \"./cli.js\";\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(path.resolve(__dirname, \"../package.json\"), \"utf-8\"));\nconst VERSION: string = pkg.version;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Configuration for a single Commander option derived from a JSON Schema property. */\nexport interface OptionConfig {\n /** The property name from the schema. */\n name: string;\n /** Commander flags string (e.g. \"--my-flag <value>\" or \"--flag, --no-flag\"). */\n flags: string;\n /** Help text for the option. */\n description: string;\n /** Default value. */\n defaultValue?: unknown;\n /** Whether the field is required (for display only). */\n required: boolean;\n /** Enum choices (string values). */\n choices?: string[];\n /** Whether this is a boolean flag pair (--flag/--no-flag). */\n isBooleanFlag?: boolean;\n /** Maps string enum value → original type name (\"int\", \"float\", \"bool\"). */\n enumOriginalTypes?: Record<string, string>;\n /** Parser function for Commander (e.g. parseInt, parseFloat). */\n parseArg?: (value: string) => unknown;\n}\n\n// ---------------------------------------------------------------------------\n// createCli\n// ---------------------------------------------------------------------------\n\n/**\n * Build and return the top-level Commander program.\n *\n * @param extensionsDir Path to the extensions directory (default: ./extensions)\n * @param progName Program name shown in help (default: apcore-cli)\n */\nexport function createCli(\n extensionsDir?: string,\n progName?: string,\n): Command {\n // Resolve program name\n const resolvedProgName = progName ?? path.basename(process.argv[1] ?? \"apcore-cli\") ?? \"apcore-cli\";\n\n // Resolve log level\n const cliLogLevel = process.env.APCORE_CLI_LOGGING_LEVEL ?? process.env.APCORE_LOGGING_LEVEL ?? \"WARNING\";\n setLogLevel(cliLogLevel);\n\n const program = new Command(resolvedProgName)\n .exitOverride()\n .version(VERSION, \"--version\", `Show ${resolvedProgName} version`)\n .description(\"apcore CLI — execute apcore modules from the command line\")\n .option(\"--extensions-dir <path>\", \"Path to extensions directory\")\n .option(\"--log-level <level>\", \"Logging level (DEBUG|INFO|WARNING|ERROR)\", \"WARNING\");\n\n // NOTE: Full registry/executor wiring requires apcore-js to be available.\n // For now, extensions-dir is accepted but not wired to a real registry.\n void extensionsDir;\n\n return program;\n}\n\n// ---------------------------------------------------------------------------\n// main\n// ---------------------------------------------------------------------------\n\n/**\n * Parse argv and run the CLI. Handles top-level error catching and exit codes.\n */\nexport function main(progName?: string): void {\n const program = createCli(undefined, progName);\n\n try {\n program.parse(process.argv);\n } catch (error: unknown) {\n if (error instanceof CommanderError) {\n // Commander already printed the error message\n process.exit(error.exitCode);\n }\n const code = exitCodeForError(error);\n if (error instanceof Error) {\n process.stderr.write(`Error: ${error.message}\\n`);\n }\n process.exit(code);\n }\n}\n\n// ---------------------------------------------------------------------------\n// buildModuleCommand\n// ---------------------------------------------------------------------------\n\n/**\n * Build a Commander Command for a single apcore module.\n */\nexport function buildModuleCommand(\n moduleDef: ModuleDescriptor,\n executor: Executor,\n helpTextMaxLength = 1000,\n): Command {\n const moduleId = moduleDef.id;\n let resolvedSchema: Record<string, unknown> = {};\n let schemaOptions: OptionConfig[] = [];\n\n // Resolve schema\n const inputSchema = moduleDef.inputSchema;\n if (inputSchema && typeof inputSchema === \"object\" && inputSchema.properties) {\n try {\n resolvedSchema = resolveRefs(inputSchema, 32, moduleId);\n } catch {\n resolvedSchema = inputSchema;\n }\n schemaOptions = schemaToCliOptions(resolvedSchema, helpTextMaxLength);\n }\n\n const cmd = new Command(moduleId).description(moduleDef.description);\n\n // Built-in options\n cmd.option(\"--input <source>\", \"Read input from STDIN ('-')\");\n cmd.option(\"-y, --yes\", \"Bypass approval prompts\", false);\n cmd.option(\"--large-input\", \"Allow STDIN input larger than 10MB\", false);\n cmd.option(\"--format <format>\", \"Output format (json|table)\");\n cmd.option(\"--sandbox\", \"Run module in subprocess sandbox\", false);\n\n // Schema-generated options\n for (const opt of schemaOptions) {\n if (opt.parseArg) {\n cmd.option(opt.flags, opt.description, opt.parseArg, opt.defaultValue);\n } else {\n cmd.option(opt.flags, opt.description, opt.defaultValue as string | boolean | undefined);\n }\n }\n\n // Action callback\n cmd.action(async (options: Record<string, unknown>) => {\n // Pop built-in options\n const stdinFlag = options.input as string | undefined;\n const autoApprove = options.yes as boolean;\n const largeInput = options.largeInput as boolean;\n const outputFormat = options.format as string | undefined;\n const sandboxEnabled = options.sandbox as boolean;\n\n // Remove built-in keys from options to get schema kwargs\n const schemaKwargs: Record<string, unknown> = {};\n const builtinKeys = new Set([\"input\", \"yes\", \"largeInput\", \"format\", \"sandbox\"]);\n for (const [k, v] of Object.entries(options)) {\n if (!builtinKeys.has(k)) {\n schemaKwargs[k] = v;\n }\n }\n\n try {\n // Collect and merge input\n const merged = await collectInput(stdinFlag, schemaKwargs, largeInput);\n\n // Reconvert enum values\n const reconverted = reconvertEnumValues(merged, schemaOptions);\n\n // Check approval\n await checkApproval(moduleDef, autoApprove);\n\n // Execute with timing\n const { Sandbox } = await import(\"./security/index.js\");\n const sandbox = new Sandbox(sandboxEnabled);\n const startTime = performance.now();\n const result = await sandbox.execute(moduleId, reconverted, executor);\n const durationMs = Math.round(performance.now() - startTime);\n\n // Audit log (success)\n const { getAuditLogger } = await import(\"./security/audit.js\");\n const auditLogger = getAuditLogger();\n if (auditLogger) {\n auditLogger.logExecution(moduleId, reconverted, \"success\", 0, durationMs);\n }\n\n // Format output\n formatExecResult(result, outputFormat);\n } catch (err: unknown) {\n // Audit log (error)\n const { getAuditLogger } = await import(\"./security/audit.js\");\n const auditLogger = getAuditLogger();\n const code = exitCodeForError(err);\n if (auditLogger) {\n auditLogger.logExecution(moduleId, {}, \"error\", code, 0);\n }\n\n if (err instanceof Error) {\n process.stderr.write(`Error: ${err.message}\\n`);\n }\n process.exit(code);\n }\n });\n\n return cmd;\n}\n\n// ---------------------------------------------------------------------------\n// validateModuleId\n// ---------------------------------------------------------------------------\n\n/**\n * Validate that a module ID conforms to the expected format.\n * Pattern: [a-z][a-z0-9_]*(.[a-z][a-z0-9_])* — max 128 chars.\n */\nexport function validateModuleId(moduleId: string): void {\n if (moduleId.length > 128) {\n process.stderr.write(\n `Error: Invalid module ID format: '${moduleId}'. Maximum length is 128 characters.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n if (!/^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)*$/.test(moduleId)) {\n process.stderr.write(\n `Error: Invalid module ID format: '${moduleId}'.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n}\n\n// ---------------------------------------------------------------------------\n// collectInput\n// ---------------------------------------------------------------------------\n\n/**\n * Collect module input from stdin and/or CLI keyword arguments.\n */\nexport async function collectInput(\n stdinFlag?: string,\n cliKwargs: Record<string, unknown> = {},\n largeInput?: boolean,\n): Promise<Record<string, unknown>> {\n // Remove null/undefined values from CLI kwargs\n const cliKwargsNonNull: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(cliKwargs)) {\n if (v !== null && v !== undefined) {\n cliKwargsNonNull[k] = v;\n }\n }\n\n if (!stdinFlag) {\n return cliKwargsNonNull;\n }\n\n if (stdinFlag === \"-\") {\n const raw = await readStdin();\n const rawSize = Buffer.byteLength(raw, \"utf-8\");\n\n if (rawSize > 10_485_760 && !largeInput) {\n process.stderr.write(\n \"Error: STDIN input exceeds 10MB limit. Use --large-input to override.\\n\",\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n if (!raw) {\n return cliKwargsNonNull;\n }\n\n let stdinData: unknown;\n try {\n stdinData = JSON.parse(raw);\n } catch {\n process.stderr.write(\n \"Error: STDIN does not contain valid JSON.\\n\",\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n if (typeof stdinData !== \"object\" || stdinData === null || Array.isArray(stdinData)) {\n process.stderr.write(\n `Error: STDIN JSON must be an object, got ${Array.isArray(stdinData) ? \"array\" : typeof stdinData}.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n // CLI flags override STDIN for duplicate keys\n return { ...(stdinData as Record<string, unknown>), ...cliKwargsNonNull };\n }\n\n return cliKwargsNonNull;\n}\n\n/**\n * Read all data from stdin with proper cleanup.\n */\nfunction readStdin(): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n const onData = (chunk: Buffer) => chunks.push(chunk);\n const onEnd = () => {\n cleanup();\n resolve(Buffer.concat(chunks).toString(\"utf-8\"));\n };\n const onError = (err: Error) => {\n cleanup();\n reject(err);\n };\n const cleanup = () => {\n process.stdin.removeListener(\"data\", onData);\n process.stdin.removeListener(\"end\", onEnd);\n process.stdin.removeListener(\"error\", onError);\n };\n process.stdin.on(\"data\", onData);\n process.stdin.on(\"end\", onEnd);\n process.stdin.on(\"error\", onError);\n process.stdin.resume();\n });\n}\n\n// ---------------------------------------------------------------------------\n// reconvertEnumValues\n// ---------------------------------------------------------------------------\n\n/**\n * Re-convert CLI string values back to their schema-typed equivalents\n * based on the option configs.\n */\nexport function reconvertEnumValues(\n kwargs: Record<string, unknown>,\n options: OptionConfig[],\n): Record<string, unknown> {\n const result = { ...kwargs };\n for (const opt of options) {\n if (!opt.enumOriginalTypes) continue;\n const paramName = opt.name;\n if (!(paramName in result) || result[paramName] === null || result[paramName] === undefined) {\n continue;\n }\n const strVal = String(result[paramName]);\n const origType = opt.enumOriginalTypes[strVal];\n if (origType === \"int\") {\n result[paramName] = parseInt(strVal, 10);\n } else if (origType === \"float\") {\n result[paramName] = parseFloat(strVal);\n } else if (origType === \"bool\") {\n result[paramName] = strVal.toLowerCase() === \"true\";\n }\n }\n return result;\n}\n","/**\n * JSON Schema $ref resolver.\n *\n * Protocol spec: Schema resolution & $ref handling\n */\n\nimport { EXIT_CODES } from \"./errors.js\";\n\n// ---------------------------------------------------------------------------\n// resolveRefs\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve all $ref references in a JSON Schema.\n * Returns a fully inlined schema with $defs/definitions removed.\n */\nexport function resolveRefs(\n schema: Record<string, unknown>,\n maxDepth = 32,\n moduleId = \"\",\n): Record<string, unknown> {\n const cloned = structuredClone(schema);\n const defs = (cloned.$defs ?? cloned.definitions ?? {}) as Record<\n string,\n unknown\n >;\n const result = resolveNode(\n cloned,\n defs,\n new Set<string>(),\n 0,\n maxDepth,\n moduleId,\n ) as Record<string, unknown>;\n\n // Remove definition keys\n delete result.$defs;\n delete result.definitions;\n return result;\n}\n\nfunction resolveNode(\n node: unknown,\n defs: Record<string, unknown>,\n visited: Set<string>,\n depth: number,\n maxDepth: number,\n moduleId: string,\n): unknown {\n if (typeof node !== \"object\" || node === null || Array.isArray(node)) {\n return node;\n }\n\n const obj = node as Record<string, unknown>;\n\n // Handle $ref\n if (\"$ref\" in obj) {\n const refPath = obj.$ref as string;\n\n if (depth >= maxDepth) {\n process.stderr.write(\n `Error: $ref resolution depth exceeded maximum of ${maxDepth} for module '${moduleId}'.\\n`,\n );\n process.exit(EXIT_CODES.SCHEMA_CIRCULAR_REF);\n }\n\n if (visited.has(refPath)) {\n process.stderr.write(\n `Error: Circular $ref detected in schema for module '${moduleId}' at path '${refPath}'.\\n`,\n );\n process.exit(EXIT_CODES.SCHEMA_CIRCULAR_REF);\n }\n\n // Parse ref target: extract key from \"#/$defs/Address\" → \"Address\"\n const parts = refPath.split(\"/\");\n const key = parts[parts.length - 1];\n\n if (!(key in defs)) {\n process.stderr.write(\n `Error: Unresolvable $ref '${refPath}' in schema for module '${moduleId}'.\\n`,\n );\n process.exit(EXIT_CODES.SCHEMA_VALIDATION_ERROR);\n }\n\n const newVisited = new Set(visited);\n newVisited.add(refPath);\n return resolveNode(defs[key], defs, newVisited, depth + 1, maxDepth, moduleId);\n }\n\n // Handle allOf\n if (\"allOf\" in obj && Array.isArray(obj.allOf)) {\n const merged: Record<string, unknown> = {\n properties: {},\n required: [] as string[],\n };\n for (const subSchema of obj.allOf as unknown[]) {\n const resolved = resolveNode(\n subSchema,\n defs,\n visited,\n depth + 1,\n maxDepth,\n moduleId,\n ) as Record<string, unknown>;\n if (resolved.properties) {\n Object.assign(\n merged.properties as Record<string, unknown>,\n resolved.properties,\n );\n }\n if (Array.isArray(resolved.required)) {\n (merged.required as string[]).push(...resolved.required);\n }\n }\n // Deduplicate required\n merged.required = [...new Set(merged.required as string[])];\n // Copy non-composition keys\n for (const [k, v] of Object.entries(obj)) {\n if (k !== \"allOf\" && !(k in merged)) {\n merged[k] = v;\n }\n }\n return merged;\n }\n\n // Handle anyOf / oneOf\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n if (keyword in obj && Array.isArray(obj[keyword])) {\n const merged: Record<string, unknown> = {\n properties: {},\n required: [] as string[],\n };\n const allRequiredSets: Set<string>[] = [];\n for (const subSchema of obj[keyword] as unknown[]) {\n const resolved = resolveNode(\n subSchema,\n defs,\n visited,\n depth + 1,\n maxDepth,\n moduleId,\n ) as Record<string, unknown>;\n if (resolved.properties) {\n Object.assign(\n merged.properties as Record<string, unknown>,\n resolved.properties,\n );\n }\n if (Array.isArray(resolved.required)) {\n allRequiredSets.push(new Set(resolved.required as string[]));\n }\n }\n // Required = intersection of all branches\n if (allRequiredSets.length > 0) {\n let intersection = allRequiredSets[0];\n for (let i = 1; i < allRequiredSets.length; i++) {\n intersection = new Set(\n [...intersection].filter((x) => allRequiredSets[i].has(x)),\n );\n }\n merged.required = [...intersection];\n } else {\n merged.required = [];\n }\n // Copy non-composition keys\n for (const [k, v] of Object.entries(obj)) {\n if (k !== keyword && !(k in merged)) {\n merged[k] = v;\n }\n }\n return merged;\n }\n }\n\n // Recursively process nested properties\n if (\"properties\" in obj && typeof obj.properties === \"object\" && obj.properties !== null) {\n const props = obj.properties as Record<string, unknown>;\n for (const [propName, propSchema] of Object.entries(props)) {\n props[propName] = resolveNode(\n propSchema,\n defs,\n visited,\n depth + 1,\n maxDepth,\n moduleId,\n );\n }\n }\n\n return obj;\n}\n","/**\n * JSON Schema -> Commander options mapping.\n *\n * Protocol spec: Schema-driven argument parsing\n */\n\nimport type { OptionConfig } from \"./main.js\";\nimport { EXIT_CODES } from \"./errors.js\";\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/** Sentinel type marker for boolean flags. */\nconst BOOLEAN_FLAG = Symbol(\"BOOLEAN_FLAG\");\n\ntype TypeResult = \"string\" | \"int\" | \"float\" | typeof BOOLEAN_FLAG | \"file\";\n\n/**\n * Map JSON Schema type to a type identifier.\n */\nexport function mapType(propName: string, propSchema: Record<string, unknown>): TypeResult {\n const schemaType = propSchema.type as string | undefined;\n\n // Check file convention\n if (\n schemaType === \"string\" &&\n (propName.endsWith(\"_file\") || propSchema[\"x-cli-file\"] === true)\n ) {\n return \"file\";\n }\n\n const typeMap: Record<string, TypeResult> = {\n string: \"string\",\n integer: \"int\",\n number: \"float\",\n boolean: BOOLEAN_FLAG,\n object: \"string\",\n array: \"string\",\n };\n\n if (!schemaType) {\n return \"string\";\n }\n\n return typeMap[schemaType] ?? \"string\";\n}\n\n/**\n * Extract help text from schema property, preferring x-llm-description.\n */\nexport function extractHelp(propSchema: Record<string, unknown>, maxLength = 1000): string | undefined {\n let text = propSchema[\"x-llm-description\"] as string | undefined;\n if (!text) {\n text = propSchema.description as string | undefined;\n }\n if (!text) {\n return undefined;\n }\n if (maxLength > 0 && text.length > maxLength) {\n return text.slice(0, maxLength - 3) + \"...\";\n }\n return text;\n}\n\n// ---------------------------------------------------------------------------\n// schemaToCliOptions\n// ---------------------------------------------------------------------------\n\n/** Reserved CLI option names that cannot be used by schema properties. */\nconst RESERVED_NAMES = new Set([\"input\", \"yes\", \"large_input\", \"format\", \"sandbox\"]);\n\n/**\n * Convert a JSON Schema `properties` object into an array of\n * Commander option configurations.\n */\nexport function schemaToCliOptions(\n schema: Record<string, unknown>,\n maxHelpLength = 1000,\n): OptionConfig[] {\n const properties = (schema.properties ?? {}) as Record<\n string,\n Record<string, unknown>\n >;\n const requiredList = (schema.required ?? []) as string[];\n const options: OptionConfig[] = [];\n const flagNames: Record<string, string> = {};\n\n for (const [propName, propSchema] of Object.entries(properties)) {\n const flagName = \"--\" + propName.replace(/_/g, \"-\");\n\n // Collision detection\n if (flagName in flagNames) {\n process.stderr.write(\n `Error: Flag name collision: properties '${propName}' and '${flagNames[flagName]}' both map to '${flagName}'.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n flagNames[flagName] = propName;\n\n // Reserved name check\n if (RESERVED_NAMES.has(propName)) {\n process.stderr.write(\n `Error: Module schema property '${propName}' conflicts with a reserved CLI option name. Rename the property.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n const typeResult = mapType(propName, propSchema);\n const isRequired = requiredList.includes(propName);\n const helpBase = extractHelp(propSchema, maxHelpLength);\n const helpText = isRequired\n ? (helpBase ? helpBase + \" \" : \"\") + \"[required]\"\n : helpBase ?? \"\";\n const defaultValue = propSchema.default as unknown;\n\n if (typeResult === BOOLEAN_FLAG) {\n // Boolean flag pair: --flag/--no-flag\n const flagBase = propName.replace(/_/g, \"-\");\n const defaultVal = (propSchema.default as boolean) ?? false;\n options.push({\n name: propName,\n flags: `--${flagBase}, --no-${flagBase}`,\n description: helpText,\n defaultValue: defaultVal,\n required: false,\n isBooleanFlag: true,\n });\n } else if (\"enum\" in propSchema && Array.isArray(propSchema.enum)) {\n const enumValues = propSchema.enum as unknown[];\n if (enumValues.length === 0) {\n // Empty enum — fall back to plain string option\n options.push({\n name: propName,\n flags: `${flagName} <value>`,\n description: helpText,\n defaultValue,\n required: false,\n });\n } else {\n const stringValues = enumValues.map(String);\n const enumOriginalTypes: Record<string, string> = {};\n for (const v of enumValues) {\n if (typeof v === \"number\" && Number.isInteger(v)) {\n enumOriginalTypes[String(v)] = \"int\";\n } else if (typeof v === \"number\") {\n enumOriginalTypes[String(v)] = \"float\";\n } else if (typeof v === \"boolean\") {\n enumOriginalTypes[String(v)] = \"bool\";\n }\n }\n options.push({\n name: propName,\n flags: `${flagName} <value>`,\n description: helpText,\n defaultValue:\n defaultValue !== undefined ? String(defaultValue) : undefined,\n required: false,\n choices: stringValues,\n enumOriginalTypes:\n Object.keys(enumOriginalTypes).length > 0\n ? enumOriginalTypes\n : undefined,\n });\n }\n } else {\n // Standard option\n let parseArg: ((value: string) => unknown) | undefined;\n if (typeResult === \"int\") {\n parseArg = (v: string) => {\n const n = parseInt(v, 10);\n if (isNaN(n)) throw new Error(`Invalid integer: ${v}`);\n return n;\n };\n } else if (typeResult === \"float\") {\n parseArg = (v: string) => {\n const n = parseFloat(v);\n if (isNaN(n)) throw new Error(`Invalid number: ${v}`);\n return n;\n };\n }\n options.push({\n name: propName,\n flags: `${flagName} <value>`,\n description: helpText,\n defaultValue,\n required: false,\n parseArg,\n });\n }\n }\n\n return options;\n}\n","/**\n * Interactive approval prompts with timeout.\n *\n * Protocol spec: Approval workflow\n */\n\nimport * as readline from \"node:readline\";\nimport type { ModuleDescriptor } from \"./cli.js\";\nimport { ApprovalTimeoutError, EXIT_CODES } from \"./errors.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Get an annotation value from either a dict or an object.\n */\nfunction getAnnotation(\n annotations: unknown,\n key: string,\n defaultValue: unknown = undefined,\n): unknown {\n if (!annotations || typeof annotations !== \"object\") return defaultValue;\n const ann = annotations as Record<string, unknown>;\n return key in ann ? ann[key] : defaultValue;\n}\n\n// ---------------------------------------------------------------------------\n// checkApproval\n// ---------------------------------------------------------------------------\n\n/**\n * Check if module requires approval and handle accordingly.\n * Returns normally if approved (or approval not required).\n * Calls process.exit(46) if denied/timed out/non-TTY.\n */\nexport async function checkApproval(\n moduleDef: ModuleDescriptor,\n autoApprove: boolean,\n): Promise<void> {\n const annotations = moduleDef.annotations;\n\n // Check if approval is required\n let requiresApproval: boolean;\n if (moduleDef.requiresApproval !== undefined) {\n requiresApproval = moduleDef.requiresApproval;\n } else if (annotations) {\n requiresApproval = getAnnotation(annotations, \"requires_approval\", false) === true;\n } else {\n return; // No annotations, no approval needed\n }\n\n if (!requiresApproval) {\n return;\n }\n\n const moduleId = moduleDef.id;\n\n // Bypass: autoApprove flag (highest priority)\n if (autoApprove) {\n return;\n }\n\n // Bypass: APCORE_CLI_AUTO_APPROVE env var\n const envVal = process.env.APCORE_CLI_AUTO_APPROVE ?? \"\";\n if (envVal === \"1\") {\n return;\n }\n if (envVal !== \"\" && envVal !== \"1\") {\n process.stderr.write(\n `Warning: APCORE_CLI_AUTO_APPROVE is set to '${envVal}', expected '1'. Ignoring.\\n`,\n );\n }\n\n // Non-TTY check\n if (!process.stdin.isTTY) {\n process.stderr.write(\n `Error: Module '${moduleId}' requires approval but no interactive ` +\n \"terminal is available. Use --yes or set APCORE_CLI_AUTO_APPROVE=1 \" +\n \"to bypass.\\n\",\n );\n process.exit(EXIT_CODES.APPROVAL_DENIED);\n }\n\n // TTY prompt\n await promptWithTimeout(moduleDef, 60);\n}\n\n/**\n * Display approval prompt with timeout.\n */\nasync function promptWithTimeout(\n moduleDef: ModuleDescriptor,\n timeout: number,\n): Promise<void> {\n // Clamp timeout\n timeout = Math.max(1, Math.min(timeout, 3600));\n\n const moduleId = moduleDef.id;\n const annotations = moduleDef.annotations;\n const message =\n (annotations\n ? (getAnnotation(annotations, \"approval_message\") as string | undefined)\n : undefined) ??\n `Module '${moduleId}' requires approval to execute.`;\n\n process.stderr.write(message + \"\\n\");\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n try {\n const answer = await Promise.race([\n new Promise<string>((resolve) => {\n rl.question(\"Proceed? [y/N] \", (ans) => resolve(ans));\n }),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n reject(new ApprovalTimeoutError(\n `Approval prompt timed out after ${timeout} seconds.`,\n ));\n }, timeout * 1000);\n }),\n ]);\n\n // Clear the timeout — prompt resolved before timeout fired\n if (timer) clearTimeout(timer);\n\n const normalized = answer.trim().toLowerCase();\n if (normalized === \"y\" || normalized === \"yes\") {\n return;\n }\n\n process.stderr.write(\"Error: Approval denied.\\n\");\n process.exit(EXIT_CODES.APPROVAL_DENIED);\n } catch (err) {\n if (timer) clearTimeout(timer);\n if (err instanceof ApprovalTimeoutError) {\n process.stderr.write(\n `Error: Approval prompt timed out after ${timeout} seconds.\\n`,\n );\n process.exit(EXIT_CODES.APPROVAL_TIMEOUT);\n }\n throw err;\n } finally {\n rl.close();\n }\n}\n","/**\n * TTY-adaptive output formatting (table/json).\n *\n * Protocol spec: Output formatting\n */\n\nimport type { ModuleDescriptor } from \"./cli.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve output format with TTY-adaptive default.\n */\nexport function resolveFormat(explicitFormat?: string): string {\n if (explicitFormat !== undefined) {\n return explicitFormat;\n }\n return process.stdout.isTTY ? \"table\" : \"json\";\n}\n\n/**\n * Truncate text to maxLength, appending '...' if needed.\n */\nexport function truncate(text: string, maxLength = 80): string {\n if (text.length <= maxLength) {\n return text;\n }\n return text.slice(0, maxLength - 3) + \"...\";\n}\n\n/**\n * Render a simple plain-text table with column headers.\n */\nfunction formatTable(\n headers: string[],\n rows: string[][],\n): string {\n // Calculate column widths\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)),\n );\n\n const sep = colWidths.map((w) => \"-\".repeat(w)).join(\" \");\n const headerLine = headers\n .map((h, i) => h.padEnd(colWidths[i]))\n .join(\" \");\n const dataLines = rows.map((row) =>\n row.map((cell, i) => (cell ?? \"\").padEnd(colWidths[i])).join(\" \"),\n );\n\n return [headerLine, sep, ...dataLines].join(\"\\n\") + \"\\n\";\n}\n\n// ---------------------------------------------------------------------------\n// formatModuleList\n// ---------------------------------------------------------------------------\n\n/**\n * Format and print a list of modules.\n */\nexport function formatModuleList(\n modules: ModuleDescriptor[],\n format: string,\n filterTags?: string[],\n): void {\n if (format === \"table\") {\n if (modules.length === 0 && filterTags && filterTags.length > 0) {\n process.stdout.write(\n `No modules found matching tags: ${filterTags.join(\", \")}.\\n`,\n );\n return;\n }\n if (modules.length === 0) {\n process.stdout.write(\"No modules found.\\n\");\n return;\n }\n\n const headers = [\"ID\", \"Description\", \"Tags\"];\n const rows = modules.map((m) => [\n m.id,\n truncate(m.description, 80),\n (m.tags ?? []).join(\", \"),\n ]);\n process.stdout.write(formatTable(headers, rows));\n } else if (format === \"json\") {\n const result = modules.map((m) => ({\n id: m.id,\n description: m.description,\n tags: m.tags ?? [],\n }));\n process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// formatModuleDetail\n// ---------------------------------------------------------------------------\n\n/**\n * Convert annotations to a plain dict, filtering out falsy/default values.\n */\nfunction annotationsToDict(\n annotations: unknown,\n): Record<string, unknown> | null {\n if (!annotations) return null;\n if (typeof annotations !== \"object\" || Array.isArray(annotations)) return null;\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(annotations as Record<string, unknown>)) {\n if (v !== null && v !== undefined && v !== false && v !== 0 && !(Array.isArray(v) && v.length === 0)) {\n result[k] = v;\n }\n }\n return Object.keys(result).length > 0 ? result : null;\n}\n\n/**\n * Format and print full module metadata.\n */\nexport function formatModuleDetail(\n moduleDef: ModuleDescriptor,\n format: string,\n): void {\n if (format === \"table\") {\n process.stdout.write(`\\nModule: ${moduleDef.id}\\n`);\n process.stdout.write(`\\nDescription:\\n ${moduleDef.description}\\n`);\n\n if (moduleDef.inputSchema && Object.keys(moduleDef.inputSchema).length > 0) {\n process.stdout.write(\"\\nInput Schema:\\n\");\n process.stdout.write(JSON.stringify(moduleDef.inputSchema, null, 2) + \"\\n\");\n }\n\n if (moduleDef.outputSchema && Object.keys(moduleDef.outputSchema).length > 0) {\n process.stdout.write(\"\\nOutput Schema:\\n\");\n process.stdout.write(JSON.stringify(moduleDef.outputSchema, null, 2) + \"\\n\");\n }\n\n const annDict = annotationsToDict(\n moduleDef.annotations,\n );\n if (annDict) {\n process.stdout.write(\"\\nAnnotations:\\n\");\n for (const [k, v] of Object.entries(annDict)) {\n process.stdout.write(` ${k}: ${v}\\n`);\n }\n }\n\n // Extension metadata (x- prefixed)\n const metadata = moduleDef.metadata;\n if (metadata) {\n const xFields: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(metadata)) {\n if (k.startsWith(\"x-\") || k.startsWith(\"x_\")) {\n xFields[k] = v;\n }\n }\n if (Object.keys(xFields).length > 0) {\n process.stdout.write(\"\\nExtension Metadata:\\n\");\n for (const [k, v] of Object.entries(xFields)) {\n process.stdout.write(` ${k}: ${v}\\n`);\n }\n }\n }\n\n const tags = moduleDef.tags ?? [];\n if (tags.length > 0) {\n process.stdout.write(`\\nTags: ${tags.join(\", \")}\\n`);\n }\n } else if (format === \"json\") {\n const result: Record<string, unknown> = {\n id: moduleDef.id,\n description: moduleDef.description,\n };\n if (moduleDef.inputSchema) result.input_schema = moduleDef.inputSchema;\n if (moduleDef.outputSchema) result.output_schema = moduleDef.outputSchema;\n\n const annDict = annotationsToDict(\n moduleDef.annotations,\n );\n if (annDict) result.annotations = annDict;\n\n const tags = moduleDef.tags ?? [];\n if (tags.length > 0) result.tags = tags;\n\n // Extension metadata\n const metadata = moduleDef.metadata;\n if (metadata) {\n for (const [k, v] of Object.entries(metadata)) {\n if (k.startsWith(\"x-\") || k.startsWith(\"x_\")) {\n result[k] = v;\n }\n }\n }\n\n process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// formatExecResult\n// ---------------------------------------------------------------------------\n\n/**\n * Format and print module execution result.\n */\nexport function formatExecResult(\n result: unknown,\n format?: string,\n): void {\n if (result === null || result === undefined) {\n return;\n }\n const effective = resolveFormat(format);\n if (\n effective === \"table\" &&\n typeof result === \"object\" &&\n !Array.isArray(result)\n ) {\n // Key-value table\n const entries = Object.entries(result as Record<string, unknown>);\n const headers = [\"Key\", \"Value\"];\n const rows = entries.map(([k, v]) => [String(k), String(v)]);\n process.stdout.write(formatTable(headers, rows));\n } else if (typeof result === \"object\") {\n process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n } else if (typeof result === \"string\") {\n process.stdout.write(result + \"\\n\");\n } else {\n process.stdout.write(String(result) + \"\\n\");\n }\n}\n","/**\n * Simple structured logger respecting logging.level config.\n */\n\nconst LEVELS = { DEBUG: 0, INFO: 1, WARNING: 2, ERROR: 3 } as const;\ntype LogLevel = keyof typeof LEVELS;\n\nlet currentLevel: LogLevel = \"WARNING\";\n\nexport function setLogLevel(level: string): void {\n const upper = level.toUpperCase();\n if (upper in LEVELS) {\n currentLevel = upper as LogLevel;\n }\n}\n\nexport function getLogLevel(): LogLevel {\n return currentLevel;\n}\n\nfunction shouldLog(level: LogLevel): boolean {\n return LEVELS[level] >= LEVELS[currentLevel];\n}\n\nexport function debug(message: string): void {\n if (shouldLog(\"DEBUG\")) process.stderr.write(`DEBUG: ${message}\\n`);\n}\n\nexport function info(message: string): void {\n if (shouldLog(\"INFO\")) process.stderr.write(`INFO: ${message}\\n`);\n}\n\nexport function warn(message: string): void {\n if (shouldLog(\"WARNING\")) process.stderr.write(`WARNING: ${message}\\n`);\n}\n\nexport function error(message: string): void {\n if (shouldLog(\"ERROR\")) process.stderr.write(`ERROR: ${message}\\n`);\n}\n"],"mappings":";;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;;ACkGO,SAAS,iBAAiB,OAA0B;AACzD,MAAI,iBAAiB,sBAAsB;AACzC,WAAO,WAAW;AAAA,EACpB;AACA,MAAI,iBAAiB,qBAAqB;AACxC,WAAO,WAAW;AAAA,EACpB;AACA,MAAI,iBAAiB,qBAAqB;AACxC,WAAO,WAAW;AAAA,EACpB;AACA,MAAI,iBAAiB,uBAAuB;AAC1C,WAAO,WAAW;AAAA,EACpB;AACA,MAAI,iBAAiB,uBAAuB;AAC1C,WAAO,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iB,GAAG,OAAO,CAAC;AACxF,IAAM,UAAkB,IAAI;AAsCrB,SAAS,UACd,eACA,UACS;AAET,QAAM,mBAAmB,YAAiB,eAAS,QAAQ,KAAK,CAAC,KAAK,YAAY,KAAK;AAGvF,QAAM,cAAc,QAAQ,IAAI,4BAA4B,QAAQ,IAAI,wBAAwB;AAChG,cAAY,WAAW;AAEvB,QAAM,UAAU,IAAI,QAAQ,gBAAgB,EACzC,aAAa,EACb,QAAQ,SAAS,aAAa,QAAQ,gBAAgB,UAAU,EAChE,YAAY,gEAA2D,EACvE,OAAO,2BAA2B,8BAA8B,EAChE,OAAO,uBAAuB,4CAA4C,SAAS;AAItF,OAAK;AAEL,SAAO;AACT;AASO,SAAS,KAAK,UAAyB;AAC5C,QAAM,UAAU,UAAU,QAAW,QAAQ;AAE7C,MAAI;AACF,YAAQ,MAAM,QAAQ,IAAI;AAAA,EAC5B,SAAS,OAAgB;AACvB,QAAI,iBAAiB,gBAAgB;AAEnC,cAAQ,KAAK,MAAM,QAAQ;AAAA,IAC7B;AACA,UAAM,OAAO,iBAAiB,KAAK;AACnC,QAAI,iBAAiB,OAAO;AAC1B,cAAQ,OAAO,MAAM,UAAU,MAAM,OAAO;AAAA,CAAI;AAAA,IAClD;AACA,YAAQ,KAAK,IAAI;AAAA,EACnB;AACF;;;ADjGA,KAAK,YAAY;","names":["fileURLToPath","path","__dirname","fileURLToPath"]}
@@ -39,8 +39,9 @@ interface ModuleDescriptor {
39
39
  declare class LazyModuleGroup {
40
40
  private readonly registry;
41
41
  readonly executor: Executor;
42
+ private readonly helpTextMaxLength;
42
43
  private commandCache;
43
- constructor(registry: Registry, executor: Executor);
44
+ constructor(registry: Registry, executor: Executor, helpTextMaxLength?: number);
44
45
  /**
45
46
  * List all available command names from the Registry.
46
47
  *
@@ -96,7 +97,7 @@ declare function main(progName?: string): void;
96
97
  /**
97
98
  * Build a Commander Command for a single apcore module.
98
99
  */
99
- declare function buildModuleCommand(moduleDef: ModuleDescriptor, executor: Executor): Command;
100
+ declare function buildModuleCommand(moduleDef: ModuleDescriptor, executor: Executor, helpTextMaxLength?: number): Command;
100
101
  /**
101
102
  * Validate that a module ID conforms to the expected format.
102
103
  * Pattern: [a-z][a-z0-9_]*(.[a-z][a-z0-9_])* — max 128 chars.
@@ -215,12 +216,12 @@ declare function mapType(propName: string, propSchema: Record<string, unknown>):
215
216
  /**
216
217
  * Extract help text from schema property, preferring x-llm-description.
217
218
  */
218
- declare function extractHelp(propSchema: Record<string, unknown>): string | undefined;
219
+ declare function extractHelp(propSchema: Record<string, unknown>, maxLength?: number): string | undefined;
219
220
  /**
220
221
  * Convert a JSON Schema `properties` object into an array of
221
222
  * Commander option configurations.
222
223
  */
223
- declare function schemaToCliOptions(schema: Record<string, unknown>): OptionConfig[];
224
+ declare function schemaToCliOptions(schema: Record<string, unknown>, maxHelpLength?: number): OptionConfig[];
224
225
 
225
226
  /**
226
227
  * Interactive approval prompts with timeout.
package/dist/src/index.js CHANGED
@@ -8,11 +8,11 @@ var __export = (target, all) => {
8
8
  __defProp(target, name, { get: all[name], enumerable: true });
9
9
  };
10
10
 
11
- // node_modules/.pnpm/tsup@8.5.1_postcss@8.5.8_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js
11
+ // node_modules/tsup/assets/esm_shims.js
12
12
  import path from "path";
13
13
  import { fileURLToPath } from "url";
14
14
  var init_esm_shims = __esm({
15
- "node_modules/.pnpm/tsup@8.5.1_postcss@8.5.8_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js"() {
15
+ "node_modules/tsup/assets/esm_shims.js"() {
16
16
  "use strict";
17
17
  }
18
18
  });
@@ -663,7 +663,7 @@ function mapType(propName, propSchema) {
663
663
  }
664
664
  return typeMap[schemaType] ?? "string";
665
665
  }
666
- function extractHelp(propSchema) {
666
+ function extractHelp(propSchema, maxLength = 1e3) {
667
667
  let text = propSchema["x-llm-description"];
668
668
  if (!text) {
669
669
  text = propSchema.description;
@@ -671,13 +671,13 @@ function extractHelp(propSchema) {
671
671
  if (!text) {
672
672
  return void 0;
673
673
  }
674
- if (text.length > 200) {
675
- return text.slice(0, 197) + "...";
674
+ if (maxLength > 0 && text.length > maxLength) {
675
+ return text.slice(0, maxLength - 3) + "...";
676
676
  }
677
677
  return text;
678
678
  }
679
679
  var RESERVED_NAMES = /* @__PURE__ */ new Set(["input", "yes", "large_input", "format", "sandbox"]);
680
- function schemaToCliOptions(schema) {
680
+ function schemaToCliOptions(schema, maxHelpLength = 1e3) {
681
681
  const properties = schema.properties ?? {};
682
682
  const requiredList = schema.required ?? [];
683
683
  const options = [];
@@ -701,7 +701,7 @@ function schemaToCliOptions(schema) {
701
701
  }
702
702
  const typeResult = mapType(propName, propSchema);
703
703
  const isRequired = requiredList.includes(propName);
704
- const helpBase = extractHelp(propSchema);
704
+ const helpBase = extractHelp(propSchema, maxHelpLength);
705
705
  const helpText = isRequired ? (helpBase ? helpBase + " " : "") + "[required]" : helpBase ?? "";
706
706
  const defaultValue = propSchema.default;
707
707
  if (typeResult === BOOLEAN_FLAG) {
@@ -1084,7 +1084,7 @@ function main(progName) {
1084
1084
  process.exit(code);
1085
1085
  }
1086
1086
  }
1087
- function buildModuleCommand(moduleDef, executor) {
1087
+ function buildModuleCommand(moduleDef, executor, helpTextMaxLength = 1e3) {
1088
1088
  const moduleId = moduleDef.id;
1089
1089
  let resolvedSchema = {};
1090
1090
  let schemaOptions = [];
@@ -1095,7 +1095,7 @@ function buildModuleCommand(moduleDef, executor) {
1095
1095
  } catch {
1096
1096
  resolvedSchema = inputSchema;
1097
1097
  }
1098
- schemaOptions = schemaToCliOptions(resolvedSchema);
1098
+ schemaOptions = schemaToCliOptions(resolvedSchema, helpTextMaxLength);
1099
1099
  }
1100
1100
  const cmd = new Command(moduleId).description(moduleDef.description);
1101
1101
  cmd.option("--input <source>", "Read input from STDIN ('-')");
@@ -1261,10 +1261,12 @@ init_esm_shims();
1261
1261
  var LazyModuleGroup = class {
1262
1262
  registry;
1263
1263
  executor;
1264
+ helpTextMaxLength;
1264
1265
  commandCache = /* @__PURE__ */ new Map();
1265
- constructor(registry, executor) {
1266
+ constructor(registry, executor, helpTextMaxLength = 1e3) {
1266
1267
  this.registry = registry;
1267
1268
  this.executor = executor;
1269
+ this.helpTextMaxLength = helpTextMaxLength;
1268
1270
  }
1269
1271
  /**
1270
1272
  * List all available command names from the Registry.
@@ -1287,7 +1289,7 @@ var LazyModuleGroup = class {
1287
1289
  if (!moduleDef) {
1288
1290
  return null;
1289
1291
  }
1290
- const cmd = buildModuleCommand(moduleDef, this.executor);
1292
+ const cmd = buildModuleCommand(moduleDef, this.executor, this.helpTextMaxLength);
1291
1293
  this.commandCache.set(cmdName, cmd);
1292
1294
  return cmd;
1293
1295
  }
@@ -1302,7 +1304,8 @@ var DEFAULTS = {
1302
1304
  "logging.level": "WARNING",
1303
1305
  "sandbox.enabled": false,
1304
1306
  "cli.stdin_buffer_limit": 10485760,
1305
- "cli.auto_approve": false
1307
+ "cli.auto_approve": false,
1308
+ "cli.help_text_max_length": 1e3
1306
1309
  };
1307
1310
  var ConfigResolver = class {
1308
1311
  cliFlags;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.8_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js","../../src/errors.ts","../../src/security/audit.ts","../../src/security/config-encryptor.ts","../../src/security/auth.ts","../../src/security/sandbox.ts","../../src/security/index.ts","../../src/index.ts","../../src/main.ts","../../src/ref-resolver.ts","../../src/schema-parser.ts","../../src/approval.ts","../../src/output.ts","../../src/logger.ts","../../src/cli.ts","../../src/config.ts","../../src/discovery.ts","../../src/shell.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Error classes and exit code mapping for apcore-cli.\n *\n * Protocol spec: Error handling & exit codes\n */\n\n// ---------------------------------------------------------------------------\n// Error classes\n// ---------------------------------------------------------------------------\n\n/** Thrown when the user does not approve module execution within the timeout. */\nexport class ApprovalTimeoutError extends Error {\n constructor(message = \"Approval timed out\") {\n super(message);\n this.name = \"ApprovalTimeoutError\";\n }\n}\n\n/** Thrown when API key authentication fails or is missing. */\nexport class AuthenticationError extends Error {\n constructor(message = \"Authentication failed\") {\n super(message);\n this.name = \"AuthenticationError\";\n }\n}\n\n/** Thrown when encrypted config cannot be decrypted. */\nexport class ConfigDecryptionError extends Error {\n constructor(message = \"Config decryption failed\") {\n super(message);\n this.name = \"ConfigDecryptionError\";\n }\n}\n\n/** Thrown when module execution fails. */\nexport class ModuleExecutionError extends Error {\n constructor(message = \"Module execution failed\") {\n super(message);\n this.name = \"ModuleExecutionError\";\n }\n}\n\n/** Thrown when approval is denied by the user. */\nexport class ApprovalDeniedError extends Error {\n constructor(message = \"Approval denied\") {\n super(message);\n this.name = \"ApprovalDeniedError\";\n }\n}\n\n/** Thrown when schema validation fails. */\nexport class SchemaValidationError extends Error {\n constructor(message = \"Schema validation failed\") {\n super(message);\n this.name = \"SchemaValidationError\";\n }\n}\n\n/** Thrown when a module is not found. */\nexport class ModuleNotFoundError extends Error {\n constructor(message = \"Module not found\") {\n super(message);\n this.name = \"ModuleNotFoundError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Exit code map\n// ---------------------------------------------------------------------------\n\nexport const EXIT_CODES = {\n SUCCESS: 0,\n MODULE_EXECUTE_ERROR: 1,\n MODULE_TIMEOUT: 1,\n INVALID_CLI_INPUT: 2,\n MODULE_NOT_FOUND: 44,\n MODULE_LOAD_ERROR: 44,\n MODULE_DISABLED: 44,\n SCHEMA_VALIDATION_ERROR: 45,\n APPROVAL_DENIED: 46,\n APPROVAL_TIMEOUT: 46,\n CONFIG_NOT_FOUND: 47,\n CONFIG_INVALID: 47,\n SCHEMA_CIRCULAR_REF: 48,\n ACL_DENIED: 77,\n KEYBOARD_INTERRUPT: 130,\n} as const;\n\nexport type ExitCode = (typeof EXIT_CODES)[keyof typeof EXIT_CODES];\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Map a caught error to the appropriate process exit code.\n * Also checks for apcore error codes on the error object.\n */\nexport function exitCodeForError(error: unknown): ExitCode {\n if (error instanceof ApprovalTimeoutError) {\n return EXIT_CODES.APPROVAL_TIMEOUT;\n }\n if (error instanceof ApprovalDeniedError) {\n return EXIT_CODES.APPROVAL_DENIED;\n }\n if (error instanceof AuthenticationError) {\n return EXIT_CODES.ACL_DENIED;\n }\n if (error instanceof ConfigDecryptionError) {\n return EXIT_CODES.CONFIG_INVALID;\n }\n if (error instanceof SchemaValidationError) {\n return EXIT_CODES.SCHEMA_VALIDATION_ERROR;\n }\n if (error instanceof ModuleNotFoundError) {\n return EXIT_CODES.MODULE_NOT_FOUND;\n }\n if (error instanceof ModuleExecutionError) {\n return EXIT_CODES.MODULE_EXECUTE_ERROR;\n }\n\n // Check for apcore error codes on the error object\n if (error instanceof Error) {\n const code = (error as unknown as Record<string, unknown>).code as string | undefined;\n const codeMap: Record<string, ExitCode> = {\n MODULE_NOT_FOUND: EXIT_CODES.MODULE_NOT_FOUND,\n MODULE_LOAD_ERROR: EXIT_CODES.MODULE_LOAD_ERROR,\n MODULE_DISABLED: EXIT_CODES.MODULE_DISABLED,\n SCHEMA_VALIDATION_ERROR: EXIT_CODES.SCHEMA_VALIDATION_ERROR,\n SCHEMA_CIRCULAR_REF: EXIT_CODES.SCHEMA_CIRCULAR_REF,\n APPROVAL_DENIED: EXIT_CODES.APPROVAL_DENIED,\n APPROVAL_TIMEOUT: EXIT_CODES.APPROVAL_TIMEOUT,\n CONFIG_NOT_FOUND: EXIT_CODES.CONFIG_NOT_FOUND,\n CONFIG_INVALID: EXIT_CODES.CONFIG_INVALID,\n MODULE_EXECUTE_ERROR: EXIT_CODES.MODULE_EXECUTE_ERROR,\n MODULE_TIMEOUT: EXIT_CODES.MODULE_TIMEOUT,\n ACL_DENIED: EXIT_CODES.ACL_DENIED,\n };\n if (code && code in codeMap) {\n return codeMap[code];\n }\n }\n\n return EXIT_CODES.MODULE_EXECUTE_ERROR;\n}\n","/**\n * AuditLogger — JSONL audit trail.\n *\n * Protocol spec: Security — audit logging\n */\n\nimport * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ntype ExecutionStatus = \"success\" | \"error\";\n\ninterface AuditEntry {\n timestamp: string;\n user: string;\n module_id: string;\n input_hash: string;\n status: ExecutionStatus;\n exit_code: number;\n duration_ms: number;\n}\n\n// ---------------------------------------------------------------------------\n// AuditLogger\n// ---------------------------------------------------------------------------\n\n/**\n * Appends structured JSONL entries to an audit log file for every module\n * execution, supporting compliance and debugging.\n */\nlet _auditLogger: AuditLogger | null = null;\n\n/**\n * Set the module-level audit logger instance.\n */\nexport function setAuditLogger(auditLogger: AuditLogger | null): void {\n _auditLogger = auditLogger;\n}\n\n/**\n * Get the current module-level audit logger instance.\n */\nexport function getAuditLogger(): AuditLogger | null {\n return _auditLogger;\n}\n\nexport class AuditLogger {\n static readonly DEFAULT_PATH = path.join(\n os.homedir(),\n \".apcore-cli\",\n \"audit.jsonl\",\n );\n\n private readonly logPath: string;\n\n constructor(path?: string) {\n this.logPath = path ?? AuditLogger.DEFAULT_PATH;\n this.ensureDirectory();\n }\n\n private ensureDirectory(): void {\n try {\n fs.mkdirSync(path.dirname(this.logPath), { recursive: true });\n } catch {\n // Silently ignore — we'll handle write errors in logExecution\n }\n }\n\n logExecution(\n moduleId: string,\n inputData: Record<string, unknown>,\n status: ExecutionStatus,\n exitCode: number,\n durationMs: number,\n ): void {\n const entry: AuditEntry = {\n timestamp: new Date().toISOString(),\n user: this.getUser(),\n module_id: moduleId,\n input_hash: this.hashInput(inputData),\n status,\n exit_code: exitCode,\n duration_ms: durationMs,\n };\n try {\n fs.appendFileSync(this.logPath, JSON.stringify(entry) + \"\\n\");\n } catch (err) {\n console.warn(`Could not write audit log: ${err}`);\n }\n }\n\n private hashInput(inputData: Record<string, unknown>): string {\n const salt = crypto.randomBytes(16);\n const sortedKeys = Object.keys(inputData).sort();\n const payload = JSON.stringify(inputData, sortedKeys);\n return crypto\n .createHash(\"sha256\")\n .update(Buffer.concat([salt, Buffer.from(payload, \"utf-8\")]))\n .digest(\"hex\");\n }\n\n private getUser(): string {\n try {\n return os.userInfo().username;\n } catch {\n return process.env.USER ?? process.env.USERNAME ?? \"unknown\";\n }\n }\n}\n","/**\n * ConfigEncryptor — Keyring + AES-256-GCM fallback.\n *\n * Protocol spec: Security — config encryption\n */\n\nimport * as crypto from \"node:crypto\";\nimport * as os from \"node:os\";\nimport { ConfigDecryptionError } from \"../errors.js\";\n\n// ---------------------------------------------------------------------------\n// Keytar dynamic import helper\n// ---------------------------------------------------------------------------\n\nlet keytarModule: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any\nasync function getKeytar(): Promise<any> { // eslint-disable-line @typescript-eslint/no-explicit-any\n if (keytarModule) return keytarModule;\n try {\n // @ts-expect-error — keytar is an optional peer dependency\n keytarModule = await import(\"keytar\");\n return keytarModule;\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// ConfigEncryptor\n// ---------------------------------------------------------------------------\n\n/**\n * Encrypts and decrypts configuration values. Prefers OS keyring for key\n * storage, falling back to AES-256-GCM with a derived key.\n */\nexport class ConfigEncryptor {\n static readonly SERVICE_NAME = \"apcore-cli\";\n\n /**\n * Encrypt and store a configuration value.\n */\n async store(key: string, value: string): Promise<string> {\n const keytar = await getKeytar();\n if (keytar) {\n try {\n await keytar.setPassword(ConfigEncryptor.SERVICE_NAME, key, value);\n return `keyring:${key}`;\n } catch {\n // Fall through to file-based encryption\n }\n }\n console.warn(\"OS keyring unavailable. Using file-based encryption.\");\n const ciphertext = this.aesEncrypt(value);\n return `enc:${Buffer.from(ciphertext).toString(\"base64\")}`;\n }\n\n /**\n * Retrieve and decrypt a configuration value.\n */\n async retrieve(configValue: string, key: string): Promise<string> {\n if (configValue.startsWith(\"keyring:\")) {\n const keytar = await getKeytar();\n if (!keytar) {\n throw new ConfigDecryptionError(\n `Keyring module not available to retrieve '${key}'.`,\n );\n }\n try {\n const refKey = configValue.slice(\"keyring:\".length);\n const result = await keytar.getPassword(\n ConfigEncryptor.SERVICE_NAME,\n refKey,\n );\n if (result === null || result === undefined) {\n throw new ConfigDecryptionError(\n `Keyring entry not found for '${refKey}'.`,\n );\n }\n return result;\n } catch (err) {\n if (err instanceof ConfigDecryptionError) throw err;\n throw new ConfigDecryptionError(\n `Failed to retrieve from keyring: ${err}`,\n );\n }\n }\n\n if (configValue.startsWith(\"enc:\")) {\n const ciphertext = Buffer.from(\n configValue.slice(\"enc:\".length),\n \"base64\",\n );\n try {\n return this.aesDecrypt(ciphertext);\n } catch {\n throw new ConfigDecryptionError(\n `Failed to decrypt configuration value '${key}'. Re-configure with 'apcore-cli config set ${key}'.`,\n );\n }\n }\n\n // Unrecognized prefix — return as-is\n return configValue;\n }\n\n // NOTE: Best-effort fallback when OS keyring is unavailable.\n // The key is derived from hostname + username (non-secret inputs).\n // For production security, ensure the OS keyring is accessible.\n private deriveKey(): Buffer {\n const hostname = os.hostname();\n const username =\n process.env.USER ?? process.env.USERNAME ?? \"unknown\";\n const salt = Buffer.from(\"apcore-cli-config-v1\");\n const material = `${hostname}:${username}`;\n return crypto.pbkdf2Sync(material, salt, 100_000, 32, \"sha256\");\n }\n\n private aesEncrypt(plaintext: string): Buffer {\n const key = this.deriveKey();\n const nonce = crypto.randomBytes(12);\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce);\n const ct = Buffer.concat([\n cipher.update(plaintext, \"utf-8\"),\n cipher.final(),\n ]);\n const tag = cipher.getAuthTag();\n // Wire format: nonce(12) + tag(16) + ciphertext\n return Buffer.concat([nonce, tag, ct]);\n }\n\n private aesDecrypt(data: Buffer): string {\n const key = this.deriveKey();\n const nonce = data.subarray(0, 12);\n const tag = data.subarray(12, 28);\n const ct = data.subarray(28);\n const decipher = crypto.createDecipheriv(\"aes-256-gcm\", key, nonce);\n decipher.setAuthTag(tag);\n const plaintext = Buffer.concat([decipher.update(ct), decipher.final()]);\n return plaintext.toString(\"utf-8\");\n }\n}\n","/**\n * AuthProvider — API key auth with keyring/encrypted storage.\n *\n * Protocol spec: Security — authentication\n */\n\nimport type { ConfigResolver } from \"../config.js\";\nimport { AuthenticationError } from \"../errors.js\";\nimport { ConfigEncryptor } from \"./config-encryptor.js\";\n\n// ---------------------------------------------------------------------------\n// AuthProvider\n// ---------------------------------------------------------------------------\n\n/**\n * Manages API key retrieval and request authentication.\n */\nexport class AuthProvider {\n private readonly config: ConfigResolver;\n private readonly encryptor: ConfigEncryptor;\n\n constructor(config: ConfigResolver, encryptor?: ConfigEncryptor) {\n this.config = config;\n this.encryptor = encryptor ?? new ConfigEncryptor();\n }\n\n /**\n * Retrieve the API key from the configured sources.\n * Handles keyring: and enc: prefixes via ConfigEncryptor.\n */\n async getApiKey(): Promise<string | null> {\n const result = this.config.resolve(\n \"auth.api_key\",\n \"--api-key\",\n \"APCORE_AUTH_API_KEY\",\n );\n if (result === null || result === undefined) {\n return null;\n }\n const strResult = String(result);\n if (strResult.startsWith(\"keyring:\") || strResult.startsWith(\"enc:\")) {\n return this.encryptor.retrieve(strResult, \"auth.api_key\");\n }\n return strResult;\n }\n\n /**\n * Add authentication headers to an outgoing request.\n */\n async authenticateRequest(\n headers: Record<string, string>,\n ): Promise<Record<string, string>> {\n const key = await this.getApiKey();\n if (!key) {\n throw new AuthenticationError(\n \"Remote registry requires authentication. \" +\n \"Set --api-key, APCORE_AUTH_API_KEY, or auth.api_key in config.\",\n );\n }\n return { ...headers, Authorization: `Bearer ${key}` };\n }\n\n /**\n * Handle an HTTP response status code for auth-related errors.\n */\n handleResponse(statusCode: number): void {\n if (statusCode === 401 || statusCode === 403) {\n throw new AuthenticationError(\n \"Authentication failed. Verify your API key.\",\n );\n }\n }\n}\n","/**\n * Sandbox — Subprocess isolation for module execution.\n *\n * Protocol spec: Security — sandboxed execution\n */\n\nimport * as child_process from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport type { Executor } from \"../cli.js\";\nimport { ModuleExecutionError } from \"../errors.js\";\n\n// ---------------------------------------------------------------------------\n// Sandbox\n// ---------------------------------------------------------------------------\n\n/**\n * Executes modules in an isolated subprocess to limit the blast radius\n * of untrusted or third-party modules.\n *\n * When disabled, delegates directly to the Executor.\n */\nexport class Sandbox {\n private readonly enabled: boolean;\n\n constructor(enabled = false) {\n this.enabled = enabled;\n }\n\n /**\n * Execute a module, optionally inside a sandboxed subprocess.\n */\n async execute(\n moduleId: string,\n inputData: Record<string, unknown>,\n executor: Executor,\n ): Promise<unknown> {\n if (!this.enabled) {\n return executor.execute(moduleId, inputData);\n }\n return this.sandboxedExecute(moduleId, inputData);\n }\n\n private sandboxedExecute(\n moduleId: string,\n inputData: Record<string, unknown>,\n ): unknown {\n // Build restricted environment\n const env: Record<string, string> = {};\n for (const key of [\"PATH\", \"NODE_PATH\", \"LANG\", \"LC_ALL\"]) {\n if (process.env[key]) {\n env[key] = process.env[key]!;\n }\n }\n for (const [key, value] of Object.entries(process.env)) {\n if (key.startsWith(\"APCORE_\") && value) {\n env[key] = value;\n }\n }\n\n const tmpDir = fs.mkdtempSync(\n path.join(os.tmpdir(), \"apcore_sandbox_\"),\n );\n\n try {\n env.HOME = tmpDir;\n env.TMPDIR = tmpDir;\n\n const script = [\n \"let d='';\",\n \"process.stdin.setEncoding('utf-8');\",\n \"process.stdin.on('data',c=>d+=c);\",\n \"process.stdin.on('end',()=>{\",\n \" const input=JSON.parse(d);\",\n ` process.stdout.write(JSON.stringify({error:\"Sandbox runner not yet implemented for module: ${moduleId}\"}));`,\n \"});\",\n ].join(\"\");\n\n const result = child_process.execFileSync(\n process.execPath,\n [\"-e\", script],\n {\n input: JSON.stringify(inputData),\n env,\n cwd: tmpDir,\n timeout: 300_000,\n maxBuffer: 10 * 1024 * 1024,\n },\n );\n\n return JSON.parse(result.toString(\"utf-8\"));\n } catch (err: unknown) {\n if (\n err instanceof Error &&\n \"killed\" in err &&\n (err as Record<string, unknown>).killed\n ) {\n throw new ModuleExecutionError(\n `Error: Module '${moduleId}' timed out in sandbox.`,\n );\n }\n const stderr =\n err instanceof Error && \"stderr\" in err\n ? String((err as Record<string, unknown>).stderr)\n : String(err);\n throw new ModuleExecutionError(\n `Error: Module '${moduleId}' execution failed: ${stderr}`,\n );\n } finally {\n try {\n fs.rmSync(tmpDir, { recursive: true, force: true });\n } catch {\n // Best effort cleanup\n }\n }\n }\n}\n","/**\n * Security module re-exports.\n *\n * Protocol spec: Security subsystem\n */\n\nexport { AuditLogger, setAuditLogger, getAuditLogger } from \"./audit.js\";\nexport { AuthProvider } from \"./auth.js\";\nexport { ConfigEncryptor } from \"./config-encryptor.js\";\nexport { Sandbox } from \"./sandbox.js\";\n","/**\n * apcore-cli — Public API exports.\n *\n * This module re-exports the public surface of the apcore CLI package.\n */\n\n// Core CLI\nexport { createCli, main, buildModuleCommand, validateModuleId, collectInput, reconvertEnumValues } from \"./main.js\";\nexport type { OptionConfig } from \"./main.js\";\n\n// Lazy module loading\nexport { LazyModuleGroup } from \"./cli.js\";\nexport type { Registry, Executor, ModuleDescriptor } from \"./cli.js\";\n\n// Configuration\nexport { ConfigResolver, DEFAULTS } from \"./config.js\";\n\n// Discovery\nexport { registerDiscoveryCommands } from \"./discovery.js\";\n\n// Output formatting\nexport { formatExecResult, resolveFormat, truncate, formatModuleList, formatModuleDetail } from \"./output.js\";\n\n// Schema handling\nexport { resolveRefs } from \"./ref-resolver.js\";\nexport { schemaToCliOptions, mapType, extractHelp } from \"./schema-parser.js\";\n\n// Approval\nexport { checkApproval } from \"./approval.js\";\n\n// Shell integration\nexport { registerShellCommands } from \"./shell.js\";\n\n// Errors\nexport {\n ApprovalTimeoutError,\n ApprovalDeniedError,\n AuthenticationError,\n ConfigDecryptionError,\n ModuleExecutionError,\n ModuleNotFoundError,\n SchemaValidationError,\n EXIT_CODES,\n exitCodeForError,\n} from \"./errors.js\";\nexport type { ExitCode } from \"./errors.js\";\n\n// Logger\nexport { setLogLevel, getLogLevel, debug, info, warn, error } from \"./logger.js\";\n\n// Security\nexport { AuditLogger, setAuditLogger, getAuditLogger, AuthProvider, ConfigEncryptor, Sandbox } from \"./security/index.js\";\n","/**\n * CLI entry point — createCli / main equivalents.\n *\n * Protocol spec: CLI bootstrapping & command registration\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport * as path from \"node:path\";\nimport { Command, CommanderError } from \"commander\";\nimport { EXIT_CODES, exitCodeForError } from \"./errors.js\";\nimport { resolveRefs } from \"./ref-resolver.js\";\nimport { schemaToCliOptions } from \"./schema-parser.js\";\nimport { checkApproval } from \"./approval.js\";\nimport { formatExecResult } from \"./output.js\";\nimport { setLogLevel } from \"./logger.js\";\nimport type { Executor, ModuleDescriptor } from \"./cli.js\";\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(path.resolve(__dirname, \"../package.json\"), \"utf-8\"));\nconst VERSION: string = pkg.version;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Configuration for a single Commander option derived from a JSON Schema property. */\nexport interface OptionConfig {\n /** The property name from the schema. */\n name: string;\n /** Commander flags string (e.g. \"--my-flag <value>\" or \"--flag, --no-flag\"). */\n flags: string;\n /** Help text for the option. */\n description: string;\n /** Default value. */\n defaultValue?: unknown;\n /** Whether the field is required (for display only). */\n required: boolean;\n /** Enum choices (string values). */\n choices?: string[];\n /** Whether this is a boolean flag pair (--flag/--no-flag). */\n isBooleanFlag?: boolean;\n /** Maps string enum value → original type name (\"int\", \"float\", \"bool\"). */\n enumOriginalTypes?: Record<string, string>;\n /** Parser function for Commander (e.g. parseInt, parseFloat). */\n parseArg?: (value: string) => unknown;\n}\n\n// ---------------------------------------------------------------------------\n// createCli\n// ---------------------------------------------------------------------------\n\n/**\n * Build and return the top-level Commander program.\n *\n * @param extensionsDir Path to the extensions directory (default: ./extensions)\n * @param progName Program name shown in help (default: apcore-cli)\n */\nexport function createCli(\n extensionsDir?: string,\n progName?: string,\n): Command {\n // Resolve program name\n const resolvedProgName = progName ?? path.basename(process.argv[1] ?? \"apcore-cli\") ?? \"apcore-cli\";\n\n // Resolve log level\n const cliLogLevel = process.env.APCORE_CLI_LOGGING_LEVEL ?? process.env.APCORE_LOGGING_LEVEL ?? \"WARNING\";\n setLogLevel(cliLogLevel);\n\n const program = new Command(resolvedProgName)\n .exitOverride()\n .version(VERSION, \"--version\", `Show ${resolvedProgName} version`)\n .description(\"apcore CLI — execute apcore modules from the command line\")\n .option(\"--extensions-dir <path>\", \"Path to extensions directory\")\n .option(\"--log-level <level>\", \"Logging level (DEBUG|INFO|WARNING|ERROR)\", \"WARNING\");\n\n // NOTE: Full registry/executor wiring requires apcore-js to be available.\n // For now, extensions-dir is accepted but not wired to a real registry.\n void extensionsDir;\n\n return program;\n}\n\n// ---------------------------------------------------------------------------\n// main\n// ---------------------------------------------------------------------------\n\n/**\n * Parse argv and run the CLI. Handles top-level error catching and exit codes.\n */\nexport function main(progName?: string): void {\n const program = createCli(undefined, progName);\n\n try {\n program.parse(process.argv);\n } catch (error: unknown) {\n if (error instanceof CommanderError) {\n // Commander already printed the error message\n process.exit(error.exitCode);\n }\n const code = exitCodeForError(error);\n if (error instanceof Error) {\n process.stderr.write(`Error: ${error.message}\\n`);\n }\n process.exit(code);\n }\n}\n\n// ---------------------------------------------------------------------------\n// buildModuleCommand\n// ---------------------------------------------------------------------------\n\n/**\n * Build a Commander Command for a single apcore module.\n */\nexport function buildModuleCommand(\n moduleDef: ModuleDescriptor,\n executor: Executor,\n): Command {\n const moduleId = moduleDef.id;\n let resolvedSchema: Record<string, unknown> = {};\n let schemaOptions: OptionConfig[] = [];\n\n // Resolve schema\n const inputSchema = moduleDef.inputSchema;\n if (inputSchema && typeof inputSchema === \"object\" && inputSchema.properties) {\n try {\n resolvedSchema = resolveRefs(inputSchema, 32, moduleId);\n } catch {\n resolvedSchema = inputSchema;\n }\n schemaOptions = schemaToCliOptions(resolvedSchema);\n }\n\n const cmd = new Command(moduleId).description(moduleDef.description);\n\n // Built-in options\n cmd.option(\"--input <source>\", \"Read input from STDIN ('-')\");\n cmd.option(\"-y, --yes\", \"Bypass approval prompts\", false);\n cmd.option(\"--large-input\", \"Allow STDIN input larger than 10MB\", false);\n cmd.option(\"--format <format>\", \"Output format (json|table)\");\n cmd.option(\"--sandbox\", \"Run module in subprocess sandbox\", false);\n\n // Schema-generated options\n for (const opt of schemaOptions) {\n if (opt.parseArg) {\n cmd.option(opt.flags, opt.description, opt.parseArg, opt.defaultValue);\n } else {\n cmd.option(opt.flags, opt.description, opt.defaultValue as string | boolean | undefined);\n }\n }\n\n // Action callback\n cmd.action(async (options: Record<string, unknown>) => {\n // Pop built-in options\n const stdinFlag = options.input as string | undefined;\n const autoApprove = options.yes as boolean;\n const largeInput = options.largeInput as boolean;\n const outputFormat = options.format as string | undefined;\n const sandboxEnabled = options.sandbox as boolean;\n\n // Remove built-in keys from options to get schema kwargs\n const schemaKwargs: Record<string, unknown> = {};\n const builtinKeys = new Set([\"input\", \"yes\", \"largeInput\", \"format\", \"sandbox\"]);\n for (const [k, v] of Object.entries(options)) {\n if (!builtinKeys.has(k)) {\n schemaKwargs[k] = v;\n }\n }\n\n try {\n // Collect and merge input\n const merged = await collectInput(stdinFlag, schemaKwargs, largeInput);\n\n // Reconvert enum values\n const reconverted = reconvertEnumValues(merged, schemaOptions);\n\n // Check approval\n await checkApproval(moduleDef, autoApprove);\n\n // Execute with timing\n const { Sandbox } = await import(\"./security/index.js\");\n const sandbox = new Sandbox(sandboxEnabled);\n const startTime = performance.now();\n const result = await sandbox.execute(moduleId, reconverted, executor);\n const durationMs = Math.round(performance.now() - startTime);\n\n // Audit log (success)\n const { getAuditLogger } = await import(\"./security/audit.js\");\n const auditLogger = getAuditLogger();\n if (auditLogger) {\n auditLogger.logExecution(moduleId, reconverted, \"success\", 0, durationMs);\n }\n\n // Format output\n formatExecResult(result, outputFormat);\n } catch (err: unknown) {\n // Audit log (error)\n const { getAuditLogger } = await import(\"./security/audit.js\");\n const auditLogger = getAuditLogger();\n const code = exitCodeForError(err);\n if (auditLogger) {\n auditLogger.logExecution(moduleId, {}, \"error\", code, 0);\n }\n\n if (err instanceof Error) {\n process.stderr.write(`Error: ${err.message}\\n`);\n }\n process.exit(code);\n }\n });\n\n return cmd;\n}\n\n// ---------------------------------------------------------------------------\n// validateModuleId\n// ---------------------------------------------------------------------------\n\n/**\n * Validate that a module ID conforms to the expected format.\n * Pattern: [a-z][a-z0-9_]*(.[a-z][a-z0-9_])* — max 128 chars.\n */\nexport function validateModuleId(moduleId: string): void {\n if (moduleId.length > 128) {\n process.stderr.write(\n `Error: Invalid module ID format: '${moduleId}'. Maximum length is 128 characters.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n if (!/^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)*$/.test(moduleId)) {\n process.stderr.write(\n `Error: Invalid module ID format: '${moduleId}'.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n}\n\n// ---------------------------------------------------------------------------\n// collectInput\n// ---------------------------------------------------------------------------\n\n/**\n * Collect module input from stdin and/or CLI keyword arguments.\n */\nexport async function collectInput(\n stdinFlag?: string,\n cliKwargs: Record<string, unknown> = {},\n largeInput?: boolean,\n): Promise<Record<string, unknown>> {\n // Remove null/undefined values from CLI kwargs\n const cliKwargsNonNull: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(cliKwargs)) {\n if (v !== null && v !== undefined) {\n cliKwargsNonNull[k] = v;\n }\n }\n\n if (!stdinFlag) {\n return cliKwargsNonNull;\n }\n\n if (stdinFlag === \"-\") {\n const raw = await readStdin();\n const rawSize = Buffer.byteLength(raw, \"utf-8\");\n\n if (rawSize > 10_485_760 && !largeInput) {\n process.stderr.write(\n \"Error: STDIN input exceeds 10MB limit. Use --large-input to override.\\n\",\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n if (!raw) {\n return cliKwargsNonNull;\n }\n\n let stdinData: unknown;\n try {\n stdinData = JSON.parse(raw);\n } catch {\n process.stderr.write(\n \"Error: STDIN does not contain valid JSON.\\n\",\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n if (typeof stdinData !== \"object\" || stdinData === null || Array.isArray(stdinData)) {\n process.stderr.write(\n `Error: STDIN JSON must be an object, got ${Array.isArray(stdinData) ? \"array\" : typeof stdinData}.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n // CLI flags override STDIN for duplicate keys\n return { ...(stdinData as Record<string, unknown>), ...cliKwargsNonNull };\n }\n\n return cliKwargsNonNull;\n}\n\n/**\n * Read all data from stdin with proper cleanup.\n */\nfunction readStdin(): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n const onData = (chunk: Buffer) => chunks.push(chunk);\n const onEnd = () => {\n cleanup();\n resolve(Buffer.concat(chunks).toString(\"utf-8\"));\n };\n const onError = (err: Error) => {\n cleanup();\n reject(err);\n };\n const cleanup = () => {\n process.stdin.removeListener(\"data\", onData);\n process.stdin.removeListener(\"end\", onEnd);\n process.stdin.removeListener(\"error\", onError);\n };\n process.stdin.on(\"data\", onData);\n process.stdin.on(\"end\", onEnd);\n process.stdin.on(\"error\", onError);\n process.stdin.resume();\n });\n}\n\n// ---------------------------------------------------------------------------\n// reconvertEnumValues\n// ---------------------------------------------------------------------------\n\n/**\n * Re-convert CLI string values back to their schema-typed equivalents\n * based on the option configs.\n */\nexport function reconvertEnumValues(\n kwargs: Record<string, unknown>,\n options: OptionConfig[],\n): Record<string, unknown> {\n const result = { ...kwargs };\n for (const opt of options) {\n if (!opt.enumOriginalTypes) continue;\n const paramName = opt.name;\n if (!(paramName in result) || result[paramName] === null || result[paramName] === undefined) {\n continue;\n }\n const strVal = String(result[paramName]);\n const origType = opt.enumOriginalTypes[strVal];\n if (origType === \"int\") {\n result[paramName] = parseInt(strVal, 10);\n } else if (origType === \"float\") {\n result[paramName] = parseFloat(strVal);\n } else if (origType === \"bool\") {\n result[paramName] = strVal.toLowerCase() === \"true\";\n }\n }\n return result;\n}\n","/**\n * JSON Schema $ref resolver.\n *\n * Protocol spec: Schema resolution & $ref handling\n */\n\nimport { EXIT_CODES } from \"./errors.js\";\n\n// ---------------------------------------------------------------------------\n// resolveRefs\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve all $ref references in a JSON Schema.\n * Returns a fully inlined schema with $defs/definitions removed.\n */\nexport function resolveRefs(\n schema: Record<string, unknown>,\n maxDepth = 32,\n moduleId = \"\",\n): Record<string, unknown> {\n const cloned = structuredClone(schema);\n const defs = (cloned.$defs ?? cloned.definitions ?? {}) as Record<\n string,\n unknown\n >;\n const result = resolveNode(\n cloned,\n defs,\n new Set<string>(),\n 0,\n maxDepth,\n moduleId,\n ) as Record<string, unknown>;\n\n // Remove definition keys\n delete result.$defs;\n delete result.definitions;\n return result;\n}\n\nfunction resolveNode(\n node: unknown,\n defs: Record<string, unknown>,\n visited: Set<string>,\n depth: number,\n maxDepth: number,\n moduleId: string,\n): unknown {\n if (typeof node !== \"object\" || node === null || Array.isArray(node)) {\n return node;\n }\n\n const obj = node as Record<string, unknown>;\n\n // Handle $ref\n if (\"$ref\" in obj) {\n const refPath = obj.$ref as string;\n\n if (depth >= maxDepth) {\n process.stderr.write(\n `Error: $ref resolution depth exceeded maximum of ${maxDepth} for module '${moduleId}'.\\n`,\n );\n process.exit(EXIT_CODES.SCHEMA_CIRCULAR_REF);\n }\n\n if (visited.has(refPath)) {\n process.stderr.write(\n `Error: Circular $ref detected in schema for module '${moduleId}' at path '${refPath}'.\\n`,\n );\n process.exit(EXIT_CODES.SCHEMA_CIRCULAR_REF);\n }\n\n // Parse ref target: extract key from \"#/$defs/Address\" → \"Address\"\n const parts = refPath.split(\"/\");\n const key = parts[parts.length - 1];\n\n if (!(key in defs)) {\n process.stderr.write(\n `Error: Unresolvable $ref '${refPath}' in schema for module '${moduleId}'.\\n`,\n );\n process.exit(EXIT_CODES.SCHEMA_VALIDATION_ERROR);\n }\n\n const newVisited = new Set(visited);\n newVisited.add(refPath);\n return resolveNode(defs[key], defs, newVisited, depth + 1, maxDepth, moduleId);\n }\n\n // Handle allOf\n if (\"allOf\" in obj && Array.isArray(obj.allOf)) {\n const merged: Record<string, unknown> = {\n properties: {},\n required: [] as string[],\n };\n for (const subSchema of obj.allOf as unknown[]) {\n const resolved = resolveNode(\n subSchema,\n defs,\n visited,\n depth + 1,\n maxDepth,\n moduleId,\n ) as Record<string, unknown>;\n if (resolved.properties) {\n Object.assign(\n merged.properties as Record<string, unknown>,\n resolved.properties,\n );\n }\n if (Array.isArray(resolved.required)) {\n (merged.required as string[]).push(...resolved.required);\n }\n }\n // Deduplicate required\n merged.required = [...new Set(merged.required as string[])];\n // Copy non-composition keys\n for (const [k, v] of Object.entries(obj)) {\n if (k !== \"allOf\" && !(k in merged)) {\n merged[k] = v;\n }\n }\n return merged;\n }\n\n // Handle anyOf / oneOf\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n if (keyword in obj && Array.isArray(obj[keyword])) {\n const merged: Record<string, unknown> = {\n properties: {},\n required: [] as string[],\n };\n const allRequiredSets: Set<string>[] = [];\n for (const subSchema of obj[keyword] as unknown[]) {\n const resolved = resolveNode(\n subSchema,\n defs,\n visited,\n depth + 1,\n maxDepth,\n moduleId,\n ) as Record<string, unknown>;\n if (resolved.properties) {\n Object.assign(\n merged.properties as Record<string, unknown>,\n resolved.properties,\n );\n }\n if (Array.isArray(resolved.required)) {\n allRequiredSets.push(new Set(resolved.required as string[]));\n }\n }\n // Required = intersection of all branches\n if (allRequiredSets.length > 0) {\n let intersection = allRequiredSets[0];\n for (let i = 1; i < allRequiredSets.length; i++) {\n intersection = new Set(\n [...intersection].filter((x) => allRequiredSets[i].has(x)),\n );\n }\n merged.required = [...intersection];\n } else {\n merged.required = [];\n }\n // Copy non-composition keys\n for (const [k, v] of Object.entries(obj)) {\n if (k !== keyword && !(k in merged)) {\n merged[k] = v;\n }\n }\n return merged;\n }\n }\n\n // Recursively process nested properties\n if (\"properties\" in obj && typeof obj.properties === \"object\" && obj.properties !== null) {\n const props = obj.properties as Record<string, unknown>;\n for (const [propName, propSchema] of Object.entries(props)) {\n props[propName] = resolveNode(\n propSchema,\n defs,\n visited,\n depth + 1,\n maxDepth,\n moduleId,\n );\n }\n }\n\n return obj;\n}\n","/**\n * JSON Schema -> Commander options mapping.\n *\n * Protocol spec: Schema-driven argument parsing\n */\n\nimport type { OptionConfig } from \"./main.js\";\nimport { EXIT_CODES } from \"./errors.js\";\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/** Sentinel type marker for boolean flags. */\nconst BOOLEAN_FLAG = Symbol(\"BOOLEAN_FLAG\");\n\ntype TypeResult = \"string\" | \"int\" | \"float\" | typeof BOOLEAN_FLAG | \"file\";\n\n/**\n * Map JSON Schema type to a type identifier.\n */\nexport function mapType(propName: string, propSchema: Record<string, unknown>): TypeResult {\n const schemaType = propSchema.type as string | undefined;\n\n // Check file convention\n if (\n schemaType === \"string\" &&\n (propName.endsWith(\"_file\") || propSchema[\"x-cli-file\"] === true)\n ) {\n return \"file\";\n }\n\n const typeMap: Record<string, TypeResult> = {\n string: \"string\",\n integer: \"int\",\n number: \"float\",\n boolean: BOOLEAN_FLAG,\n object: \"string\",\n array: \"string\",\n };\n\n if (!schemaType) {\n return \"string\";\n }\n\n return typeMap[schemaType] ?? \"string\";\n}\n\n/**\n * Extract help text from schema property, preferring x-llm-description.\n */\nexport function extractHelp(propSchema: Record<string, unknown>): string | undefined {\n let text = propSchema[\"x-llm-description\"] as string | undefined;\n if (!text) {\n text = propSchema.description as string | undefined;\n }\n if (!text) {\n return undefined;\n }\n if (text.length > 200) {\n return text.slice(0, 197) + \"...\";\n }\n return text;\n}\n\n// ---------------------------------------------------------------------------\n// schemaToCliOptions\n// ---------------------------------------------------------------------------\n\n/** Reserved CLI option names that cannot be used by schema properties. */\nconst RESERVED_NAMES = new Set([\"input\", \"yes\", \"large_input\", \"format\", \"sandbox\"]);\n\n/**\n * Convert a JSON Schema `properties` object into an array of\n * Commander option configurations.\n */\nexport function schemaToCliOptions(\n schema: Record<string, unknown>,\n): OptionConfig[] {\n const properties = (schema.properties ?? {}) as Record<\n string,\n Record<string, unknown>\n >;\n const requiredList = (schema.required ?? []) as string[];\n const options: OptionConfig[] = [];\n const flagNames: Record<string, string> = {};\n\n for (const [propName, propSchema] of Object.entries(properties)) {\n const flagName = \"--\" + propName.replace(/_/g, \"-\");\n\n // Collision detection\n if (flagName in flagNames) {\n process.stderr.write(\n `Error: Flag name collision: properties '${propName}' and '${flagNames[flagName]}' both map to '${flagName}'.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n flagNames[flagName] = propName;\n\n // Reserved name check\n if (RESERVED_NAMES.has(propName)) {\n process.stderr.write(\n `Error: Module schema property '${propName}' conflicts with a reserved CLI option name. Rename the property.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n const typeResult = mapType(propName, propSchema);\n const isRequired = requiredList.includes(propName);\n const helpBase = extractHelp(propSchema);\n const helpText = isRequired\n ? (helpBase ? helpBase + \" \" : \"\") + \"[required]\"\n : helpBase ?? \"\";\n const defaultValue = propSchema.default as unknown;\n\n if (typeResult === BOOLEAN_FLAG) {\n // Boolean flag pair: --flag/--no-flag\n const flagBase = propName.replace(/_/g, \"-\");\n const defaultVal = (propSchema.default as boolean) ?? false;\n options.push({\n name: propName,\n flags: `--${flagBase}, --no-${flagBase}`,\n description: helpText,\n defaultValue: defaultVal,\n required: false,\n isBooleanFlag: true,\n });\n } else if (\"enum\" in propSchema && Array.isArray(propSchema.enum)) {\n const enumValues = propSchema.enum as unknown[];\n if (enumValues.length === 0) {\n // Empty enum — fall back to plain string option\n options.push({\n name: propName,\n flags: `${flagName} <value>`,\n description: helpText,\n defaultValue,\n required: false,\n });\n } else {\n const stringValues = enumValues.map(String);\n const enumOriginalTypes: Record<string, string> = {};\n for (const v of enumValues) {\n if (typeof v === \"number\" && Number.isInteger(v)) {\n enumOriginalTypes[String(v)] = \"int\";\n } else if (typeof v === \"number\") {\n enumOriginalTypes[String(v)] = \"float\";\n } else if (typeof v === \"boolean\") {\n enumOriginalTypes[String(v)] = \"bool\";\n }\n }\n options.push({\n name: propName,\n flags: `${flagName} <value>`,\n description: helpText,\n defaultValue:\n defaultValue !== undefined ? String(defaultValue) : undefined,\n required: false,\n choices: stringValues,\n enumOriginalTypes:\n Object.keys(enumOriginalTypes).length > 0\n ? enumOriginalTypes\n : undefined,\n });\n }\n } else {\n // Standard option\n let parseArg: ((value: string) => unknown) | undefined;\n if (typeResult === \"int\") {\n parseArg = (v: string) => {\n const n = parseInt(v, 10);\n if (isNaN(n)) throw new Error(`Invalid integer: ${v}`);\n return n;\n };\n } else if (typeResult === \"float\") {\n parseArg = (v: string) => {\n const n = parseFloat(v);\n if (isNaN(n)) throw new Error(`Invalid number: ${v}`);\n return n;\n };\n }\n options.push({\n name: propName,\n flags: `${flagName} <value>`,\n description: helpText,\n defaultValue,\n required: false,\n parseArg,\n });\n }\n }\n\n return options;\n}\n","/**\n * Interactive approval prompts with timeout.\n *\n * Protocol spec: Approval workflow\n */\n\nimport * as readline from \"node:readline\";\nimport type { ModuleDescriptor } from \"./cli.js\";\nimport { ApprovalTimeoutError, EXIT_CODES } from \"./errors.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Get an annotation value from either a dict or an object.\n */\nfunction getAnnotation(\n annotations: unknown,\n key: string,\n defaultValue: unknown = undefined,\n): unknown {\n if (!annotations || typeof annotations !== \"object\") return defaultValue;\n const ann = annotations as Record<string, unknown>;\n return key in ann ? ann[key] : defaultValue;\n}\n\n// ---------------------------------------------------------------------------\n// checkApproval\n// ---------------------------------------------------------------------------\n\n/**\n * Check if module requires approval and handle accordingly.\n * Returns normally if approved (or approval not required).\n * Calls process.exit(46) if denied/timed out/non-TTY.\n */\nexport async function checkApproval(\n moduleDef: ModuleDescriptor,\n autoApprove: boolean,\n): Promise<void> {\n const annotations = moduleDef.annotations;\n\n // Check if approval is required\n let requiresApproval: boolean;\n if (moduleDef.requiresApproval !== undefined) {\n requiresApproval = moduleDef.requiresApproval;\n } else if (annotations) {\n requiresApproval = getAnnotation(annotations, \"requires_approval\", false) === true;\n } else {\n return; // No annotations, no approval needed\n }\n\n if (!requiresApproval) {\n return;\n }\n\n const moduleId = moduleDef.id;\n\n // Bypass: autoApprove flag (highest priority)\n if (autoApprove) {\n return;\n }\n\n // Bypass: APCORE_CLI_AUTO_APPROVE env var\n const envVal = process.env.APCORE_CLI_AUTO_APPROVE ?? \"\";\n if (envVal === \"1\") {\n return;\n }\n if (envVal !== \"\" && envVal !== \"1\") {\n process.stderr.write(\n `Warning: APCORE_CLI_AUTO_APPROVE is set to '${envVal}', expected '1'. Ignoring.\\n`,\n );\n }\n\n // Non-TTY check\n if (!process.stdin.isTTY) {\n process.stderr.write(\n `Error: Module '${moduleId}' requires approval but no interactive ` +\n \"terminal is available. Use --yes or set APCORE_CLI_AUTO_APPROVE=1 \" +\n \"to bypass.\\n\",\n );\n process.exit(EXIT_CODES.APPROVAL_DENIED);\n }\n\n // TTY prompt\n await promptWithTimeout(moduleDef, 60);\n}\n\n/**\n * Display approval prompt with timeout.\n */\nasync function promptWithTimeout(\n moduleDef: ModuleDescriptor,\n timeout: number,\n): Promise<void> {\n // Clamp timeout\n timeout = Math.max(1, Math.min(timeout, 3600));\n\n const moduleId = moduleDef.id;\n const annotations = moduleDef.annotations;\n const message =\n (annotations\n ? (getAnnotation(annotations, \"approval_message\") as string | undefined)\n : undefined) ??\n `Module '${moduleId}' requires approval to execute.`;\n\n process.stderr.write(message + \"\\n\");\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n try {\n const answer = await Promise.race([\n new Promise<string>((resolve) => {\n rl.question(\"Proceed? [y/N] \", (ans) => resolve(ans));\n }),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n reject(new ApprovalTimeoutError(\n `Approval prompt timed out after ${timeout} seconds.`,\n ));\n }, timeout * 1000);\n }),\n ]);\n\n // Clear the timeout — prompt resolved before timeout fired\n if (timer) clearTimeout(timer);\n\n const normalized = answer.trim().toLowerCase();\n if (normalized === \"y\" || normalized === \"yes\") {\n return;\n }\n\n process.stderr.write(\"Error: Approval denied.\\n\");\n process.exit(EXIT_CODES.APPROVAL_DENIED);\n } catch (err) {\n if (timer) clearTimeout(timer);\n if (err instanceof ApprovalTimeoutError) {\n process.stderr.write(\n `Error: Approval prompt timed out after ${timeout} seconds.\\n`,\n );\n process.exit(EXIT_CODES.APPROVAL_TIMEOUT);\n }\n throw err;\n } finally {\n rl.close();\n }\n}\n","/**\n * TTY-adaptive output formatting (table/json).\n *\n * Protocol spec: Output formatting\n */\n\nimport type { ModuleDescriptor } from \"./cli.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve output format with TTY-adaptive default.\n */\nexport function resolveFormat(explicitFormat?: string): string {\n if (explicitFormat !== undefined) {\n return explicitFormat;\n }\n return process.stdout.isTTY ? \"table\" : \"json\";\n}\n\n/**\n * Truncate text to maxLength, appending '...' if needed.\n */\nexport function truncate(text: string, maxLength = 80): string {\n if (text.length <= maxLength) {\n return text;\n }\n return text.slice(0, maxLength - 3) + \"...\";\n}\n\n/**\n * Render a simple plain-text table with column headers.\n */\nfunction formatTable(\n headers: string[],\n rows: string[][],\n): string {\n // Calculate column widths\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)),\n );\n\n const sep = colWidths.map((w) => \"-\".repeat(w)).join(\" \");\n const headerLine = headers\n .map((h, i) => h.padEnd(colWidths[i]))\n .join(\" \");\n const dataLines = rows.map((row) =>\n row.map((cell, i) => (cell ?? \"\").padEnd(colWidths[i])).join(\" \"),\n );\n\n return [headerLine, sep, ...dataLines].join(\"\\n\") + \"\\n\";\n}\n\n// ---------------------------------------------------------------------------\n// formatModuleList\n// ---------------------------------------------------------------------------\n\n/**\n * Format and print a list of modules.\n */\nexport function formatModuleList(\n modules: ModuleDescriptor[],\n format: string,\n filterTags?: string[],\n): void {\n if (format === \"table\") {\n if (modules.length === 0 && filterTags && filterTags.length > 0) {\n process.stdout.write(\n `No modules found matching tags: ${filterTags.join(\", \")}.\\n`,\n );\n return;\n }\n if (modules.length === 0) {\n process.stdout.write(\"No modules found.\\n\");\n return;\n }\n\n const headers = [\"ID\", \"Description\", \"Tags\"];\n const rows = modules.map((m) => [\n m.id,\n truncate(m.description, 80),\n (m.tags ?? []).join(\", \"),\n ]);\n process.stdout.write(formatTable(headers, rows));\n } else if (format === \"json\") {\n const result = modules.map((m) => ({\n id: m.id,\n description: m.description,\n tags: m.tags ?? [],\n }));\n process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// formatModuleDetail\n// ---------------------------------------------------------------------------\n\n/**\n * Convert annotations to a plain dict, filtering out falsy/default values.\n */\nfunction annotationsToDict(\n annotations: unknown,\n): Record<string, unknown> | null {\n if (!annotations) return null;\n if (typeof annotations !== \"object\" || Array.isArray(annotations)) return null;\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(annotations as Record<string, unknown>)) {\n if (v !== null && v !== undefined && v !== false && v !== 0 && !(Array.isArray(v) && v.length === 0)) {\n result[k] = v;\n }\n }\n return Object.keys(result).length > 0 ? result : null;\n}\n\n/**\n * Format and print full module metadata.\n */\nexport function formatModuleDetail(\n moduleDef: ModuleDescriptor,\n format: string,\n): void {\n if (format === \"table\") {\n process.stdout.write(`\\nModule: ${moduleDef.id}\\n`);\n process.stdout.write(`\\nDescription:\\n ${moduleDef.description}\\n`);\n\n if (moduleDef.inputSchema && Object.keys(moduleDef.inputSchema).length > 0) {\n process.stdout.write(\"\\nInput Schema:\\n\");\n process.stdout.write(JSON.stringify(moduleDef.inputSchema, null, 2) + \"\\n\");\n }\n\n if (moduleDef.outputSchema && Object.keys(moduleDef.outputSchema).length > 0) {\n process.stdout.write(\"\\nOutput Schema:\\n\");\n process.stdout.write(JSON.stringify(moduleDef.outputSchema, null, 2) + \"\\n\");\n }\n\n const annDict = annotationsToDict(\n moduleDef.annotations,\n );\n if (annDict) {\n process.stdout.write(\"\\nAnnotations:\\n\");\n for (const [k, v] of Object.entries(annDict)) {\n process.stdout.write(` ${k}: ${v}\\n`);\n }\n }\n\n // Extension metadata (x- prefixed)\n const metadata = moduleDef.metadata;\n if (metadata) {\n const xFields: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(metadata)) {\n if (k.startsWith(\"x-\") || k.startsWith(\"x_\")) {\n xFields[k] = v;\n }\n }\n if (Object.keys(xFields).length > 0) {\n process.stdout.write(\"\\nExtension Metadata:\\n\");\n for (const [k, v] of Object.entries(xFields)) {\n process.stdout.write(` ${k}: ${v}\\n`);\n }\n }\n }\n\n const tags = moduleDef.tags ?? [];\n if (tags.length > 0) {\n process.stdout.write(`\\nTags: ${tags.join(\", \")}\\n`);\n }\n } else if (format === \"json\") {\n const result: Record<string, unknown> = {\n id: moduleDef.id,\n description: moduleDef.description,\n };\n if (moduleDef.inputSchema) result.input_schema = moduleDef.inputSchema;\n if (moduleDef.outputSchema) result.output_schema = moduleDef.outputSchema;\n\n const annDict = annotationsToDict(\n moduleDef.annotations,\n );\n if (annDict) result.annotations = annDict;\n\n const tags = moduleDef.tags ?? [];\n if (tags.length > 0) result.tags = tags;\n\n // Extension metadata\n const metadata = moduleDef.metadata;\n if (metadata) {\n for (const [k, v] of Object.entries(metadata)) {\n if (k.startsWith(\"x-\") || k.startsWith(\"x_\")) {\n result[k] = v;\n }\n }\n }\n\n process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// formatExecResult\n// ---------------------------------------------------------------------------\n\n/**\n * Format and print module execution result.\n */\nexport function formatExecResult(\n result: unknown,\n format?: string,\n): void {\n if (result === null || result === undefined) {\n return;\n }\n const effective = resolveFormat(format);\n if (\n effective === \"table\" &&\n typeof result === \"object\" &&\n !Array.isArray(result)\n ) {\n // Key-value table\n const entries = Object.entries(result as Record<string, unknown>);\n const headers = [\"Key\", \"Value\"];\n const rows = entries.map(([k, v]) => [String(k), String(v)]);\n process.stdout.write(formatTable(headers, rows));\n } else if (typeof result === \"object\") {\n process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n } else if (typeof result === \"string\") {\n process.stdout.write(result + \"\\n\");\n } else {\n process.stdout.write(String(result) + \"\\n\");\n }\n}\n","/**\n * Simple structured logger respecting logging.level config.\n */\n\nconst LEVELS = { DEBUG: 0, INFO: 1, WARNING: 2, ERROR: 3 } as const;\ntype LogLevel = keyof typeof LEVELS;\n\nlet currentLevel: LogLevel = \"WARNING\";\n\nexport function setLogLevel(level: string): void {\n const upper = level.toUpperCase();\n if (upper in LEVELS) {\n currentLevel = upper as LogLevel;\n }\n}\n\nexport function getLogLevel(): LogLevel {\n return currentLevel;\n}\n\nfunction shouldLog(level: LogLevel): boolean {\n return LEVELS[level] >= LEVELS[currentLevel];\n}\n\nexport function debug(message: string): void {\n if (shouldLog(\"DEBUG\")) process.stderr.write(`DEBUG: ${message}\\n`);\n}\n\nexport function info(message: string): void {\n if (shouldLog(\"INFO\")) process.stderr.write(`INFO: ${message}\\n`);\n}\n\nexport function warn(message: string): void {\n if (shouldLog(\"WARNING\")) process.stderr.write(`WARNING: ${message}\\n`);\n}\n\nexport function error(message: string): void {\n if (shouldLog(\"ERROR\")) process.stderr.write(`ERROR: ${message}\\n`);\n}\n","/**\n * LazyModuleGroup — Dynamic command loading from Registry.\n *\n * Equivalent to the Python LazyModuleGroup. Dynamically discovers apcore\n * modules from the Registry and exposes them as Commander subcommands.\n *\n * Protocol spec: CLI command structure & lazy loading\n */\n\nimport { Command } from \"commander\";\nimport { buildModuleCommand } from \"./main.js\";\n\n// TODO: Import Registry and Executor from apcore-js once available\n// import type { Registry, Executor, ModuleDescriptor } from \"apcore-js\";\n\n// ---------------------------------------------------------------------------\n// Placeholder types until apcore-js types are available\n// ---------------------------------------------------------------------------\n\n/** Placeholder for apcore-js Registry. */\nexport interface Registry {\n listModules(): ModuleDescriptor[];\n getModule(moduleId: string): ModuleDescriptor | null;\n}\n\n/** Placeholder for apcore-js Executor. */\nexport interface Executor {\n execute(moduleId: string, input: Record<string, unknown>): Promise<unknown>;\n}\n\n/** Placeholder for apcore-js ModuleDescriptor. */\nexport interface ModuleDescriptor {\n id: string;\n name: string;\n description: string;\n tags?: string[];\n inputSchema?: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n requiresApproval?: boolean;\n annotations?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// LazyModuleGroup\n// ---------------------------------------------------------------------------\n\n/**\n * Dynamically loads apcore modules as Commander subcommands from Registry.\n *\n * TODO: Implement lazy loading — commands should only be fully built when\n * actually invoked, not at registration time.\n */\nexport class LazyModuleGroup {\n private readonly registry: Registry;\n readonly executor: Executor;\n private commandCache: Map<string, Command> = new Map();\n\n constructor(registry: Registry, executor: Executor) {\n this.registry = registry;\n this.executor = executor;\n }\n\n /**\n * List all available command names from the Registry.\n *\n * TODO: Implement registry enumeration.\n */\n listCommands(): string[] {\n // TODO: Query registry for all module IDs\n return this.registry.listModules().map((m) => m.id);\n }\n\n /**\n * Get or lazily build a Commander Command for the given module.\n *\n * TODO: Implement lazy command construction with schema-based options.\n */\n getCommand(cmdName: string): Command | null {\n if (this.commandCache.has(cmdName)) {\n return this.commandCache.get(cmdName)!;\n }\n\n const moduleDef = this.registry.getModule(cmdName);\n if (!moduleDef) {\n return null;\n }\n\n const cmd = buildModuleCommand(moduleDef, this.executor);\n this.commandCache.set(cmdName, cmd);\n return cmd;\n }\n}\n","/**\n * ConfigResolver — 4-tier config resolution (CLI flag > env > file > default).\n *\n * Protocol spec: Configuration resolution\n */\n\nimport * as fs from \"node:fs\";\nimport yaml from \"js-yaml\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Default configuration values. */\nexport const DEFAULTS: Record<string, unknown> = {\n \"extensions.root\": \"./extensions\",\n \"logging.level\": \"WARNING\",\n \"sandbox.enabled\": false,\n \"cli.stdin_buffer_limit\": 10_485_760,\n \"cli.auto_approve\": false,\n};\n\n// ---------------------------------------------------------------------------\n// ConfigResolver\n// ---------------------------------------------------------------------------\n\n/**\n * Resolves configuration from four tiers (highest to lowest priority):\n * 1. CLI flags\n * 2. Environment variables\n * 3. Config file (YAML/JSON)\n * 4. Built-in defaults\n */\nexport class ConfigResolver {\n private readonly cliFlags: Record<string, unknown>;\n private readonly configPath: string;\n private fileCache: Record<string, unknown> | null = null;\n private fileCacheLoaded = false;\n\n constructor(cliFlags?: Record<string, unknown>, configPath?: string) {\n this.cliFlags = cliFlags ?? {};\n this.configPath = configPath ?? \"apcore.yaml\";\n }\n\n /**\n * Resolve a single configuration key across all four tiers.\n */\n resolve(key: string, cliFlag?: string, envVar?: string): unknown {\n // Tier 1: CLI flag\n const flagKey = cliFlag ?? key;\n if (flagKey in this.cliFlags) {\n const value = this.cliFlags[flagKey];\n if (value !== null && value !== undefined) {\n return value;\n }\n }\n\n // Tier 2: Environment variable\n if (envVar) {\n const envValue = process.env[envVar];\n if (envValue !== undefined && envValue !== \"\") {\n return envValue;\n }\n }\n\n // Tier 3: Config file\n const fileValue = this.resolveFromFile(key);\n if (fileValue !== undefined) {\n return fileValue;\n }\n\n // Tier 4: Defaults\n return DEFAULTS[key];\n }\n\n /**\n * Load a value from the config file using a dot-separated key path.\n */\n private resolveFromFile(key: string): unknown {\n if (!this.fileCacheLoaded) {\n this.fileCache = this.loadConfigFile();\n this.fileCacheLoaded = true;\n }\n if (this.fileCache === null) {\n return undefined;\n }\n return this.fileCache[key];\n }\n\n /**\n * Load and flatten a YAML config file.\n */\n private loadConfigFile(): Record<string, unknown> | null {\n let content: string;\n try {\n content = fs.readFileSync(this.configPath, \"utf-8\");\n } catch (err: unknown) {\n if (err instanceof Error && \"code\" in err && err.code === \"ENOENT\") {\n return null;\n }\n console.warn(\n `Configuration file '${this.configPath}' is malformed, using defaults.`,\n );\n return null;\n }\n\n let parsed: unknown;\n try {\n parsed = yaml.load(content);\n } catch {\n console.warn(\n `Configuration file '${this.configPath}' is malformed, using defaults.`,\n );\n return null;\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n console.warn(\n `Configuration file '${this.configPath}' is malformed, using defaults.`,\n );\n return null;\n }\n\n return this.flattenDict(parsed as Record<string, unknown>);\n }\n\n /**\n * Flatten nested dict to dot-notation keys.\n */\n private flattenDict(\n d: Record<string, unknown>,\n prefix = \"\",\n ): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(d)) {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n if (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value)\n ) {\n Object.assign(\n result,\n this.flattenDict(value as Record<string, unknown>, fullKey),\n );\n } else {\n result[fullKey] = value;\n }\n }\n return result;\n }\n}\n","/**\n * Discovery commands — list and describe modules.\n *\n * Protocol spec: Module discovery & introspection\n */\n\nimport { Command } from \"commander\";\nimport type { ModuleDescriptor, Registry } from \"./cli.js\";\nimport { EXIT_CODES } from \"./errors.js\";\nimport { validateModuleId } from \"./main.js\";\nimport {\n formatModuleDetail,\n formatModuleList,\n resolveFormat,\n} from \"./output.js\";\n\nconst TAG_PATTERN = /^[a-z][a-z0-9_-]*$/;\n\nfunction validateTag(tag: string): void {\n if (!TAG_PATTERN.test(tag)) {\n process.stderr.write(\n `Error: Invalid tag format: '${tag}'. Tags must match [a-z][a-z0-9_-]*.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n}\n\n/**\n * Collect repeated --tag options into an array.\n */\nfunction collectTag(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n\n/**\n * Register list and describe commands on the CLI group.\n */\nexport function registerDiscoveryCommands(\n cli: Command,\n registry: Registry,\n): void {\n const listCmd = new Command(\"list\")\n .description(\"List available modules in the registry.\")\n .option(\"--tag <tag>\", \"Filter modules by tag (AND logic). Repeatable.\", collectTag, [])\n .option(\"--format <format>\", \"Output format.\", undefined)\n .action((opts: { tag: string[]; format?: string }) => {\n // Validate tags\n for (const t of opts.tag) {\n validateTag(t);\n }\n\n const modules: ModuleDescriptor[] = [];\n for (const m of registry.listModules()) {\n modules.push(m);\n }\n\n let filtered = modules;\n if (opts.tag.length > 0) {\n const filterTags = new Set(opts.tag);\n filtered = modules.filter((m) => {\n const mTags = m.tags ?? [];\n return [...filterTags].every((t) => mTags.includes(t));\n });\n }\n\n const fmt = resolveFormat(opts.format);\n formatModuleList(filtered, fmt, opts.tag.length > 0 ? opts.tag : undefined);\n });\n cli.addCommand(listCmd);\n\n const describeCmd = new Command(\"describe\")\n .description(\"Show metadata, schema, and annotations for a module.\")\n .argument(\"<module-id>\", \"Module ID to describe\")\n .option(\"--format <format>\", \"Output format.\", undefined)\n .action((moduleId: string, opts: { format?: string }) => {\n validateModuleId(moduleId);\n\n const moduleDef = registry.getModule(moduleId);\n if (!moduleDef) {\n process.stderr.write(\n `Error: Module '${moduleId}' not found.\\n`,\n );\n process.exit(EXIT_CODES.MODULE_NOT_FOUND);\n }\n\n const fmt = resolveFormat(opts.format);\n formatModuleDetail(moduleDef, fmt);\n });\n cli.addCommand(describeCmd);\n}\n","/**\n * Shell completion + man page generation.\n *\n * Protocol spec: Shell integration\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport * as path from \"node:path\";\nimport { Command } from \"commander\";\nimport { EXIT_CODES } from \"./errors.js\";\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(path.resolve(__dirname, \"../package.json\"), \"utf-8\"));\nconst SHELL_VERSION: string = pkg.version;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a prog_name like 'my-tool' to a valid shell identifier '_my_tool'.\n */\nfunction makeFunctionName(progName: string): string {\n return \"_\" + progName.replace(/[^a-zA-Z0-9]/g, \"_\");\n}\n\n/**\n * Shell-safe quoting.\n */\nfunction shellQuote(s: string): string {\n return \"'\" + s.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n\n// ---------------------------------------------------------------------------\n// Completion generators\n// ---------------------------------------------------------------------------\n\nfunction generateBashCompletion(progName: string): string {\n const fn = makeFunctionName(progName);\n const quoted = shellQuote(progName);\n const moduleListCmd =\n `${quoted} list --format json 2>/dev/null` +\n ` | node -e \"process.stdin.on('data',d=>{JSON.parse(d).forEach(m=>console.log(m.id))})\" 2>/dev/null`;\n\n return (\n `${fn}() {\\n` +\n ` local cur prev opts\\n` +\n ` COMPREPLY=()\\n` +\n ` cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\\n` +\n ` prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"\\n` +\n `\\n` +\n ` if [[ \\${COMP_CWORD} -eq 1 ]]; then\\n` +\n ` opts=\"list describe completion man\"\\n` +\n ` COMPREPLY=( $(compgen -W \"\\${opts}\" -- \\${cur}) )\\n` +\n ` return 0\\n` +\n ` fi\\n` +\n `\\n` +\n ` if [[ \"\\${COMP_WORDS[1]}\" == \"exec\" && \\${COMP_CWORD} -eq 2 ]]; then\\n` +\n ` local modules=$(${moduleListCmd})\\n` +\n ` COMPREPLY=( $(compgen -W \"\\${modules}\" -- \\${cur}) )\\n` +\n ` return 0\\n` +\n ` fi\\n` +\n `}\\n` +\n `complete -F ${fn} ${quoted}\\n`\n );\n}\n\nfunction generateZshCompletion(progName: string): string {\n const fn = makeFunctionName(progName);\n const quoted = shellQuote(progName);\n const moduleListCmd =\n `${quoted} list --format json 2>/dev/null` +\n ` | node -e \"process.stdin.on('data',d=>{JSON.parse(d).forEach(m=>console.log(m.id))})\" 2>/dev/null`;\n\n return (\n `#compdef ${progName}\\n` +\n `\\n` +\n `${fn}() {\\n` +\n ` local -a commands\\n` +\n ` commands=(\\n` +\n ` 'list:List available modules'\\n` +\n ` 'describe:Show module metadata and schema'\\n` +\n ` 'completion:Generate shell completion script'\\n` +\n ` 'man:Generate man page'\\n` +\n ` )\\n` +\n `\\n` +\n ` _arguments -C \\\\\\n` +\n ` '1:command:->command' \\\\\\n` +\n ` '*::arg:->args'\\n` +\n `\\n` +\n ` case \"$state\" in\\n` +\n ` command)\\n` +\n ` _describe -t commands '${progName} commands' commands\\n` +\n ` ;;\\n` +\n ` args)\\n` +\n ` case \"\\${words[1]}\" in\\n` +\n ` exec)\\n` +\n ` local modules\\n` +\n ` modules=($(${moduleListCmd}))\\n` +\n ` compadd -a modules\\n` +\n ` ;;\\n` +\n ` esac\\n` +\n ` ;;\\n` +\n ` esac\\n` +\n `}\\n` +\n `\\n` +\n `compdef ${fn} ${quoted}\\n`\n );\n}\n\nfunction generateFishCompletion(progName: string): string {\n const quoted = shellQuote(progName);\n const moduleListCmd =\n `${quoted} list --format json 2>/dev/null` +\n ` | node -e \\\\\"process.stdin.on('data',d=>{JSON.parse(d).forEach(m=>console.log(m.id))})\\\\\" 2>/dev/null`;\n\n return (\n `# Fish completions for ${progName}\\n` +\n `complete -c ${quoted} -n \"__fish_use_subcommand\"` +\n ` -a list -d \"List available modules\"\\n` +\n `complete -c ${quoted} -n \"__fish_use_subcommand\"` +\n ` -a describe -d \"Show module metadata and schema\"\\n` +\n `complete -c ${quoted} -n \"__fish_use_subcommand\"` +\n ` -a completion -d \"Generate shell completion script\"\\n` +\n `complete -c ${quoted} -n \"__fish_use_subcommand\"` +\n ` -a man -d \"Generate man page\"\\n` +\n `\\n` +\n `complete -c ${quoted} -n \"__fish_seen_subcommand_from exec\"` +\n ` -a \"(${moduleListCmd})\"\\n`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Man page generation\n// ---------------------------------------------------------------------------\n\nfunction buildSynopsis(\n command: Command | null,\n progName: string,\n commandName: string,\n): string {\n if (!command) {\n return `\\\\fB${progName} ${commandName}\\\\fR [OPTIONS]`;\n }\n\n const parts = [`\\\\fB${progName} ${commandName}\\\\fR`];\n for (const opt of command.options) {\n const flag = opt.long ?? opt.short ?? \"\";\n if (opt.isBoolean?.()) {\n parts.push(`[${flag}]`);\n } else if (opt.required) {\n const typeName = (opt.argChoices ? \"CHOICE\" : \"VALUE\").toUpperCase();\n parts.push(`${flag} \\\\fI${typeName}\\\\fR`);\n } else {\n const typeName = (opt.argChoices ? \"CHOICE\" : \"VALUE\").toUpperCase();\n parts.push(`[${flag} \\\\fI${typeName}\\\\fR]`);\n }\n }\n\n for (const arg of command.registeredArguments ?? []) {\n const meta = arg.name().toUpperCase();\n if (arg.required) {\n parts.push(`\\\\fI${meta}\\\\fR`);\n } else {\n parts.push(`[\\\\fI${meta}\\\\fR]`);\n }\n }\n\n return parts.join(\" \");\n}\n\nfunction generateManPage(\n commandName: string,\n command: Command | null,\n progName: string,\n version = SHELL_VERSION,\n): string {\n const today = new Date().toISOString().slice(0, 10);\n const title = `${progName}-${commandName}`.toUpperCase();\n const pkgLabel = `${progName} ${version}`;\n const manualLabel = `${progName} Manual`;\n\n const sections: string[] = [];\n sections.push(`.TH \"${title}\" \"1\" \"${today}\" \"${pkgLabel}\" \"${manualLabel}\"`);\n\n sections.push(\".SH NAME\");\n const desc = command?.description() ?? commandName;\n const nameDesc = desc.split(\"\\n\")[0].replace(/\\.$/, \"\");\n sections.push(`${progName}-${commandName} \\\\- ${nameDesc}`);\n\n sections.push(\".SH SYNOPSIS\");\n sections.push(buildSynopsis(command, progName, commandName));\n\n if (command?.description()) {\n sections.push(\".SH DESCRIPTION\");\n sections.push(\n command.description().replace(/\\\\/g, \"\\\\\\\\\").replace(/-/g, \"\\\\-\"),\n );\n }\n\n if (command && command.options.length > 0) {\n sections.push(\".SH OPTIONS\");\n for (const opt of command.options) {\n const flag = [opt.short, opt.long].filter(Boolean).join(\", \");\n sections.push(\".TP\");\n if (opt.isBoolean?.()) {\n sections.push(`\\\\fB${flag}\\\\fR`);\n } else {\n sections.push(`\\\\fB${flag}\\\\fR \\\\fIVALUE\\\\fR`);\n }\n if (opt.description) {\n sections.push(opt.description);\n }\n if (opt.defaultValue !== undefined && !opt.isBoolean?.()) {\n sections.push(`Default: ${opt.defaultValue}.`);\n }\n }\n }\n\n sections.push(\".SH ENVIRONMENT\");\n sections.push(\".TP\");\n sections.push(\"\\\\fBAPCORE_EXTENSIONS_ROOT\\\\fR\");\n sections.push(\n \"Path to the apcore extensions directory. Overrides the default \\\\fI./extensions\\\\fR.\",\n );\n sections.push(\".TP\");\n sections.push(\"\\\\fBAPCORE_CLI_AUTO_APPROVE\\\\fR\");\n sections.push(\n \"Set to \\\\fB1\\\\fR to bypass approval prompts for modules that require human-in-the-loop confirmation.\",\n );\n sections.push(\".TP\");\n sections.push(\"\\\\fBAPCORE_CLI_LOGGING_LEVEL\\\\fR\");\n sections.push(\n \"CLI-specific logging verbosity. One of: DEBUG, INFO, WARNING, ERROR. \" +\n \"Takes priority over \\\\fBAPCORE_LOGGING_LEVEL\\\\fR. Default: WARNING.\",\n );\n sections.push(\".TP\");\n sections.push(\"\\\\fBAPCORE_LOGGING_LEVEL\\\\fR\");\n sections.push(\n \"Global apcore logging verbosity. One of: DEBUG, INFO, WARNING, ERROR. \" +\n \"Used as fallback when \\\\fBAPCORE_CLI_LOGGING_LEVEL\\\\fR is not set. Default: WARNING.\",\n );\n\n sections.push(\".SH EXIT CODES\");\n const exitCodes: [string, string][] = [\n [\"0\", \"Success.\"],\n [\"1\", \"Module execution error.\"],\n [\"2\", \"Invalid CLI input or missing argument.\"],\n [\"44\", \"Module not found, disabled, or failed to load.\"],\n [\"45\", \"Input failed JSON Schema validation.\"],\n [\n \"46\",\n \"Approval denied, timed out, or no interactive terminal available.\",\n ],\n [\n \"47\",\n \"Configuration error (extensions directory not found or unreadable).\",\n ],\n [\"48\", \"Schema contains a circular \\\\fB$ref\\\\fR.\"],\n [\"77\", \"ACL denied — insufficient permissions for this module.\"],\n [\"130\", \"Execution cancelled by user (SIGINT / Ctrl\\\\-C).\"],\n ];\n for (const [code, meaning] of exitCodes) {\n sections.push(`.TP\\n\\\\fB${code}\\\\fR\\n${meaning}`);\n }\n\n sections.push(\".SH SEE ALSO\");\n sections.push(\n [\n `\\\\fB${progName}\\\\fR(1)`,\n `\\\\fB${progName}\\\\-list\\\\fR(1)`,\n `\\\\fB${progName}\\\\-describe\\\\fR(1)`,\n `\\\\fB${progName}\\\\-completion\\\\fR(1)`,\n ].join(\", \"),\n );\n\n return sections.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// registerShellCommands\n// ---------------------------------------------------------------------------\n\n/**\n * Register completion and man commands.\n */\nexport function registerShellCommands(\n cli: Command,\n progName = \"apcore-cli\",\n): void {\n const completionCmd = new Command(\"completion\")\n .description(\n \"Generate a shell completion script and print it to stdout.\",\n )\n .argument(\"<shell>\", \"Shell type: bash, zsh, or fish\")\n .action((shell: string) => {\n const validShells = [\"bash\", \"zsh\", \"fish\"];\n if (!validShells.includes(shell)) {\n process.stderr.write(\n `Error: Unknown shell '${shell}'. Expected: bash, zsh, or fish.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n const resolved = cli.name() || progName;\n const generators: Record<string, () => string> = {\n bash: () => generateBashCompletion(resolved),\n zsh: () => generateZshCompletion(resolved),\n fish: () => generateFishCompletion(resolved),\n };\n process.stdout.write(generators[shell]());\n });\n cli.addCommand(completionCmd);\n\n const manCmd = new Command(\"man\")\n .description(\"Generate a roff man page for COMMAND and print it to stdout.\")\n .argument(\"<command>\", \"Command to generate man page for\")\n .action((commandName: string) => {\n const knownBuiltins = new Set([\"list\", \"describe\", \"completion\", \"man\"]);\n const cmd = cli.commands.find((c) => c.name() === commandName) ?? null;\n\n if (!cmd && !knownBuiltins.has(commandName)) {\n process.stderr.write(\n `Error: Unknown command '${commandName}'.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n const resolved = cli.name() || progName;\n const roff = generateManPage(commandName, cmd, resolved);\n process.stdout.write(roff);\n });\n cli.addCommand(manCmd);\n}\n"],"mappings":";;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;;ACkGO,SAAS,iBAAiBA,QAA0B;AACzD,MAAIA,kBAAiB,sBAAsB;AACzC,WAAO,WAAW;AAAA,EACpB;AACA,MAAIA,kBAAiB,qBAAqB;AACxC,WAAO,WAAW;AAAA,EACpB;AACA,MAAIA,kBAAiB,qBAAqB;AACxC,WAAO,WAAW;AAAA,EACpB;AACA,MAAIA,kBAAiB,uBAAuB;AAC1C,WAAO,WAAW;AAAA,EACpB;AACA,MAAIA,kBAAiB,uBAAuB;AAC1C,WAAO,WAAW;AAAA,EACpB;AACA,MAAIA,kBAAiB,qBAAqB;AACxC,WAAO,WAAW;AAAA,EACpB;AACA,MAAIA,kBAAiB,sBAAsB;AACzC,WAAO,WAAW;AAAA,EACpB;AAGA,MAAIA,kBAAiB,OAAO;AAC1B,UAAM,OAAQA,OAA6C;AAC3D,UAAM,UAAoC;AAAA,MACxC,kBAAkB,WAAW;AAAA,MAC7B,mBAAmB,WAAW;AAAA,MAC9B,iBAAiB,WAAW;AAAA,MAC5B,yBAAyB,WAAW;AAAA,MACpC,qBAAqB,WAAW;AAAA,MAChC,iBAAiB,WAAW;AAAA,MAC5B,kBAAkB,WA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/B,UAAM,gBAAgB,oBAAI,IAAI,CAAC,QAAQ,YAAY,cAAc,KAAK,CAAC;AACvE,UAAM,MAAM,IAAI,SAAS,KAAK,CAAC,MAAM,EAAE,KAAK,MAAM,WAAW,KAAK;AAElE,QAAI,CAAC,OAAO,CAAC,cAAc,IAAI,WAAW,GAAG;AAC3C,cAAQ,OAAO;AAAA,QACb,2BAA2B,WAAW;AAAA;AAAA,MACxC;AACA,cAAQ,KAAK,WAAW,iBAAiB;AAAA,IAC3C;AAEA,UAAM,WAAW,IAAI,KAAK,KAAK;AAC/B,UAAM,OAAO,gBAAgB,aAAa,KAAK,QAAQ;AACvD,YAAQ,OAAO,MAAM,IAAI;AAAA,EAC3B,CAAC;AACH,MAAI,WAAW,MAAM;AACvB;;;AV5SA;AAiBA;","names":["error","path","crypto","os","hostname","fs","os","path","fileURLToPath","path","resolve","__dirname","fileURLToPath","error","Sandbox","getAuditLogger","resolve","fs","Command","Command","readFileSync","fileURLToPath","path","Command","__dirname","pkg"]}
1
+ {"version":3,"sources":["../../node_modules/tsup/assets/esm_shims.js","../../src/errors.ts","../../src/security/audit.ts","../../src/security/config-encryptor.ts","../../src/security/auth.ts","../../src/security/sandbox.ts","../../src/security/index.ts","../../src/index.ts","../../src/main.ts","../../src/ref-resolver.ts","../../src/schema-parser.ts","../../src/approval.ts","../../src/output.ts","../../src/logger.ts","../../src/cli.ts","../../src/config.ts","../../src/discovery.ts","../../src/shell.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Error classes and exit code mapping for apcore-cli.\n *\n * Protocol spec: Error handling & exit codes\n */\n\n// ---------------------------------------------------------------------------\n// Error classes\n// ---------------------------------------------------------------------------\n\n/** Thrown when the user does not approve module execution within the timeout. */\nexport class ApprovalTimeoutError extends Error {\n constructor(message = \"Approval timed out\") {\n super(message);\n this.name = \"ApprovalTimeoutError\";\n }\n}\n\n/** Thrown when API key authentication fails or is missing. */\nexport class AuthenticationError extends Error {\n constructor(message = \"Authentication failed\") {\n super(message);\n this.name = \"AuthenticationError\";\n }\n}\n\n/** Thrown when encrypted config cannot be decrypted. */\nexport class ConfigDecryptionError extends Error {\n constructor(message = \"Config decryption failed\") {\n super(message);\n this.name = \"ConfigDecryptionError\";\n }\n}\n\n/** Thrown when module execution fails. */\nexport class ModuleExecutionError extends Error {\n constructor(message = \"Module execution failed\") {\n super(message);\n this.name = \"ModuleExecutionError\";\n }\n}\n\n/** Thrown when approval is denied by the user. */\nexport class ApprovalDeniedError extends Error {\n constructor(message = \"Approval denied\") {\n super(message);\n this.name = \"ApprovalDeniedError\";\n }\n}\n\n/** Thrown when schema validation fails. */\nexport class SchemaValidationError extends Error {\n constructor(message = \"Schema validation failed\") {\n super(message);\n this.name = \"SchemaValidationError\";\n }\n}\n\n/** Thrown when a module is not found. */\nexport class ModuleNotFoundError extends Error {\n constructor(message = \"Module not found\") {\n super(message);\n this.name = \"ModuleNotFoundError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Exit code map\n// ---------------------------------------------------------------------------\n\nexport const EXIT_CODES = {\n SUCCESS: 0,\n MODULE_EXECUTE_ERROR: 1,\n MODULE_TIMEOUT: 1,\n INVALID_CLI_INPUT: 2,\n MODULE_NOT_FOUND: 44,\n MODULE_LOAD_ERROR: 44,\n MODULE_DISABLED: 44,\n SCHEMA_VALIDATION_ERROR: 45,\n APPROVAL_DENIED: 46,\n APPROVAL_TIMEOUT: 46,\n CONFIG_NOT_FOUND: 47,\n CONFIG_INVALID: 47,\n SCHEMA_CIRCULAR_REF: 48,\n ACL_DENIED: 77,\n KEYBOARD_INTERRUPT: 130,\n} as const;\n\nexport type ExitCode = (typeof EXIT_CODES)[keyof typeof EXIT_CODES];\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Map a caught error to the appropriate process exit code.\n * Also checks for apcore error codes on the error object.\n */\nexport function exitCodeForError(error: unknown): ExitCode {\n if (error instanceof ApprovalTimeoutError) {\n return EXIT_CODES.APPROVAL_TIMEOUT;\n }\n if (error instanceof ApprovalDeniedError) {\n return EXIT_CODES.APPROVAL_DENIED;\n }\n if (error instanceof AuthenticationError) {\n return EXIT_CODES.ACL_DENIED;\n }\n if (error instanceof ConfigDecryptionError) {\n return EXIT_CODES.CONFIG_INVALID;\n }\n if (error instanceof SchemaValidationError) {\n return EXIT_CODES.SCHEMA_VALIDATION_ERROR;\n }\n if (error instanceof ModuleNotFoundError) {\n return EXIT_CODES.MODULE_NOT_FOUND;\n }\n if (error instanceof ModuleExecutionError) {\n return EXIT_CODES.MODULE_EXECUTE_ERROR;\n }\n\n // Check for apcore error codes on the error object\n if (error instanceof Error) {\n const code = (error as unknown as Record<string, unknown>).code as string | undefined;\n const codeMap: Record<string, ExitCode> = {\n MODULE_NOT_FOUND: EXIT_CODES.MODULE_NOT_FOUND,\n MODULE_LOAD_ERROR: EXIT_CODES.MODULE_LOAD_ERROR,\n MODULE_DISABLED: EXIT_CODES.MODULE_DISABLED,\n SCHEMA_VALIDATION_ERROR: EXIT_CODES.SCHEMA_VALIDATION_ERROR,\n SCHEMA_CIRCULAR_REF: EXIT_CODES.SCHEMA_CIRCULAR_REF,\n APPROVAL_DENIED: EXIT_CODES.APPROVAL_DENIED,\n APPROVAL_TIMEOUT: EXIT_CODES.APPROVAL_TIMEOUT,\n CONFIG_NOT_FOUND: EXIT_CODES.CONFIG_NOT_FOUND,\n CONFIG_INVALID: EXIT_CODES.CONFIG_INVALID,\n MODULE_EXECUTE_ERROR: EXIT_CODES.MODULE_EXECUTE_ERROR,\n MODULE_TIMEOUT: EXIT_CODES.MODULE_TIMEOUT,\n ACL_DENIED: EXIT_CODES.ACL_DENIED,\n };\n if (code && code in codeMap) {\n return codeMap[code];\n }\n }\n\n return EXIT_CODES.MODULE_EXECUTE_ERROR;\n}\n","/**\n * AuditLogger — JSONL audit trail.\n *\n * Protocol spec: Security — audit logging\n */\n\nimport * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ntype ExecutionStatus = \"success\" | \"error\";\n\ninterface AuditEntry {\n timestamp: string;\n user: string;\n module_id: string;\n input_hash: string;\n status: ExecutionStatus;\n exit_code: number;\n duration_ms: number;\n}\n\n// ---------------------------------------------------------------------------\n// AuditLogger\n// ---------------------------------------------------------------------------\n\n/**\n * Appends structured JSONL entries to an audit log file for every module\n * execution, supporting compliance and debugging.\n */\nlet _auditLogger: AuditLogger | null = null;\n\n/**\n * Set the module-level audit logger instance.\n */\nexport function setAuditLogger(auditLogger: AuditLogger | null): void {\n _auditLogger = auditLogger;\n}\n\n/**\n * Get the current module-level audit logger instance.\n */\nexport function getAuditLogger(): AuditLogger | null {\n return _auditLogger;\n}\n\nexport class AuditLogger {\n static readonly DEFAULT_PATH = path.join(\n os.homedir(),\n \".apcore-cli\",\n \"audit.jsonl\",\n );\n\n private readonly logPath: string;\n\n constructor(path?: string) {\n this.logPath = path ?? AuditLogger.DEFAULT_PATH;\n this.ensureDirectory();\n }\n\n private ensureDirectory(): void {\n try {\n fs.mkdirSync(path.dirname(this.logPath), { recursive: true });\n } catch {\n // Silently ignore — we'll handle write errors in logExecution\n }\n }\n\n logExecution(\n moduleId: string,\n inputData: Record<string, unknown>,\n status: ExecutionStatus,\n exitCode: number,\n durationMs: number,\n ): void {\n const entry: AuditEntry = {\n timestamp: new Date().toISOString(),\n user: this.getUser(),\n module_id: moduleId,\n input_hash: this.hashInput(inputData),\n status,\n exit_code: exitCode,\n duration_ms: durationMs,\n };\n try {\n fs.appendFileSync(this.logPath, JSON.stringify(entry) + \"\\n\");\n } catch (err) {\n console.warn(`Could not write audit log: ${err}`);\n }\n }\n\n private hashInput(inputData: Record<string, unknown>): string {\n const salt = crypto.randomBytes(16);\n const sortedKeys = Object.keys(inputData).sort();\n const payload = JSON.stringify(inputData, sortedKeys);\n return crypto\n .createHash(\"sha256\")\n .update(Buffer.concat([salt, Buffer.from(payload, \"utf-8\")]))\n .digest(\"hex\");\n }\n\n private getUser(): string {\n try {\n return os.userInfo().username;\n } catch {\n return process.env.USER ?? process.env.USERNAME ?? \"unknown\";\n }\n }\n}\n","/**\n * ConfigEncryptor — Keyring + AES-256-GCM fallback.\n *\n * Protocol spec: Security — config encryption\n */\n\nimport * as crypto from \"node:crypto\";\nimport * as os from \"node:os\";\nimport { ConfigDecryptionError } from \"../errors.js\";\n\n// ---------------------------------------------------------------------------\n// Keytar dynamic import helper\n// ---------------------------------------------------------------------------\n\nlet keytarModule: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any\nasync function getKeytar(): Promise<any> { // eslint-disable-line @typescript-eslint/no-explicit-any\n if (keytarModule) return keytarModule;\n try {\n // @ts-expect-error — keytar is an optional peer dependency\n keytarModule = await import(\"keytar\");\n return keytarModule;\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// ConfigEncryptor\n// ---------------------------------------------------------------------------\n\n/**\n * Encrypts and decrypts configuration values. Prefers OS keyring for key\n * storage, falling back to AES-256-GCM with a derived key.\n */\nexport class ConfigEncryptor {\n static readonly SERVICE_NAME = \"apcore-cli\";\n\n /**\n * Encrypt and store a configuration value.\n */\n async store(key: string, value: string): Promise<string> {\n const keytar = await getKeytar();\n if (keytar) {\n try {\n await keytar.setPassword(ConfigEncryptor.SERVICE_NAME, key, value);\n return `keyring:${key}`;\n } catch {\n // Fall through to file-based encryption\n }\n }\n console.warn(\"OS keyring unavailable. Using file-based encryption.\");\n const ciphertext = this.aesEncrypt(value);\n return `enc:${Buffer.from(ciphertext).toString(\"base64\")}`;\n }\n\n /**\n * Retrieve and decrypt a configuration value.\n */\n async retrieve(configValue: string, key: string): Promise<string> {\n if (configValue.startsWith(\"keyring:\")) {\n const keytar = await getKeytar();\n if (!keytar) {\n throw new ConfigDecryptionError(\n `Keyring module not available to retrieve '${key}'.`,\n );\n }\n try {\n const refKey = configValue.slice(\"keyring:\".length);\n const result = await keytar.getPassword(\n ConfigEncryptor.SERVICE_NAME,\n refKey,\n );\n if (result === null || result === undefined) {\n throw new ConfigDecryptionError(\n `Keyring entry not found for '${refKey}'.`,\n );\n }\n return result;\n } catch (err) {\n if (err instanceof ConfigDecryptionError) throw err;\n throw new ConfigDecryptionError(\n `Failed to retrieve from keyring: ${err}`,\n );\n }\n }\n\n if (configValue.startsWith(\"enc:\")) {\n const ciphertext = Buffer.from(\n configValue.slice(\"enc:\".length),\n \"base64\",\n );\n try {\n return this.aesDecrypt(ciphertext);\n } catch {\n throw new ConfigDecryptionError(\n `Failed to decrypt configuration value '${key}'. Re-configure with 'apcore-cli config set ${key}'.`,\n );\n }\n }\n\n // Unrecognized prefix — return as-is\n return configValue;\n }\n\n // NOTE: Best-effort fallback when OS keyring is unavailable.\n // The key is derived from hostname + username (non-secret inputs).\n // For production security, ensure the OS keyring is accessible.\n private deriveKey(): Buffer {\n const hostname = os.hostname();\n const username =\n process.env.USER ?? process.env.USERNAME ?? \"unknown\";\n const salt = Buffer.from(\"apcore-cli-config-v1\");\n const material = `${hostname}:${username}`;\n return crypto.pbkdf2Sync(material, salt, 100_000, 32, \"sha256\");\n }\n\n private aesEncrypt(plaintext: string): Buffer {\n const key = this.deriveKey();\n const nonce = crypto.randomBytes(12);\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce);\n const ct = Buffer.concat([\n cipher.update(plaintext, \"utf-8\"),\n cipher.final(),\n ]);\n const tag = cipher.getAuthTag();\n // Wire format: nonce(12) + tag(16) + ciphertext\n return Buffer.concat([nonce, tag, ct]);\n }\n\n private aesDecrypt(data: Buffer): string {\n const key = this.deriveKey();\n const nonce = data.subarray(0, 12);\n const tag = data.subarray(12, 28);\n const ct = data.subarray(28);\n const decipher = crypto.createDecipheriv(\"aes-256-gcm\", key, nonce);\n decipher.setAuthTag(tag);\n const plaintext = Buffer.concat([decipher.update(ct), decipher.final()]);\n return plaintext.toString(\"utf-8\");\n }\n}\n","/**\n * AuthProvider — API key auth with keyring/encrypted storage.\n *\n * Protocol spec: Security — authentication\n */\n\nimport type { ConfigResolver } from \"../config.js\";\nimport { AuthenticationError } from \"../errors.js\";\nimport { ConfigEncryptor } from \"./config-encryptor.js\";\n\n// ---------------------------------------------------------------------------\n// AuthProvider\n// ---------------------------------------------------------------------------\n\n/**\n * Manages API key retrieval and request authentication.\n */\nexport class AuthProvider {\n private readonly config: ConfigResolver;\n private readonly encryptor: ConfigEncryptor;\n\n constructor(config: ConfigResolver, encryptor?: ConfigEncryptor) {\n this.config = config;\n this.encryptor = encryptor ?? new ConfigEncryptor();\n }\n\n /**\n * Retrieve the API key from the configured sources.\n * Handles keyring: and enc: prefixes via ConfigEncryptor.\n */\n async getApiKey(): Promise<string | null> {\n const result = this.config.resolve(\n \"auth.api_key\",\n \"--api-key\",\n \"APCORE_AUTH_API_KEY\",\n );\n if (result === null || result === undefined) {\n return null;\n }\n const strResult = String(result);\n if (strResult.startsWith(\"keyring:\") || strResult.startsWith(\"enc:\")) {\n return this.encryptor.retrieve(strResult, \"auth.api_key\");\n }\n return strResult;\n }\n\n /**\n * Add authentication headers to an outgoing request.\n */\n async authenticateRequest(\n headers: Record<string, string>,\n ): Promise<Record<string, string>> {\n const key = await this.getApiKey();\n if (!key) {\n throw new AuthenticationError(\n \"Remote registry requires authentication. \" +\n \"Set --api-key, APCORE_AUTH_API_KEY, or auth.api_key in config.\",\n );\n }\n return { ...headers, Authorization: `Bearer ${key}` };\n }\n\n /**\n * Handle an HTTP response status code for auth-related errors.\n */\n handleResponse(statusCode: number): void {\n if (statusCode === 401 || statusCode === 403) {\n throw new AuthenticationError(\n \"Authentication failed. Verify your API key.\",\n );\n }\n }\n}\n","/**\n * Sandbox — Subprocess isolation for module execution.\n *\n * Protocol spec: Security — sandboxed execution\n */\n\nimport * as child_process from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport type { Executor } from \"../cli.js\";\nimport { ModuleExecutionError } from \"../errors.js\";\n\n// ---------------------------------------------------------------------------\n// Sandbox\n// ---------------------------------------------------------------------------\n\n/**\n * Executes modules in an isolated subprocess to limit the blast radius\n * of untrusted or third-party modules.\n *\n * When disabled, delegates directly to the Executor.\n */\nexport class Sandbox {\n private readonly enabled: boolean;\n\n constructor(enabled = false) {\n this.enabled = enabled;\n }\n\n /**\n * Execute a module, optionally inside a sandboxed subprocess.\n */\n async execute(\n moduleId: string,\n inputData: Record<string, unknown>,\n executor: Executor,\n ): Promise<unknown> {\n if (!this.enabled) {\n return executor.execute(moduleId, inputData);\n }\n return this.sandboxedExecute(moduleId, inputData);\n }\n\n private sandboxedExecute(\n moduleId: string,\n inputData: Record<string, unknown>,\n ): unknown {\n // Build restricted environment\n const env: Record<string, string> = {};\n for (const key of [\"PATH\", \"NODE_PATH\", \"LANG\", \"LC_ALL\"]) {\n if (process.env[key]) {\n env[key] = process.env[key]!;\n }\n }\n for (const [key, value] of Object.entries(process.env)) {\n if (key.startsWith(\"APCORE_\") && value) {\n env[key] = value;\n }\n }\n\n const tmpDir = fs.mkdtempSync(\n path.join(os.tmpdir(), \"apcore_sandbox_\"),\n );\n\n try {\n env.HOME = tmpDir;\n env.TMPDIR = tmpDir;\n\n const script = [\n \"let d='';\",\n \"process.stdin.setEncoding('utf-8');\",\n \"process.stdin.on('data',c=>d+=c);\",\n \"process.stdin.on('end',()=>{\",\n \" const input=JSON.parse(d);\",\n ` process.stdout.write(JSON.stringify({error:\"Sandbox runner not yet implemented for module: ${moduleId}\"}));`,\n \"});\",\n ].join(\"\");\n\n const result = child_process.execFileSync(\n process.execPath,\n [\"-e\", script],\n {\n input: JSON.stringify(inputData),\n env,\n cwd: tmpDir,\n timeout: 300_000,\n maxBuffer: 10 * 1024 * 1024,\n },\n );\n\n return JSON.parse(result.toString(\"utf-8\"));\n } catch (err: unknown) {\n if (\n err instanceof Error &&\n \"killed\" in err &&\n (err as Record<string, unknown>).killed\n ) {\n throw new ModuleExecutionError(\n `Error: Module '${moduleId}' timed out in sandbox.`,\n );\n }\n const stderr =\n err instanceof Error && \"stderr\" in err\n ? String((err as Record<string, unknown>).stderr)\n : String(err);\n throw new ModuleExecutionError(\n `Error: Module '${moduleId}' execution failed: ${stderr}`,\n );\n } finally {\n try {\n fs.rmSync(tmpDir, { recursive: true, force: true });\n } catch {\n // Best effort cleanup\n }\n }\n }\n}\n","/**\n * Security module re-exports.\n *\n * Protocol spec: Security subsystem\n */\n\nexport { AuditLogger, setAuditLogger, getAuditLogger } from \"./audit.js\";\nexport { AuthProvider } from \"./auth.js\";\nexport { ConfigEncryptor } from \"./config-encryptor.js\";\nexport { Sandbox } from \"./sandbox.js\";\n","/**\n * apcore-cli — Public API exports.\n *\n * This module re-exports the public surface of the apcore CLI package.\n */\n\n// Core CLI\nexport { createCli, main, buildModuleCommand, validateModuleId, collectInput, reconvertEnumValues } from \"./main.js\";\nexport type { OptionConfig } from \"./main.js\";\n\n// Lazy module loading\nexport { LazyModuleGroup } from \"./cli.js\";\nexport type { Registry, Executor, ModuleDescriptor } from \"./cli.js\";\n\n// Configuration\nexport { ConfigResolver, DEFAULTS } from \"./config.js\";\n\n// Discovery\nexport { registerDiscoveryCommands } from \"./discovery.js\";\n\n// Output formatting\nexport { formatExecResult, resolveFormat, truncate, formatModuleList, formatModuleDetail } from \"./output.js\";\n\n// Schema handling\nexport { resolveRefs } from \"./ref-resolver.js\";\nexport { schemaToCliOptions, mapType, extractHelp } from \"./schema-parser.js\";\n\n// Approval\nexport { checkApproval } from \"./approval.js\";\n\n// Shell integration\nexport { registerShellCommands } from \"./shell.js\";\n\n// Errors\nexport {\n ApprovalTimeoutError,\n ApprovalDeniedError,\n AuthenticationError,\n ConfigDecryptionError,\n ModuleExecutionError,\n ModuleNotFoundError,\n SchemaValidationError,\n EXIT_CODES,\n exitCodeForError,\n} from \"./errors.js\";\nexport type { ExitCode } from \"./errors.js\";\n\n// Logger\nexport { setLogLevel, getLogLevel, debug, info, warn, error } from \"./logger.js\";\n\n// Security\nexport { AuditLogger, setAuditLogger, getAuditLogger, AuthProvider, ConfigEncryptor, Sandbox } from \"./security/index.js\";\n","/**\n * CLI entry point — createCli / main equivalents.\n *\n * Protocol spec: CLI bootstrapping & command registration\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport * as path from \"node:path\";\nimport { Command, CommanderError } from \"commander\";\nimport { EXIT_CODES, exitCodeForError } from \"./errors.js\";\nimport { resolveRefs } from \"./ref-resolver.js\";\nimport { schemaToCliOptions } from \"./schema-parser.js\";\nimport { checkApproval } from \"./approval.js\";\nimport { formatExecResult } from \"./output.js\";\nimport { setLogLevel } from \"./logger.js\";\nimport type { Executor, ModuleDescriptor } from \"./cli.js\";\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(path.resolve(__dirname, \"../package.json\"), \"utf-8\"));\nconst VERSION: string = pkg.version;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Configuration for a single Commander option derived from a JSON Schema property. */\nexport interface OptionConfig {\n /** The property name from the schema. */\n name: string;\n /** Commander flags string (e.g. \"--my-flag <value>\" or \"--flag, --no-flag\"). */\n flags: string;\n /** Help text for the option. */\n description: string;\n /** Default value. */\n defaultValue?: unknown;\n /** Whether the field is required (for display only). */\n required: boolean;\n /** Enum choices (string values). */\n choices?: string[];\n /** Whether this is a boolean flag pair (--flag/--no-flag). */\n isBooleanFlag?: boolean;\n /** Maps string enum value → original type name (\"int\", \"float\", \"bool\"). */\n enumOriginalTypes?: Record<string, string>;\n /** Parser function for Commander (e.g. parseInt, parseFloat). */\n parseArg?: (value: string) => unknown;\n}\n\n// ---------------------------------------------------------------------------\n// createCli\n// ---------------------------------------------------------------------------\n\n/**\n * Build and return the top-level Commander program.\n *\n * @param extensionsDir Path to the extensions directory (default: ./extensions)\n * @param progName Program name shown in help (default: apcore-cli)\n */\nexport function createCli(\n extensionsDir?: string,\n progName?: string,\n): Command {\n // Resolve program name\n const resolvedProgName = progName ?? path.basename(process.argv[1] ?? \"apcore-cli\") ?? \"apcore-cli\";\n\n // Resolve log level\n const cliLogLevel = process.env.APCORE_CLI_LOGGING_LEVEL ?? process.env.APCORE_LOGGING_LEVEL ?? \"WARNING\";\n setLogLevel(cliLogLevel);\n\n const program = new Command(resolvedProgName)\n .exitOverride()\n .version(VERSION, \"--version\", `Show ${resolvedProgName} version`)\n .description(\"apcore CLI — execute apcore modules from the command line\")\n .option(\"--extensions-dir <path>\", \"Path to extensions directory\")\n .option(\"--log-level <level>\", \"Logging level (DEBUG|INFO|WARNING|ERROR)\", \"WARNING\");\n\n // NOTE: Full registry/executor wiring requires apcore-js to be available.\n // For now, extensions-dir is accepted but not wired to a real registry.\n void extensionsDir;\n\n return program;\n}\n\n// ---------------------------------------------------------------------------\n// main\n// ---------------------------------------------------------------------------\n\n/**\n * Parse argv and run the CLI. Handles top-level error catching and exit codes.\n */\nexport function main(progName?: string): void {\n const program = createCli(undefined, progName);\n\n try {\n program.parse(process.argv);\n } catch (error: unknown) {\n if (error instanceof CommanderError) {\n // Commander already printed the error message\n process.exit(error.exitCode);\n }\n const code = exitCodeForError(error);\n if (error instanceof Error) {\n process.stderr.write(`Error: ${error.message}\\n`);\n }\n process.exit(code);\n }\n}\n\n// ---------------------------------------------------------------------------\n// buildModuleCommand\n// ---------------------------------------------------------------------------\n\n/**\n * Build a Commander Command for a single apcore module.\n */\nexport function buildModuleCommand(\n moduleDef: ModuleDescriptor,\n executor: Executor,\n helpTextMaxLength = 1000,\n): Command {\n const moduleId = moduleDef.id;\n let resolvedSchema: Record<string, unknown> = {};\n let schemaOptions: OptionConfig[] = [];\n\n // Resolve schema\n const inputSchema = moduleDef.inputSchema;\n if (inputSchema && typeof inputSchema === \"object\" && inputSchema.properties) {\n try {\n resolvedSchema = resolveRefs(inputSchema, 32, moduleId);\n } catch {\n resolvedSchema = inputSchema;\n }\n schemaOptions = schemaToCliOptions(resolvedSchema, helpTextMaxLength);\n }\n\n const cmd = new Command(moduleId).description(moduleDef.description);\n\n // Built-in options\n cmd.option(\"--input <source>\", \"Read input from STDIN ('-')\");\n cmd.option(\"-y, --yes\", \"Bypass approval prompts\", false);\n cmd.option(\"--large-input\", \"Allow STDIN input larger than 10MB\", false);\n cmd.option(\"--format <format>\", \"Output format (json|table)\");\n cmd.option(\"--sandbox\", \"Run module in subprocess sandbox\", false);\n\n // Schema-generated options\n for (const opt of schemaOptions) {\n if (opt.parseArg) {\n cmd.option(opt.flags, opt.description, opt.parseArg, opt.defaultValue);\n } else {\n cmd.option(opt.flags, opt.description, opt.defaultValue as string | boolean | undefined);\n }\n }\n\n // Action callback\n cmd.action(async (options: Record<string, unknown>) => {\n // Pop built-in options\n const stdinFlag = options.input as string | undefined;\n const autoApprove = options.yes as boolean;\n const largeInput = options.largeInput as boolean;\n const outputFormat = options.format as string | undefined;\n const sandboxEnabled = options.sandbox as boolean;\n\n // Remove built-in keys from options to get schema kwargs\n const schemaKwargs: Record<string, unknown> = {};\n const builtinKeys = new Set([\"input\", \"yes\", \"largeInput\", \"format\", \"sandbox\"]);\n for (const [k, v] of Object.entries(options)) {\n if (!builtinKeys.has(k)) {\n schemaKwargs[k] = v;\n }\n }\n\n try {\n // Collect and merge input\n const merged = await collectInput(stdinFlag, schemaKwargs, largeInput);\n\n // Reconvert enum values\n const reconverted = reconvertEnumValues(merged, schemaOptions);\n\n // Check approval\n await checkApproval(moduleDef, autoApprove);\n\n // Execute with timing\n const { Sandbox } = await import(\"./security/index.js\");\n const sandbox = new Sandbox(sandboxEnabled);\n const startTime = performance.now();\n const result = await sandbox.execute(moduleId, reconverted, executor);\n const durationMs = Math.round(performance.now() - startTime);\n\n // Audit log (success)\n const { getAuditLogger } = await import(\"./security/audit.js\");\n const auditLogger = getAuditLogger();\n if (auditLogger) {\n auditLogger.logExecution(moduleId, reconverted, \"success\", 0, durationMs);\n }\n\n // Format output\n formatExecResult(result, outputFormat);\n } catch (err: unknown) {\n // Audit log (error)\n const { getAuditLogger } = await import(\"./security/audit.js\");\n const auditLogger = getAuditLogger();\n const code = exitCodeForError(err);\n if (auditLogger) {\n auditLogger.logExecution(moduleId, {}, \"error\", code, 0);\n }\n\n if (err instanceof Error) {\n process.stderr.write(`Error: ${err.message}\\n`);\n }\n process.exit(code);\n }\n });\n\n return cmd;\n}\n\n// ---------------------------------------------------------------------------\n// validateModuleId\n// ---------------------------------------------------------------------------\n\n/**\n * Validate that a module ID conforms to the expected format.\n * Pattern: [a-z][a-z0-9_]*(.[a-z][a-z0-9_])* — max 128 chars.\n */\nexport function validateModuleId(moduleId: string): void {\n if (moduleId.length > 128) {\n process.stderr.write(\n `Error: Invalid module ID format: '${moduleId}'. Maximum length is 128 characters.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n if (!/^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)*$/.test(moduleId)) {\n process.stderr.write(\n `Error: Invalid module ID format: '${moduleId}'.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n}\n\n// ---------------------------------------------------------------------------\n// collectInput\n// ---------------------------------------------------------------------------\n\n/**\n * Collect module input from stdin and/or CLI keyword arguments.\n */\nexport async function collectInput(\n stdinFlag?: string,\n cliKwargs: Record<string, unknown> = {},\n largeInput?: boolean,\n): Promise<Record<string, unknown>> {\n // Remove null/undefined values from CLI kwargs\n const cliKwargsNonNull: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(cliKwargs)) {\n if (v !== null && v !== undefined) {\n cliKwargsNonNull[k] = v;\n }\n }\n\n if (!stdinFlag) {\n return cliKwargsNonNull;\n }\n\n if (stdinFlag === \"-\") {\n const raw = await readStdin();\n const rawSize = Buffer.byteLength(raw, \"utf-8\");\n\n if (rawSize > 10_485_760 && !largeInput) {\n process.stderr.write(\n \"Error: STDIN input exceeds 10MB limit. Use --large-input to override.\\n\",\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n if (!raw) {\n return cliKwargsNonNull;\n }\n\n let stdinData: unknown;\n try {\n stdinData = JSON.parse(raw);\n } catch {\n process.stderr.write(\n \"Error: STDIN does not contain valid JSON.\\n\",\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n if (typeof stdinData !== \"object\" || stdinData === null || Array.isArray(stdinData)) {\n process.stderr.write(\n `Error: STDIN JSON must be an object, got ${Array.isArray(stdinData) ? \"array\" : typeof stdinData}.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n // CLI flags override STDIN for duplicate keys\n return { ...(stdinData as Record<string, unknown>), ...cliKwargsNonNull };\n }\n\n return cliKwargsNonNull;\n}\n\n/**\n * Read all data from stdin with proper cleanup.\n */\nfunction readStdin(): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n const onData = (chunk: Buffer) => chunks.push(chunk);\n const onEnd = () => {\n cleanup();\n resolve(Buffer.concat(chunks).toString(\"utf-8\"));\n };\n const onError = (err: Error) => {\n cleanup();\n reject(err);\n };\n const cleanup = () => {\n process.stdin.removeListener(\"data\", onData);\n process.stdin.removeListener(\"end\", onEnd);\n process.stdin.removeListener(\"error\", onError);\n };\n process.stdin.on(\"data\", onData);\n process.stdin.on(\"end\", onEnd);\n process.stdin.on(\"error\", onError);\n process.stdin.resume();\n });\n}\n\n// ---------------------------------------------------------------------------\n// reconvertEnumValues\n// ---------------------------------------------------------------------------\n\n/**\n * Re-convert CLI string values back to their schema-typed equivalents\n * based on the option configs.\n */\nexport function reconvertEnumValues(\n kwargs: Record<string, unknown>,\n options: OptionConfig[],\n): Record<string, unknown> {\n const result = { ...kwargs };\n for (const opt of options) {\n if (!opt.enumOriginalTypes) continue;\n const paramName = opt.name;\n if (!(paramName in result) || result[paramName] === null || result[paramName] === undefined) {\n continue;\n }\n const strVal = String(result[paramName]);\n const origType = opt.enumOriginalTypes[strVal];\n if (origType === \"int\") {\n result[paramName] = parseInt(strVal, 10);\n } else if (origType === \"float\") {\n result[paramName] = parseFloat(strVal);\n } else if (origType === \"bool\") {\n result[paramName] = strVal.toLowerCase() === \"true\";\n }\n }\n return result;\n}\n","/**\n * JSON Schema $ref resolver.\n *\n * Protocol spec: Schema resolution & $ref handling\n */\n\nimport { EXIT_CODES } from \"./errors.js\";\n\n// ---------------------------------------------------------------------------\n// resolveRefs\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve all $ref references in a JSON Schema.\n * Returns a fully inlined schema with $defs/definitions removed.\n */\nexport function resolveRefs(\n schema: Record<string, unknown>,\n maxDepth = 32,\n moduleId = \"\",\n): Record<string, unknown> {\n const cloned = structuredClone(schema);\n const defs = (cloned.$defs ?? cloned.definitions ?? {}) as Record<\n string,\n unknown\n >;\n const result = resolveNode(\n cloned,\n defs,\n new Set<string>(),\n 0,\n maxDepth,\n moduleId,\n ) as Record<string, unknown>;\n\n // Remove definition keys\n delete result.$defs;\n delete result.definitions;\n return result;\n}\n\nfunction resolveNode(\n node: unknown,\n defs: Record<string, unknown>,\n visited: Set<string>,\n depth: number,\n maxDepth: number,\n moduleId: string,\n): unknown {\n if (typeof node !== \"object\" || node === null || Array.isArray(node)) {\n return node;\n }\n\n const obj = node as Record<string, unknown>;\n\n // Handle $ref\n if (\"$ref\" in obj) {\n const refPath = obj.$ref as string;\n\n if (depth >= maxDepth) {\n process.stderr.write(\n `Error: $ref resolution depth exceeded maximum of ${maxDepth} for module '${moduleId}'.\\n`,\n );\n process.exit(EXIT_CODES.SCHEMA_CIRCULAR_REF);\n }\n\n if (visited.has(refPath)) {\n process.stderr.write(\n `Error: Circular $ref detected in schema for module '${moduleId}' at path '${refPath}'.\\n`,\n );\n process.exit(EXIT_CODES.SCHEMA_CIRCULAR_REF);\n }\n\n // Parse ref target: extract key from \"#/$defs/Address\" → \"Address\"\n const parts = refPath.split(\"/\");\n const key = parts[parts.length - 1];\n\n if (!(key in defs)) {\n process.stderr.write(\n `Error: Unresolvable $ref '${refPath}' in schema for module '${moduleId}'.\\n`,\n );\n process.exit(EXIT_CODES.SCHEMA_VALIDATION_ERROR);\n }\n\n const newVisited = new Set(visited);\n newVisited.add(refPath);\n return resolveNode(defs[key], defs, newVisited, depth + 1, maxDepth, moduleId);\n }\n\n // Handle allOf\n if (\"allOf\" in obj && Array.isArray(obj.allOf)) {\n const merged: Record<string, unknown> = {\n properties: {},\n required: [] as string[],\n };\n for (const subSchema of obj.allOf as unknown[]) {\n const resolved = resolveNode(\n subSchema,\n defs,\n visited,\n depth + 1,\n maxDepth,\n moduleId,\n ) as Record<string, unknown>;\n if (resolved.properties) {\n Object.assign(\n merged.properties as Record<string, unknown>,\n resolved.properties,\n );\n }\n if (Array.isArray(resolved.required)) {\n (merged.required as string[]).push(...resolved.required);\n }\n }\n // Deduplicate required\n merged.required = [...new Set(merged.required as string[])];\n // Copy non-composition keys\n for (const [k, v] of Object.entries(obj)) {\n if (k !== \"allOf\" && !(k in merged)) {\n merged[k] = v;\n }\n }\n return merged;\n }\n\n // Handle anyOf / oneOf\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n if (keyword in obj && Array.isArray(obj[keyword])) {\n const merged: Record<string, unknown> = {\n properties: {},\n required: [] as string[],\n };\n const allRequiredSets: Set<string>[] = [];\n for (const subSchema of obj[keyword] as unknown[]) {\n const resolved = resolveNode(\n subSchema,\n defs,\n visited,\n depth + 1,\n maxDepth,\n moduleId,\n ) as Record<string, unknown>;\n if (resolved.properties) {\n Object.assign(\n merged.properties as Record<string, unknown>,\n resolved.properties,\n );\n }\n if (Array.isArray(resolved.required)) {\n allRequiredSets.push(new Set(resolved.required as string[]));\n }\n }\n // Required = intersection of all branches\n if (allRequiredSets.length > 0) {\n let intersection = allRequiredSets[0];\n for (let i = 1; i < allRequiredSets.length; i++) {\n intersection = new Set(\n [...intersection].filter((x) => allRequiredSets[i].has(x)),\n );\n }\n merged.required = [...intersection];\n } else {\n merged.required = [];\n }\n // Copy non-composition keys\n for (const [k, v] of Object.entries(obj)) {\n if (k !== keyword && !(k in merged)) {\n merged[k] = v;\n }\n }\n return merged;\n }\n }\n\n // Recursively process nested properties\n if (\"properties\" in obj && typeof obj.properties === \"object\" && obj.properties !== null) {\n const props = obj.properties as Record<string, unknown>;\n for (const [propName, propSchema] of Object.entries(props)) {\n props[propName] = resolveNode(\n propSchema,\n defs,\n visited,\n depth + 1,\n maxDepth,\n moduleId,\n );\n }\n }\n\n return obj;\n}\n","/**\n * JSON Schema -> Commander options mapping.\n *\n * Protocol spec: Schema-driven argument parsing\n */\n\nimport type { OptionConfig } from \"./main.js\";\nimport { EXIT_CODES } from \"./errors.js\";\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/** Sentinel type marker for boolean flags. */\nconst BOOLEAN_FLAG = Symbol(\"BOOLEAN_FLAG\");\n\ntype TypeResult = \"string\" | \"int\" | \"float\" | typeof BOOLEAN_FLAG | \"file\";\n\n/**\n * Map JSON Schema type to a type identifier.\n */\nexport function mapType(propName: string, propSchema: Record<string, unknown>): TypeResult {\n const schemaType = propSchema.type as string | undefined;\n\n // Check file convention\n if (\n schemaType === \"string\" &&\n (propName.endsWith(\"_file\") || propSchema[\"x-cli-file\"] === true)\n ) {\n return \"file\";\n }\n\n const typeMap: Record<string, TypeResult> = {\n string: \"string\",\n integer: \"int\",\n number: \"float\",\n boolean: BOOLEAN_FLAG,\n object: \"string\",\n array: \"string\",\n };\n\n if (!schemaType) {\n return \"string\";\n }\n\n return typeMap[schemaType] ?? \"string\";\n}\n\n/**\n * Extract help text from schema property, preferring x-llm-description.\n */\nexport function extractHelp(propSchema: Record<string, unknown>, maxLength = 1000): string | undefined {\n let text = propSchema[\"x-llm-description\"] as string | undefined;\n if (!text) {\n text = propSchema.description as string | undefined;\n }\n if (!text) {\n return undefined;\n }\n if (maxLength > 0 && text.length > maxLength) {\n return text.slice(0, maxLength - 3) + \"...\";\n }\n return text;\n}\n\n// ---------------------------------------------------------------------------\n// schemaToCliOptions\n// ---------------------------------------------------------------------------\n\n/** Reserved CLI option names that cannot be used by schema properties. */\nconst RESERVED_NAMES = new Set([\"input\", \"yes\", \"large_input\", \"format\", \"sandbox\"]);\n\n/**\n * Convert a JSON Schema `properties` object into an array of\n * Commander option configurations.\n */\nexport function schemaToCliOptions(\n schema: Record<string, unknown>,\n maxHelpLength = 1000,\n): OptionConfig[] {\n const properties = (schema.properties ?? {}) as Record<\n string,\n Record<string, unknown>\n >;\n const requiredList = (schema.required ?? []) as string[];\n const options: OptionConfig[] = [];\n const flagNames: Record<string, string> = {};\n\n for (const [propName, propSchema] of Object.entries(properties)) {\n const flagName = \"--\" + propName.replace(/_/g, \"-\");\n\n // Collision detection\n if (flagName in flagNames) {\n process.stderr.write(\n `Error: Flag name collision: properties '${propName}' and '${flagNames[flagName]}' both map to '${flagName}'.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n flagNames[flagName] = propName;\n\n // Reserved name check\n if (RESERVED_NAMES.has(propName)) {\n process.stderr.write(\n `Error: Module schema property '${propName}' conflicts with a reserved CLI option name. Rename the property.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n const typeResult = mapType(propName, propSchema);\n const isRequired = requiredList.includes(propName);\n const helpBase = extractHelp(propSchema, maxHelpLength);\n const helpText = isRequired\n ? (helpBase ? helpBase + \" \" : \"\") + \"[required]\"\n : helpBase ?? \"\";\n const defaultValue = propSchema.default as unknown;\n\n if (typeResult === BOOLEAN_FLAG) {\n // Boolean flag pair: --flag/--no-flag\n const flagBase = propName.replace(/_/g, \"-\");\n const defaultVal = (propSchema.default as boolean) ?? false;\n options.push({\n name: propName,\n flags: `--${flagBase}, --no-${flagBase}`,\n description: helpText,\n defaultValue: defaultVal,\n required: false,\n isBooleanFlag: true,\n });\n } else if (\"enum\" in propSchema && Array.isArray(propSchema.enum)) {\n const enumValues = propSchema.enum as unknown[];\n if (enumValues.length === 0) {\n // Empty enum — fall back to plain string option\n options.push({\n name: propName,\n flags: `${flagName} <value>`,\n description: helpText,\n defaultValue,\n required: false,\n });\n } else {\n const stringValues = enumValues.map(String);\n const enumOriginalTypes: Record<string, string> = {};\n for (const v of enumValues) {\n if (typeof v === \"number\" && Number.isInteger(v)) {\n enumOriginalTypes[String(v)] = \"int\";\n } else if (typeof v === \"number\") {\n enumOriginalTypes[String(v)] = \"float\";\n } else if (typeof v === \"boolean\") {\n enumOriginalTypes[String(v)] = \"bool\";\n }\n }\n options.push({\n name: propName,\n flags: `${flagName} <value>`,\n description: helpText,\n defaultValue:\n defaultValue !== undefined ? String(defaultValue) : undefined,\n required: false,\n choices: stringValues,\n enumOriginalTypes:\n Object.keys(enumOriginalTypes).length > 0\n ? enumOriginalTypes\n : undefined,\n });\n }\n } else {\n // Standard option\n let parseArg: ((value: string) => unknown) | undefined;\n if (typeResult === \"int\") {\n parseArg = (v: string) => {\n const n = parseInt(v, 10);\n if (isNaN(n)) throw new Error(`Invalid integer: ${v}`);\n return n;\n };\n } else if (typeResult === \"float\") {\n parseArg = (v: string) => {\n const n = parseFloat(v);\n if (isNaN(n)) throw new Error(`Invalid number: ${v}`);\n return n;\n };\n }\n options.push({\n name: propName,\n flags: `${flagName} <value>`,\n description: helpText,\n defaultValue,\n required: false,\n parseArg,\n });\n }\n }\n\n return options;\n}\n","/**\n * Interactive approval prompts with timeout.\n *\n * Protocol spec: Approval workflow\n */\n\nimport * as readline from \"node:readline\";\nimport type { ModuleDescriptor } from \"./cli.js\";\nimport { ApprovalTimeoutError, EXIT_CODES } from \"./errors.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Get an annotation value from either a dict or an object.\n */\nfunction getAnnotation(\n annotations: unknown,\n key: string,\n defaultValue: unknown = undefined,\n): unknown {\n if (!annotations || typeof annotations !== \"object\") return defaultValue;\n const ann = annotations as Record<string, unknown>;\n return key in ann ? ann[key] : defaultValue;\n}\n\n// ---------------------------------------------------------------------------\n// checkApproval\n// ---------------------------------------------------------------------------\n\n/**\n * Check if module requires approval and handle accordingly.\n * Returns normally if approved (or approval not required).\n * Calls process.exit(46) if denied/timed out/non-TTY.\n */\nexport async function checkApproval(\n moduleDef: ModuleDescriptor,\n autoApprove: boolean,\n): Promise<void> {\n const annotations = moduleDef.annotations;\n\n // Check if approval is required\n let requiresApproval: boolean;\n if (moduleDef.requiresApproval !== undefined) {\n requiresApproval = moduleDef.requiresApproval;\n } else if (annotations) {\n requiresApproval = getAnnotation(annotations, \"requires_approval\", false) === true;\n } else {\n return; // No annotations, no approval needed\n }\n\n if (!requiresApproval) {\n return;\n }\n\n const moduleId = moduleDef.id;\n\n // Bypass: autoApprove flag (highest priority)\n if (autoApprove) {\n return;\n }\n\n // Bypass: APCORE_CLI_AUTO_APPROVE env var\n const envVal = process.env.APCORE_CLI_AUTO_APPROVE ?? \"\";\n if (envVal === \"1\") {\n return;\n }\n if (envVal !== \"\" && envVal !== \"1\") {\n process.stderr.write(\n `Warning: APCORE_CLI_AUTO_APPROVE is set to '${envVal}', expected '1'. Ignoring.\\n`,\n );\n }\n\n // Non-TTY check\n if (!process.stdin.isTTY) {\n process.stderr.write(\n `Error: Module '${moduleId}' requires approval but no interactive ` +\n \"terminal is available. Use --yes or set APCORE_CLI_AUTO_APPROVE=1 \" +\n \"to bypass.\\n\",\n );\n process.exit(EXIT_CODES.APPROVAL_DENIED);\n }\n\n // TTY prompt\n await promptWithTimeout(moduleDef, 60);\n}\n\n/**\n * Display approval prompt with timeout.\n */\nasync function promptWithTimeout(\n moduleDef: ModuleDescriptor,\n timeout: number,\n): Promise<void> {\n // Clamp timeout\n timeout = Math.max(1, Math.min(timeout, 3600));\n\n const moduleId = moduleDef.id;\n const annotations = moduleDef.annotations;\n const message =\n (annotations\n ? (getAnnotation(annotations, \"approval_message\") as string | undefined)\n : undefined) ??\n `Module '${moduleId}' requires approval to execute.`;\n\n process.stderr.write(message + \"\\n\");\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n try {\n const answer = await Promise.race([\n new Promise<string>((resolve) => {\n rl.question(\"Proceed? [y/N] \", (ans) => resolve(ans));\n }),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n reject(new ApprovalTimeoutError(\n `Approval prompt timed out after ${timeout} seconds.`,\n ));\n }, timeout * 1000);\n }),\n ]);\n\n // Clear the timeout — prompt resolved before timeout fired\n if (timer) clearTimeout(timer);\n\n const normalized = answer.trim().toLowerCase();\n if (normalized === \"y\" || normalized === \"yes\") {\n return;\n }\n\n process.stderr.write(\"Error: Approval denied.\\n\");\n process.exit(EXIT_CODES.APPROVAL_DENIED);\n } catch (err) {\n if (timer) clearTimeout(timer);\n if (err instanceof ApprovalTimeoutError) {\n process.stderr.write(\n `Error: Approval prompt timed out after ${timeout} seconds.\\n`,\n );\n process.exit(EXIT_CODES.APPROVAL_TIMEOUT);\n }\n throw err;\n } finally {\n rl.close();\n }\n}\n","/**\n * TTY-adaptive output formatting (table/json).\n *\n * Protocol spec: Output formatting\n */\n\nimport type { ModuleDescriptor } from \"./cli.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve output format with TTY-adaptive default.\n */\nexport function resolveFormat(explicitFormat?: string): string {\n if (explicitFormat !== undefined) {\n return explicitFormat;\n }\n return process.stdout.isTTY ? \"table\" : \"json\";\n}\n\n/**\n * Truncate text to maxLength, appending '...' if needed.\n */\nexport function truncate(text: string, maxLength = 80): string {\n if (text.length <= maxLength) {\n return text;\n }\n return text.slice(0, maxLength - 3) + \"...\";\n}\n\n/**\n * Render a simple plain-text table with column headers.\n */\nfunction formatTable(\n headers: string[],\n rows: string[][],\n): string {\n // Calculate column widths\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)),\n );\n\n const sep = colWidths.map((w) => \"-\".repeat(w)).join(\" \");\n const headerLine = headers\n .map((h, i) => h.padEnd(colWidths[i]))\n .join(\" \");\n const dataLines = rows.map((row) =>\n row.map((cell, i) => (cell ?? \"\").padEnd(colWidths[i])).join(\" \"),\n );\n\n return [headerLine, sep, ...dataLines].join(\"\\n\") + \"\\n\";\n}\n\n// ---------------------------------------------------------------------------\n// formatModuleList\n// ---------------------------------------------------------------------------\n\n/**\n * Format and print a list of modules.\n */\nexport function formatModuleList(\n modules: ModuleDescriptor[],\n format: string,\n filterTags?: string[],\n): void {\n if (format === \"table\") {\n if (modules.length === 0 && filterTags && filterTags.length > 0) {\n process.stdout.write(\n `No modules found matching tags: ${filterTags.join(\", \")}.\\n`,\n );\n return;\n }\n if (modules.length === 0) {\n process.stdout.write(\"No modules found.\\n\");\n return;\n }\n\n const headers = [\"ID\", \"Description\", \"Tags\"];\n const rows = modules.map((m) => [\n m.id,\n truncate(m.description, 80),\n (m.tags ?? []).join(\", \"),\n ]);\n process.stdout.write(formatTable(headers, rows));\n } else if (format === \"json\") {\n const result = modules.map((m) => ({\n id: m.id,\n description: m.description,\n tags: m.tags ?? [],\n }));\n process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// formatModuleDetail\n// ---------------------------------------------------------------------------\n\n/**\n * Convert annotations to a plain dict, filtering out falsy/default values.\n */\nfunction annotationsToDict(\n annotations: unknown,\n): Record<string, unknown> | null {\n if (!annotations) return null;\n if (typeof annotations !== \"object\" || Array.isArray(annotations)) return null;\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(annotations as Record<string, unknown>)) {\n if (v !== null && v !== undefined && v !== false && v !== 0 && !(Array.isArray(v) && v.length === 0)) {\n result[k] = v;\n }\n }\n return Object.keys(result).length > 0 ? result : null;\n}\n\n/**\n * Format and print full module metadata.\n */\nexport function formatModuleDetail(\n moduleDef: ModuleDescriptor,\n format: string,\n): void {\n if (format === \"table\") {\n process.stdout.write(`\\nModule: ${moduleDef.id}\\n`);\n process.stdout.write(`\\nDescription:\\n ${moduleDef.description}\\n`);\n\n if (moduleDef.inputSchema && Object.keys(moduleDef.inputSchema).length > 0) {\n process.stdout.write(\"\\nInput Schema:\\n\");\n process.stdout.write(JSON.stringify(moduleDef.inputSchema, null, 2) + \"\\n\");\n }\n\n if (moduleDef.outputSchema && Object.keys(moduleDef.outputSchema).length > 0) {\n process.stdout.write(\"\\nOutput Schema:\\n\");\n process.stdout.write(JSON.stringify(moduleDef.outputSchema, null, 2) + \"\\n\");\n }\n\n const annDict = annotationsToDict(\n moduleDef.annotations,\n );\n if (annDict) {\n process.stdout.write(\"\\nAnnotations:\\n\");\n for (const [k, v] of Object.entries(annDict)) {\n process.stdout.write(` ${k}: ${v}\\n`);\n }\n }\n\n // Extension metadata (x- prefixed)\n const metadata = moduleDef.metadata;\n if (metadata) {\n const xFields: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(metadata)) {\n if (k.startsWith(\"x-\") || k.startsWith(\"x_\")) {\n xFields[k] = v;\n }\n }\n if (Object.keys(xFields).length > 0) {\n process.stdout.write(\"\\nExtension Metadata:\\n\");\n for (const [k, v] of Object.entries(xFields)) {\n process.stdout.write(` ${k}: ${v}\\n`);\n }\n }\n }\n\n const tags = moduleDef.tags ?? [];\n if (tags.length > 0) {\n process.stdout.write(`\\nTags: ${tags.join(\", \")}\\n`);\n }\n } else if (format === \"json\") {\n const result: Record<string, unknown> = {\n id: moduleDef.id,\n description: moduleDef.description,\n };\n if (moduleDef.inputSchema) result.input_schema = moduleDef.inputSchema;\n if (moduleDef.outputSchema) result.output_schema = moduleDef.outputSchema;\n\n const annDict = annotationsToDict(\n moduleDef.annotations,\n );\n if (annDict) result.annotations = annDict;\n\n const tags = moduleDef.tags ?? [];\n if (tags.length > 0) result.tags = tags;\n\n // Extension metadata\n const metadata = moduleDef.metadata;\n if (metadata) {\n for (const [k, v] of Object.entries(metadata)) {\n if (k.startsWith(\"x-\") || k.startsWith(\"x_\")) {\n result[k] = v;\n }\n }\n }\n\n process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// formatExecResult\n// ---------------------------------------------------------------------------\n\n/**\n * Format and print module execution result.\n */\nexport function formatExecResult(\n result: unknown,\n format?: string,\n): void {\n if (result === null || result === undefined) {\n return;\n }\n const effective = resolveFormat(format);\n if (\n effective === \"table\" &&\n typeof result === \"object\" &&\n !Array.isArray(result)\n ) {\n // Key-value table\n const entries = Object.entries(result as Record<string, unknown>);\n const headers = [\"Key\", \"Value\"];\n const rows = entries.map(([k, v]) => [String(k), String(v)]);\n process.stdout.write(formatTable(headers, rows));\n } else if (typeof result === \"object\") {\n process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n } else if (typeof result === \"string\") {\n process.stdout.write(result + \"\\n\");\n } else {\n process.stdout.write(String(result) + \"\\n\");\n }\n}\n","/**\n * Simple structured logger respecting logging.level config.\n */\n\nconst LEVELS = { DEBUG: 0, INFO: 1, WARNING: 2, ERROR: 3 } as const;\ntype LogLevel = keyof typeof LEVELS;\n\nlet currentLevel: LogLevel = \"WARNING\";\n\nexport function setLogLevel(level: string): void {\n const upper = level.toUpperCase();\n if (upper in LEVELS) {\n currentLevel = upper as LogLevel;\n }\n}\n\nexport function getLogLevel(): LogLevel {\n return currentLevel;\n}\n\nfunction shouldLog(level: LogLevel): boolean {\n return LEVELS[level] >= LEVELS[currentLevel];\n}\n\nexport function debug(message: string): void {\n if (shouldLog(\"DEBUG\")) process.stderr.write(`DEBUG: ${message}\\n`);\n}\n\nexport function info(message: string): void {\n if (shouldLog(\"INFO\")) process.stderr.write(`INFO: ${message}\\n`);\n}\n\nexport function warn(message: string): void {\n if (shouldLog(\"WARNING\")) process.stderr.write(`WARNING: ${message}\\n`);\n}\n\nexport function error(message: string): void {\n if (shouldLog(\"ERROR\")) process.stderr.write(`ERROR: ${message}\\n`);\n}\n","/**\n * LazyModuleGroup — Dynamic command loading from Registry.\n *\n * Equivalent to the Python LazyModuleGroup. Dynamically discovers apcore\n * modules from the Registry and exposes them as Commander subcommands.\n *\n * Protocol spec: CLI command structure & lazy loading\n */\n\nimport { Command } from \"commander\";\nimport { buildModuleCommand } from \"./main.js\";\n\n// TODO: Import Registry and Executor from apcore-js once available\n// import type { Registry, Executor, ModuleDescriptor } from \"apcore-js\";\n\n// ---------------------------------------------------------------------------\n// Placeholder types until apcore-js types are available\n// ---------------------------------------------------------------------------\n\n/** Placeholder for apcore-js Registry. */\nexport interface Registry {\n listModules(): ModuleDescriptor[];\n getModule(moduleId: string): ModuleDescriptor | null;\n}\n\n/** Placeholder for apcore-js Executor. */\nexport interface Executor {\n execute(moduleId: string, input: Record<string, unknown>): Promise<unknown>;\n}\n\n/** Placeholder for apcore-js ModuleDescriptor. */\nexport interface ModuleDescriptor {\n id: string;\n name: string;\n description: string;\n tags?: string[];\n inputSchema?: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n requiresApproval?: boolean;\n annotations?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// LazyModuleGroup\n// ---------------------------------------------------------------------------\n\n/**\n * Dynamically loads apcore modules as Commander subcommands from Registry.\n *\n * TODO: Implement lazy loading — commands should only be fully built when\n * actually invoked, not at registration time.\n */\nexport class LazyModuleGroup {\n private readonly registry: Registry;\n readonly executor: Executor;\n private readonly helpTextMaxLength: number;\n private commandCache: Map<string, Command> = new Map();\n\n constructor(registry: Registry, executor: Executor, helpTextMaxLength = 1000) {\n this.registry = registry;\n this.executor = executor;\n this.helpTextMaxLength = helpTextMaxLength;\n }\n\n /**\n * List all available command names from the Registry.\n *\n * TODO: Implement registry enumeration.\n */\n listCommands(): string[] {\n // TODO: Query registry for all module IDs\n return this.registry.listModules().map((m) => m.id);\n }\n\n /**\n * Get or lazily build a Commander Command for the given module.\n *\n * TODO: Implement lazy command construction with schema-based options.\n */\n getCommand(cmdName: string): Command | null {\n if (this.commandCache.has(cmdName)) {\n return this.commandCache.get(cmdName)!;\n }\n\n const moduleDef = this.registry.getModule(cmdName);\n if (!moduleDef) {\n return null;\n }\n\n const cmd = buildModuleCommand(moduleDef, this.executor, this.helpTextMaxLength);\n this.commandCache.set(cmdName, cmd);\n return cmd;\n }\n}\n","/**\n * ConfigResolver — 4-tier config resolution (CLI flag > env > file > default).\n *\n * Protocol spec: Configuration resolution\n */\n\nimport * as fs from \"node:fs\";\nimport yaml from \"js-yaml\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Default configuration values. */\nexport const DEFAULTS: Record<string, unknown> = {\n \"extensions.root\": \"./extensions\",\n \"logging.level\": \"WARNING\",\n \"sandbox.enabled\": false,\n \"cli.stdin_buffer_limit\": 10_485_760,\n \"cli.auto_approve\": false,\n \"cli.help_text_max_length\": 1000,\n};\n\n// ---------------------------------------------------------------------------\n// ConfigResolver\n// ---------------------------------------------------------------------------\n\n/**\n * Resolves configuration from four tiers (highest to lowest priority):\n * 1. CLI flags\n * 2. Environment variables\n * 3. Config file (YAML/JSON)\n * 4. Built-in defaults\n */\nexport class ConfigResolver {\n private readonly cliFlags: Record<string, unknown>;\n private readonly configPath: string;\n private fileCache: Record<string, unknown> | null = null;\n private fileCacheLoaded = false;\n\n constructor(cliFlags?: Record<string, unknown>, configPath?: string) {\n this.cliFlags = cliFlags ?? {};\n this.configPath = configPath ?? \"apcore.yaml\";\n }\n\n /**\n * Resolve a single configuration key across all four tiers.\n */\n resolve(key: string, cliFlag?: string, envVar?: string): unknown {\n // Tier 1: CLI flag\n const flagKey = cliFlag ?? key;\n if (flagKey in this.cliFlags) {\n const value = this.cliFlags[flagKey];\n if (value !== null && value !== undefined) {\n return value;\n }\n }\n\n // Tier 2: Environment variable\n if (envVar) {\n const envValue = process.env[envVar];\n if (envValue !== undefined && envValue !== \"\") {\n return envValue;\n }\n }\n\n // Tier 3: Config file\n const fileValue = this.resolveFromFile(key);\n if (fileValue !== undefined) {\n return fileValue;\n }\n\n // Tier 4: Defaults\n return DEFAULTS[key];\n }\n\n /**\n * Load a value from the config file using a dot-separated key path.\n */\n private resolveFromFile(key: string): unknown {\n if (!this.fileCacheLoaded) {\n this.fileCache = this.loadConfigFile();\n this.fileCacheLoaded = true;\n }\n if (this.fileCache === null) {\n return undefined;\n }\n return this.fileCache[key];\n }\n\n /**\n * Load and flatten a YAML config file.\n */\n private loadConfigFile(): Record<string, unknown> | null {\n let content: string;\n try {\n content = fs.readFileSync(this.configPath, \"utf-8\");\n } catch (err: unknown) {\n if (err instanceof Error && \"code\" in err && err.code === \"ENOENT\") {\n return null;\n }\n console.warn(\n `Configuration file '${this.configPath}' is malformed, using defaults.`,\n );\n return null;\n }\n\n let parsed: unknown;\n try {\n parsed = yaml.load(content);\n } catch {\n console.warn(\n `Configuration file '${this.configPath}' is malformed, using defaults.`,\n );\n return null;\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n console.warn(\n `Configuration file '${this.configPath}' is malformed, using defaults.`,\n );\n return null;\n }\n\n return this.flattenDict(parsed as Record<string, unknown>);\n }\n\n /**\n * Flatten nested dict to dot-notation keys.\n */\n private flattenDict(\n d: Record<string, unknown>,\n prefix = \"\",\n ): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(d)) {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n if (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value)\n ) {\n Object.assign(\n result,\n this.flattenDict(value as Record<string, unknown>, fullKey),\n );\n } else {\n result[fullKey] = value;\n }\n }\n return result;\n }\n}\n","/**\n * Discovery commands — list and describe modules.\n *\n * Protocol spec: Module discovery & introspection\n */\n\nimport { Command } from \"commander\";\nimport type { ModuleDescriptor, Registry } from \"./cli.js\";\nimport { EXIT_CODES } from \"./errors.js\";\nimport { validateModuleId } from \"./main.js\";\nimport {\n formatModuleDetail,\n formatModuleList,\n resolveFormat,\n} from \"./output.js\";\n\nconst TAG_PATTERN = /^[a-z][a-z0-9_-]*$/;\n\nfunction validateTag(tag: string): void {\n if (!TAG_PATTERN.test(tag)) {\n process.stderr.write(\n `Error: Invalid tag format: '${tag}'. Tags must match [a-z][a-z0-9_-]*.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n}\n\n/**\n * Collect repeated --tag options into an array.\n */\nfunction collectTag(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n\n/**\n * Register list and describe commands on the CLI group.\n */\nexport function registerDiscoveryCommands(\n cli: Command,\n registry: Registry,\n): void {\n const listCmd = new Command(\"list\")\n .description(\"List available modules in the registry.\")\n .option(\"--tag <tag>\", \"Filter modules by tag (AND logic). Repeatable.\", collectTag, [])\n .option(\"--format <format>\", \"Output format.\", undefined)\n .action((opts: { tag: string[]; format?: string }) => {\n // Validate tags\n for (const t of opts.tag) {\n validateTag(t);\n }\n\n const modules: ModuleDescriptor[] = [];\n for (const m of registry.listModules()) {\n modules.push(m);\n }\n\n let filtered = modules;\n if (opts.tag.length > 0) {\n const filterTags = new Set(opts.tag);\n filtered = modules.filter((m) => {\n const mTags = m.tags ?? [];\n return [...filterTags].every((t) => mTags.includes(t));\n });\n }\n\n const fmt = resolveFormat(opts.format);\n formatModuleList(filtered, fmt, opts.tag.length > 0 ? opts.tag : undefined);\n });\n cli.addCommand(listCmd);\n\n const describeCmd = new Command(\"describe\")\n .description(\"Show metadata, schema, and annotations for a module.\")\n .argument(\"<module-id>\", \"Module ID to describe\")\n .option(\"--format <format>\", \"Output format.\", undefined)\n .action((moduleId: string, opts: { format?: string }) => {\n validateModuleId(moduleId);\n\n const moduleDef = registry.getModule(moduleId);\n if (!moduleDef) {\n process.stderr.write(\n `Error: Module '${moduleId}' not found.\\n`,\n );\n process.exit(EXIT_CODES.MODULE_NOT_FOUND);\n }\n\n const fmt = resolveFormat(opts.format);\n formatModuleDetail(moduleDef, fmt);\n });\n cli.addCommand(describeCmd);\n}\n","/**\n * Shell completion + man page generation.\n *\n * Protocol spec: Shell integration\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport * as path from \"node:path\";\nimport { Command } from \"commander\";\nimport { EXIT_CODES } from \"./errors.js\";\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(path.resolve(__dirname, \"../package.json\"), \"utf-8\"));\nconst SHELL_VERSION: string = pkg.version;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a prog_name like 'my-tool' to a valid shell identifier '_my_tool'.\n */\nfunction makeFunctionName(progName: string): string {\n return \"_\" + progName.replace(/[^a-zA-Z0-9]/g, \"_\");\n}\n\n/**\n * Shell-safe quoting.\n */\nfunction shellQuote(s: string): string {\n return \"'\" + s.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n\n// ---------------------------------------------------------------------------\n// Completion generators\n// ---------------------------------------------------------------------------\n\nfunction generateBashCompletion(progName: string): string {\n const fn = makeFunctionName(progName);\n const quoted = shellQuote(progName);\n const moduleListCmd =\n `${quoted} list --format json 2>/dev/null` +\n ` | node -e \"process.stdin.on('data',d=>{JSON.parse(d).forEach(m=>console.log(m.id))})\" 2>/dev/null`;\n\n return (\n `${fn}() {\\n` +\n ` local cur prev opts\\n` +\n ` COMPREPLY=()\\n` +\n ` cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\\n` +\n ` prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"\\n` +\n `\\n` +\n ` if [[ \\${COMP_CWORD} -eq 1 ]]; then\\n` +\n ` opts=\"list describe completion man\"\\n` +\n ` COMPREPLY=( $(compgen -W \"\\${opts}\" -- \\${cur}) )\\n` +\n ` return 0\\n` +\n ` fi\\n` +\n `\\n` +\n ` if [[ \"\\${COMP_WORDS[1]}\" == \"exec\" && \\${COMP_CWORD} -eq 2 ]]; then\\n` +\n ` local modules=$(${moduleListCmd})\\n` +\n ` COMPREPLY=( $(compgen -W \"\\${modules}\" -- \\${cur}) )\\n` +\n ` return 0\\n` +\n ` fi\\n` +\n `}\\n` +\n `complete -F ${fn} ${quoted}\\n`\n );\n}\n\nfunction generateZshCompletion(progName: string): string {\n const fn = makeFunctionName(progName);\n const quoted = shellQuote(progName);\n const moduleListCmd =\n `${quoted} list --format json 2>/dev/null` +\n ` | node -e \"process.stdin.on('data',d=>{JSON.parse(d).forEach(m=>console.log(m.id))})\" 2>/dev/null`;\n\n return (\n `#compdef ${progName}\\n` +\n `\\n` +\n `${fn}() {\\n` +\n ` local -a commands\\n` +\n ` commands=(\\n` +\n ` 'list:List available modules'\\n` +\n ` 'describe:Show module metadata and schema'\\n` +\n ` 'completion:Generate shell completion script'\\n` +\n ` 'man:Generate man page'\\n` +\n ` )\\n` +\n `\\n` +\n ` _arguments -C \\\\\\n` +\n ` '1:command:->command' \\\\\\n` +\n ` '*::arg:->args'\\n` +\n `\\n` +\n ` case \"$state\" in\\n` +\n ` command)\\n` +\n ` _describe -t commands '${progName} commands' commands\\n` +\n ` ;;\\n` +\n ` args)\\n` +\n ` case \"\\${words[1]}\" in\\n` +\n ` exec)\\n` +\n ` local modules\\n` +\n ` modules=($(${moduleListCmd}))\\n` +\n ` compadd -a modules\\n` +\n ` ;;\\n` +\n ` esac\\n` +\n ` ;;\\n` +\n ` esac\\n` +\n `}\\n` +\n `\\n` +\n `compdef ${fn} ${quoted}\\n`\n );\n}\n\nfunction generateFishCompletion(progName: string): string {\n const quoted = shellQuote(progName);\n const moduleListCmd =\n `${quoted} list --format json 2>/dev/null` +\n ` | node -e \\\\\"process.stdin.on('data',d=>{JSON.parse(d).forEach(m=>console.log(m.id))})\\\\\" 2>/dev/null`;\n\n return (\n `# Fish completions for ${progName}\\n` +\n `complete -c ${quoted} -n \"__fish_use_subcommand\"` +\n ` -a list -d \"List available modules\"\\n` +\n `complete -c ${quoted} -n \"__fish_use_subcommand\"` +\n ` -a describe -d \"Show module metadata and schema\"\\n` +\n `complete -c ${quoted} -n \"__fish_use_subcommand\"` +\n ` -a completion -d \"Generate shell completion script\"\\n` +\n `complete -c ${quoted} -n \"__fish_use_subcommand\"` +\n ` -a man -d \"Generate man page\"\\n` +\n `\\n` +\n `complete -c ${quoted} -n \"__fish_seen_subcommand_from exec\"` +\n ` -a \"(${moduleListCmd})\"\\n`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Man page generation\n// ---------------------------------------------------------------------------\n\nfunction buildSynopsis(\n command: Command | null,\n progName: string,\n commandName: string,\n): string {\n if (!command) {\n return `\\\\fB${progName} ${commandName}\\\\fR [OPTIONS]`;\n }\n\n const parts = [`\\\\fB${progName} ${commandName}\\\\fR`];\n for (const opt of command.options) {\n const flag = opt.long ?? opt.short ?? \"\";\n if (opt.isBoolean?.()) {\n parts.push(`[${flag}]`);\n } else if (opt.required) {\n const typeName = (opt.argChoices ? \"CHOICE\" : \"VALUE\").toUpperCase();\n parts.push(`${flag} \\\\fI${typeName}\\\\fR`);\n } else {\n const typeName = (opt.argChoices ? \"CHOICE\" : \"VALUE\").toUpperCase();\n parts.push(`[${flag} \\\\fI${typeName}\\\\fR]`);\n }\n }\n\n for (const arg of command.registeredArguments ?? []) {\n const meta = arg.name().toUpperCase();\n if (arg.required) {\n parts.push(`\\\\fI${meta}\\\\fR`);\n } else {\n parts.push(`[\\\\fI${meta}\\\\fR]`);\n }\n }\n\n return parts.join(\" \");\n}\n\nfunction generateManPage(\n commandName: string,\n command: Command | null,\n progName: string,\n version = SHELL_VERSION,\n): string {\n const today = new Date().toISOString().slice(0, 10);\n const title = `${progName}-${commandName}`.toUpperCase();\n const pkgLabel = `${progName} ${version}`;\n const manualLabel = `${progName} Manual`;\n\n const sections: string[] = [];\n sections.push(`.TH \"${title}\" \"1\" \"${today}\" \"${pkgLabel}\" \"${manualLabel}\"`);\n\n sections.push(\".SH NAME\");\n const desc = command?.description() ?? commandName;\n const nameDesc = desc.split(\"\\n\")[0].replace(/\\.$/, \"\");\n sections.push(`${progName}-${commandName} \\\\- ${nameDesc}`);\n\n sections.push(\".SH SYNOPSIS\");\n sections.push(buildSynopsis(command, progName, commandName));\n\n if (command?.description()) {\n sections.push(\".SH DESCRIPTION\");\n sections.push(\n command.description().replace(/\\\\/g, \"\\\\\\\\\").replace(/-/g, \"\\\\-\"),\n );\n }\n\n if (command && command.options.length > 0) {\n sections.push(\".SH OPTIONS\");\n for (const opt of command.options) {\n const flag = [opt.short, opt.long].filter(Boolean).join(\", \");\n sections.push(\".TP\");\n if (opt.isBoolean?.()) {\n sections.push(`\\\\fB${flag}\\\\fR`);\n } else {\n sections.push(`\\\\fB${flag}\\\\fR \\\\fIVALUE\\\\fR`);\n }\n if (opt.description) {\n sections.push(opt.description);\n }\n if (opt.defaultValue !== undefined && !opt.isBoolean?.()) {\n sections.push(`Default: ${opt.defaultValue}.`);\n }\n }\n }\n\n sections.push(\".SH ENVIRONMENT\");\n sections.push(\".TP\");\n sections.push(\"\\\\fBAPCORE_EXTENSIONS_ROOT\\\\fR\");\n sections.push(\n \"Path to the apcore extensions directory. Overrides the default \\\\fI./extensions\\\\fR.\",\n );\n sections.push(\".TP\");\n sections.push(\"\\\\fBAPCORE_CLI_AUTO_APPROVE\\\\fR\");\n sections.push(\n \"Set to \\\\fB1\\\\fR to bypass approval prompts for modules that require human-in-the-loop confirmation.\",\n );\n sections.push(\".TP\");\n sections.push(\"\\\\fBAPCORE_CLI_LOGGING_LEVEL\\\\fR\");\n sections.push(\n \"CLI-specific logging verbosity. One of: DEBUG, INFO, WARNING, ERROR. \" +\n \"Takes priority over \\\\fBAPCORE_LOGGING_LEVEL\\\\fR. Default: WARNING.\",\n );\n sections.push(\".TP\");\n sections.push(\"\\\\fBAPCORE_LOGGING_LEVEL\\\\fR\");\n sections.push(\n \"Global apcore logging verbosity. One of: DEBUG, INFO, WARNING, ERROR. \" +\n \"Used as fallback when \\\\fBAPCORE_CLI_LOGGING_LEVEL\\\\fR is not set. Default: WARNING.\",\n );\n\n sections.push(\".SH EXIT CODES\");\n const exitCodes: [string, string][] = [\n [\"0\", \"Success.\"],\n [\"1\", \"Module execution error.\"],\n [\"2\", \"Invalid CLI input or missing argument.\"],\n [\"44\", \"Module not found, disabled, or failed to load.\"],\n [\"45\", \"Input failed JSON Schema validation.\"],\n [\n \"46\",\n \"Approval denied, timed out, or no interactive terminal available.\",\n ],\n [\n \"47\",\n \"Configuration error (extensions directory not found or unreadable).\",\n ],\n [\"48\", \"Schema contains a circular \\\\fB$ref\\\\fR.\"],\n [\"77\", \"ACL denied — insufficient permissions for this module.\"],\n [\"130\", \"Execution cancelled by user (SIGINT / Ctrl\\\\-C).\"],\n ];\n for (const [code, meaning] of exitCodes) {\n sections.push(`.TP\\n\\\\fB${code}\\\\fR\\n${meaning}`);\n }\n\n sections.push(\".SH SEE ALSO\");\n sections.push(\n [\n `\\\\fB${progName}\\\\fR(1)`,\n `\\\\fB${progName}\\\\-list\\\\fR(1)`,\n `\\\\fB${progName}\\\\-describe\\\\fR(1)`,\n `\\\\fB${progName}\\\\-completion\\\\fR(1)`,\n ].join(\", \"),\n );\n\n return sections.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// registerShellCommands\n// ---------------------------------------------------------------------------\n\n/**\n * Register completion and man commands.\n */\nexport function registerShellCommands(\n cli: Command,\n progName = \"apcore-cli\",\n): void {\n const completionCmd = new Command(\"completion\")\n .description(\n \"Generate a shell completion script and print it to stdout.\",\n )\n .argument(\"<shell>\", \"Shell type: bash, zsh, or fish\")\n .action((shell: string) => {\n const validShells = [\"bash\", \"zsh\", \"fish\"];\n if (!validShells.includes(shell)) {\n process.stderr.write(\n `Error: Unknown shell '${shell}'. Expected: bash, zsh, or fish.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n const resolved = cli.name() || progName;\n const generators: Record<string, () => string> = {\n bash: () => generateBashCompletion(resolved),\n zsh: () => generateZshCompletion(resolved),\n fish: () => generateFishCompletion(resolved),\n };\n process.stdout.write(generators[shell]());\n });\n cli.addCommand(completionCmd);\n\n const manCmd = new Command(\"man\")\n .description(\"Generate a roff man page for COMMAND and print it to stdout.\")\n .argument(\"<command>\", \"Command to generate man page for\")\n .action((commandName: string) => {\n const knownBuiltins = new Set([\"list\", \"describe\", \"completion\", \"man\"]);\n const cmd = cli.commands.find((c) => c.name() === commandName) ?? null;\n\n if (!cmd && !knownBuiltins.has(commandName)) {\n process.stderr.write(\n `Error: Unknown command '${commandName}'.\\n`,\n );\n process.exit(EXIT_CODES.INVALID_CLI_INPUT);\n }\n\n const resolved = cli.name() || progName;\n const roff = generateManPage(commandName, cmd, resolved);\n process.stdout.write(roff);\n });\n cli.addCommand(manCmd);\n}\n"],"mappings":";;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;;ACkGO,SAAS,iBAAiBA,QAA0B;AACzD,MAAIA,kBAAiB,sBAAsB;AACzC,WAAO,WAAW;AAAA,EACpB;AACA,MAAIA,kBAAiB,qBAAqB;AACxC,WAAO,WAAW;AAAA,EACpB;AACA,MAAIA,kBAAiB,qBAAqB;AACxC,WAAO,WAAW;AAAA,EACpB;AACA,MAAIA,kBAAiB,uBAAuB;AAC1C,WAAO,WAAW;AAAA,EACpB;AACA,MAAIA,kBAAiB,uBAAuB;AAC1C,WAAO,WAAW;AAAA,EACpB;AACA,MAAIA,kBAAiB,qBAAqB;AACxC,WAAO,WAAW;AAAA,EACpB;AACA,MAAIA,kBAAiB,sBAAsB;AACzC,WAAO,WAAW;AAAA,EACpB;AAGA,MAAIA,kBAAiB,OAAO;AAC1B,UAAM,OAAQA,OAA6C;AAC3D,UAAM,UAAoC;AAAA,MACxC,kBAAkB,WAAW;AAAA,MAC7B,mBAAmB,WAAW;AAAA,MAC9B,iBAAiB,WAAW;AAAA,MAC5B,yBAAyB,WAAW;AAAA,MACp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AQ;AAAA,IAC7C;AACA,YAAQ,OAAO,MAAM,WAAW,KAAK,EAAE,CAAC;AAAA,EAC1C,CAAC;AACH,MAAI,WAAW,aAAa;AAE5B,QAAM,SAAS,IAAIA,SAAQ,KAAK,EAC7B,YAAY,8DAA8D,EAC1E,SAAS,aAAa,kCAAkC,EACxD,OAAO,CAAC,gBAAwB;AAC/B,UAAM,gBAAgB,oBAAI,IAAI,CAAC,QAAQ,YAAY,cAAc,KAAK,CAAC;AACvE,UAAM,MAAM,IAAI,SAAS,KAAK,CAAC,MAAM,EAAE,KAAK,MAAM,WAAW,KAAK;AAElE,QAAI,CAAC,OAAO,CAAC,cAAc,IAAI,WAAW,GAAG;AAC3C,cAAQ,OAAO;AAAA,QACb,2BAA2B,WAAW;AAAA;AAAA,MACxC;AACA,cAAQ,KAAK,WAAW,iBAAiB;AAAA,IAC3C;AAEA,UAAM,WAAW,IAAI,KAAK,KAAK;AAC/B,UAAM,OAAO,gBAAgB,aAAa,KAAK,QAAQ;AACvD,YAAQ,OAAO,MAAM,IAAI;AAAA,EAC3B,CAAC;AACH,MAAI,WAAW,MAAM;AACvB;;;AV5SA;AAiBA;","names":["error","path","crypto","os","hostname","fs","os","path","fileURLToPath","path","resolve","__dirname","fileURLToPath","error","Sandbox","getAuditLogger","resolve","fs","Command","Command","readFileSync","fileURLToPath","path","Command","__dirname","pkg"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apcore-cli",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "CLI wrapper for the apcore core SDK — exposes apcore modules as CLI commands",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",