@documentation-robotics/cli 0.1.12 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -1
- package/dist/analyzers/verify-engine.js +22 -19
- package/dist/analyzers/verify-engine.js.map +2 -2
- package/dist/cli.js +101 -27
- package/dist/cli.js.map +3 -3
- package/dist/coding-agents/agents/claude-code.js +3 -1
- package/dist/coding-agents/agents/claude-code.js.map +2 -2
- package/dist/coding-agents/claude-code-client.js +2 -1
- package/dist/coding-agents/claude-code-client.js.map +2 -2
- package/dist/coding-agents/copilot-client.js +17 -12
- package/dist/coding-agents/copilot-client.js.map +2 -2
- package/dist/coding-agents/default-permissions.js +122 -0
- package/dist/coding-agents/default-permissions.js.map +7 -0
- package/dist/commands/add.js +10 -6
- package/dist/commands/add.js.map +2 -2
- package/dist/commands/analyzer.js +18 -10
- package/dist/commands/analyzer.js.map +2 -2
- package/dist/commands/audit.js +6 -6
- package/dist/commands/audit.js.map +2 -2
- package/dist/commands/changeset.js +238 -145
- package/dist/commands/changeset.js.map +2 -2
- package/dist/commands/delete.js +45 -18
- package/dist/commands/delete.js.map +3 -3
- package/dist/commands/element.js +3 -2
- package/dist/commands/element.js.map +2 -2
- package/dist/commands/farm.js +657 -0
- package/dist/commands/farm.js.map +7 -0
- package/dist/commands/init.js +11 -1
- package/dist/commands/init.js.map +2 -2
- package/dist/commands/mcp.js +107 -0
- package/dist/commands/mcp.js.map +7 -0
- package/dist/commands/relationship.js +53 -30
- package/dist/commands/relationship.js.map +2 -2
- package/dist/commands/reports.js +1 -1
- package/dist/commands/reports.js.map +2 -2
- package/dist/commands/update.js +19 -6
- package/dist/commands/update.js.map +2 -2
- package/dist/commands/validate.js +41 -3
- package/dist/commands/validate.js.map +2 -2
- package/dist/commands/version.js +2 -2
- package/dist/commands/version.js.map +2 -2
- package/dist/config.js +83 -0
- package/dist/config.js.map +7 -0
- package/dist/core/annotation-store.js +138 -0
- package/dist/core/annotation-store.js.map +7 -0
- package/dist/core/farm-manifest.js +134 -0
- package/dist/core/farm-manifest.js.map +7 -0
- package/dist/core/farm-sync-engine.js +346 -0
- package/dist/core/farm-sync-engine.js.map +7 -0
- package/dist/core/farm-sync-state.js +159 -0
- package/dist/core/farm-sync-state.js.map +7 -0
- package/dist/core/manifest.js +6 -3
- package/dist/core/manifest.js.map +2 -2
- package/dist/core/migration-registry.js +55 -1
- package/dist/core/migration-registry.js.map +2 -2
- package/dist/core/model.js +177 -16
- package/dist/core/model.js.map +3 -3
- package/dist/core/virtual-projection.js +1 -0
- package/dist/core/virtual-projection.js.map +2 -2
- package/dist/generated/node-types.js +1 -1
- package/dist/generated/node-types.js.map +2 -2
- package/dist/generated/relationship-index.js +45 -9
- package/dist/generated/relationship-index.js.map +2 -2
- package/dist/integrations/claude_code/docs/MCP_SERVER.md +55 -0
- package/dist/integrations/claude_code/docs/README.md +4 -0
- package/dist/mcp/api-key-manager.js +98 -0
- package/dist/mcp/api-key-manager.js.map +7 -0
- package/dist/mcp/http-transport.js +176 -0
- package/dist/mcp/http-transport.js.map +7 -0
- package/dist/mcp/resource-registry.js +97 -0
- package/dist/mcp/resource-registry.js.map +7 -0
- package/dist/mcp/tool-registry.js +44 -0
- package/dist/mcp/tool-registry.js.map +7 -0
- package/dist/mcp/tools/annotation-create.js +39 -0
- package/dist/mcp/tools/annotation-create.js.map +7 -0
- package/dist/mcp/tools/annotation-delete.js +29 -0
- package/dist/mcp/tools/annotation-delete.js.map +7 -0
- package/dist/mcp/tools/annotation-get.js +29 -0
- package/dist/mcp/tools/annotation-get.js.map +7 -0
- package/dist/mcp/tools/annotation-list.js +24 -0
- package/dist/mcp/tools/annotation-list.js.map +7 -0
- package/dist/mcp/tools/annotation-reply.js +34 -0
- package/dist/mcp/tools/annotation-reply.js.map +7 -0
- package/dist/mcp/tools/annotation-shared.js +10 -0
- package/dist/mcp/tools/annotation-shared.js.map +7 -0
- package/dist/mcp/tools/annotation-update.js +39 -0
- package/dist/mcp/tools/annotation-update.js.map +7 -0
- package/dist/mcp/tools/changeset-list.js +33 -0
- package/dist/mcp/tools/changeset-list.js.map +7 -0
- package/dist/mcp/tools/changeset-show.js +39 -0
- package/dist/mcp/tools/changeset-show.js.map +7 -0
- package/dist/mcp/tools/chat-launch.js +50 -0
- package/dist/mcp/tools/chat-launch.js.map +7 -0
- package/dist/mcp/tools/chat-status.js +26 -0
- package/dist/mcp/tools/chat-status.js.map +7 -0
- package/dist/mcp/tools/index.js +47 -0
- package/dist/mcp/tools/index.js.map +7 -0
- package/dist/mcp/tools/model-add.js +106 -0
- package/dist/mcp/tools/model-add.js.map +7 -0
- package/dist/mcp/tools/model-delete.js +99 -0
- package/dist/mcp/tools/model-delete.js.map +7 -0
- package/dist/mcp/tools/model-export.js +72 -0
- package/dist/mcp/tools/model-export.js.map +7 -0
- package/dist/mcp/tools/model-info.js +51 -0
- package/dist/mcp/tools/model-info.js.map +7 -0
- package/dist/mcp/tools/model-list.js +53 -0
- package/dist/mcp/tools/model-list.js.map +7 -0
- package/dist/mcp/tools/model-reload.js +34 -0
- package/dist/mcp/tools/model-reload.js.map +7 -0
- package/dist/mcp/tools/model-search.js +88 -0
- package/dist/mcp/tools/model-search.js.map +7 -0
- package/dist/mcp/tools/model-show.js +41 -0
- package/dist/mcp/tools/model-show.js.map +7 -0
- package/dist/mcp/tools/model-stats.js +22 -0
- package/dist/mcp/tools/model-stats.js.map +7 -0
- package/dist/mcp/tools/model-trace.js +55 -0
- package/dist/mcp/tools/model-trace.js.map +7 -0
- package/dist/mcp/tools/model-update.js +105 -0
- package/dist/mcp/tools/model-update.js.map +7 -0
- package/dist/mcp/tools/model-validate.js +78 -0
- package/dist/mcp/tools/model-validate.js.map +7 -0
- package/dist/mcp/tools/shared.js +103 -0
- package/dist/mcp/tools/shared.js.map +7 -0
- package/dist/reports/model-layer-report-generator.js +5 -3
- package/dist/reports/model-layer-report-generator.js.map +2 -2
- package/dist/reports/model-readme-generator.js +116 -0
- package/dist/reports/model-readme-generator.js.map +7 -0
- package/dist/reports/model-report-data.js +37 -1
- package/dist/reports/model-report-data.js.map +2 -2
- package/dist/reports/model-report-orchestrator.js +29 -6
- package/dist/reports/model-report-orchestrator.js.map +2 -2
- package/dist/reports/model-report-utils.js +9 -0
- package/dist/reports/model-report-utils.js.map +7 -0
- package/dist/schemas/bundled/analyzers/cbm.json +2 -2
- package/dist/schemas/bundled/analyzers/manifest.json +2 -2
- package/dist/schemas/bundled/api.json +1 -1
- package/dist/schemas/bundled/apm.json +1 -1
- package/dist/schemas/bundled/application.json +12 -1
- package/dist/schemas/bundled/base.json +1 -1
- package/dist/schemas/bundled/business.json +1 -1
- package/dist/schemas/bundled/data-model.json +38 -2
- package/dist/schemas/bundled/data-store.json +1 -1
- package/dist/schemas/bundled/manifest.json +4 -4
- package/dist/schemas/bundled/motivation.json +1 -1
- package/dist/schemas/bundled/navigation.json +1 -1
- package/dist/schemas/bundled/product.json +1 -1
- package/dist/schemas/bundled/security.json +1 -1
- package/dist/schemas/bundled/technology.json +1 -1
- package/dist/schemas/bundled/testing.json +1 -1
- package/dist/schemas/bundled/ux.json +1 -1
- package/dist/server/server.js +45 -7
- package/dist/server/server.js.map +2 -2
- package/dist/telemetry/config.js +2 -40
- package/dist/telemetry/config.js.map +2 -2
- package/dist/telemetry/index.js +1 -1
- package/dist/types/index.js.map +2 -2
- package/dist/utils/ansi-suppressor.js +25 -0
- package/dist/utils/ansi-suppressor.js.map +7 -0
- package/dist/utils/color-utils.js +34 -0
- package/dist/utils/color-utils.js.map +7 -0
- package/dist/utils/element-reference-shape.js +15 -1
- package/dist/utils/element-reference-shape.js.map +3 -3
- package/dist/utils/errors.js +69 -10
- package/dist/utils/errors.js.map +2 -2
- package/dist/utils/globals.js +17 -1
- package/dist/utils/globals.js.map +2 -2
- package/dist/utils/project-paths.js +24 -2
- package/dist/utils/project-paths.js.map +2 -2
- package/dist/utils/reference-path-parser.js +49 -0
- package/dist/utils/reference-path-parser.js.map +7 -0
- package/dist/utils/source-reference.js +5 -0
- package/dist/utils/source-reference.js.map +2 -2
- package/dist/utils/spec-version.js +10 -2
- package/dist/utils/spec-version.js.map +2 -2
- package/dist/validators/composed-reference-validator.js +262 -0
- package/dist/validators/composed-reference-validator.js.map +7 -0
- package/dist/validators/reference-validator.js +59 -8
- package/dist/validators/reference-validator.js.map +3 -3
- package/dist/validators/relationship-schema-validator.js +30 -2
- package/dist/validators/relationship-schema-validator.js.map +3 -3
- package/dist/viewer/README.md +6 -6
- package/dist/viewer/assets/main-B7AOQXXX.js +81 -0
- package/dist/viewer/assets/main-vdrFrG7q.css +1 -0
- package/dist/viewer/index.html +2 -2
- package/dist/viewer/manifest.json +10 -10
- package/dist/viewer/version.json +1 -1
- package/package.json +6 -3
- package/dist/viewer/assets/main-BRPZyc36.css +0 -1
- package/dist/viewer/assets/main-BrpLargo.js +0 -81
package/dist/cli.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/cli.ts"],
|
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n\n/**\n * Documentation Robotics CLI - Bun Implementation\n * Entry point for the command-line interface\n *\n * Instrumented with OpenTelemetry to create root spans for command execution.\n * Telemetry is controlled by the TELEMETRY_ENABLED build-time constant.\n */\n\nimport { Command, CommanderError } from \"commander\";\nimport { setGlobalOptions } from \"./utils/globals.js\";\nimport { initCommand } from \"./commands/init.js\";\nimport { addCommand } from \"./commands/add.js\";\nimport { updateCommand } from \"./commands/update.js\";\nimport { deleteCommand } from \"./commands/delete.js\";\nimport { showCommand } from \"./commands/show.js\";\nimport { listCommand } from \"./commands/list.js\";\nimport { searchCommand } from \"./commands/search.js\";\nimport { validateCommand } from \"./commands/validate.js\";\nimport { infoCommand } from \"./commands/info.js\";\nimport { relationshipCommands } from \"./commands/relationship.js\";\nimport { elementCommands } from \"./commands/element.js\";\nimport { schemaCommands } from \"./commands/schema.js\";\nimport { catalogCommands } from \"./commands/catalog.js\";\nimport { docsCommands } from \"./commands/docs.js\";\nimport { traceCommand } from \"./commands/trace.js\";\nimport { exportCommand } from \"./commands/export.js\";\nimport { importCommand } from \"./commands/import.js\";\nimport { chatCommand } from \"./commands/chat.js\";\nimport { upgradeCommand } from \"./commands/upgrade.js\";\nimport { conformanceCommand } from \"./commands/conformance.js\";\nimport { changesetCommands } from \"./commands/changeset.js\";\nimport { claudeCommands } from \"./commands/claude.js\";\nimport { copilotCommands } from \"./commands/copilot.js\";\nimport { analyzerCommands } from \"./commands/analyzer.js\";\nimport { versionCommand } from \"./commands/version.js\";\nimport { statsCommand } from \"./commands/stats.js\";\nimport { reportCommand } from \"./commands/report.js\";\nimport { reportsCommands } from \"./commands/reports.js\";\nimport { auditCommand } from \"./commands/audit.js\";\nimport { auditDiffCommand } from \"./commands/audit-diff.js\";\nimport { auditSnapshotsCommand } from \"./commands/audit-snapshots.js\";\nimport { repairAttributeCollisionCommand } from \"./commands/repair.js\";\nimport { initTelemetry, startActiveSpan, shutdownTelemetry } from \"./telemetry/index.js\";\nimport { installConsoleInterceptor } from \"./telemetry/console-interceptor.js\";\nimport { getErrorMessage } from \"./utils/errors.js\";\n\n// Declare TELEMETRY_ENABLED as a build-time constant (substituted by esbuild)\n// Provide runtime fallback when not running through esbuild\ndeclare const TELEMETRY_ENABLED: boolean;\nconst isTelemetryEnabled = typeof TELEMETRY_ENABLED !== \"undefined\" ? TELEMETRY_ENABLED : false;\n\n// Commands that require console interceptor for telemetry logging\nconst CONSOLE_LOGGING_COMMANDS = new Set(['chat', 'validate', 'import', 'export']);\n\n/**\n * Extract exit code from an error object.\n * Handles CLIError instances and duck-typed objects with exitCode property.\n */\nasync function extractExitCode(error: unknown): Promise<number> {\n const { CLIError } = await import(\"./utils/errors.js\");\n\n if (error instanceof CLIError) {\n return error.exitCode;\n }\n\n // Commander's own errors (--help, unknown commands, etc.) carry exitCode as\n // expected control flow \u2014 handle them directly without duck-typing.\n if (error instanceof CommanderError) {\n return error.exitCode;\n }\n\n // Fallback for duck-typing (handles bundling/module issues)\n if (error && typeof error === \"object\" && \"exitCode\" in error) {\n const errorObj = error as any;\n if (typeof errorObj.exitCode === \"number\") {\n // Validate this looks like a CLIError before accepting\n if (errorObj.name === \"CLIError\" || errorObj.message) {\n if (process.argv.includes(\"--debug\")) {\n console.warn(\n \"[DEBUG] Using duck-typed error object as fallback - this may indicate a module loading issue\"\n );\n }\n return errorObj.exitCode;\n }\n }\n }\n\n return 1;\n}\n\n// Declare build-time constant (substituted by esbuild)\ndeclare const CLI_VERSION: string;\nconst cliVersion = typeof CLI_VERSION !== \"undefined\" ? CLI_VERSION : \"0.1.3\";\n\nconst program = new Command();\n\n// Handle --version and -V flags by redirecting to version command\n// This ensures they go through the telemetry wrapper\nif (process.argv.includes(\"--version\") || process.argv.includes(\"-V\")) {\n process.argv = [\"node\", \"dr\", \"version\"];\n}\n\nprogram\n .name(\"dr\")\n .description(\"Documentation Robotics CLI - Architecture Model Management\")\n .option(\"-v, --verbose\", \"Enable verbose output\")\n .option(\"--debug\", \"Enable debug mode\")\n .exitOverride() // Prevent Commander from calling process.exit() - we handle exit ourselves\n .showSuggestionAfterError() // \"Did you mean X?\" on unknown commands/options\n .hook(\"preAction\", async (thisCommand) => {\n // Set up global state (verbose/debug flags)\n const options = thisCommand.opts();\n setGlobalOptions({\n verbose: options.verbose as boolean | undefined,\n debug: options.debug as boolean | undefined,\n });\n });\n\n// Model commands\nprogram\n .command(\"init [name]\")\n .description(\"Initialize a new architecture model\")\n .option(\"--name <name>\", \"Model name (overrides positional argument)\")\n .option(\"--author <author>\", \"Model author\")\n .option(\"--description <desc>\", \"Model description\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr init\n $ dr init claudetoreum\n $ dr init \"Enterprise Architecture\" --author \"Team A\"\n $ dr init --name \"My Project\" --description \"13-layer federated model\"`\n )\n .action((name, options) => initCommand({ ...options, name: options.name || name }));\n\nprogram\n .command(\"add <layer> <type> <name>\")\n .description(\"Add an element to a layer\")\n .option(\"--name <name>\", \"Element display name (defaults to the name argument)\")\n .option(\"--description <desc>\", \"Element description\")\n .option(\"--attributes <json>\", \"Element type-specific attributes as JSON object\")\n .option(\"--source-file <path>\", \"Source file path (relative from repository root)\")\n .option(\"--source-symbol <name>\", \"Symbol name (class, function, variable) in source file\")\n .option(\"--source-provenance <type>\", \"Provenance type: extracted, manual, inferred, generated\")\n .option(\"--source-repo-remote <url>\", \"Git remote URL for repository context\")\n .option(\"--source-repo-commit <sha>\", \"Git commit SHA (40 hex characters) for repository context\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr add business service \"Customer Management\"\n $ dr add api operation \"Create Customer\" --attributes '{\"operationId\":\"createCustomer\",\"summary\":\"Create a customer\",\"tags\":\"customers\"}'\n $ dr add application component \"Customer API\" --description \"REST API for customer operations\"\n $ dr add security policy \"Auth Validator\" --source-file \"src/auth/validator.ts\" --source-symbol \"validateToken\" --source-provenance \"extracted\"\n\nNote: Element IDs are generated automatically in format {layer}.{type}.{kebab-name}`\n )\n .action(addCommand);\n\nprogram\n .command(\"update <id>\")\n .description(\"Update an element\")\n .option(\"--name <name>\", \"New element name\")\n .option(\"--description <desc>\", \"New description\")\n .option(\"--type <new-type>\", \"Change element type (must be valid for the element's layer; incompatible attributes must be cleaned up manually)\")\n .option(\"--attributes <json>\", \"Updated type-specific attributes (JSON)\")\n .option(\"--source-file <path>\", \"Source file path (relative from repository root)\")\n .option(\"--source-symbol <name>\", \"Symbol name (class, function, variable) in source file\")\n .option(\"--source-provenance <type>\", \"Provenance type: extracted, manual, inferred, generated\")\n .option(\"--source-repo-remote <url>\", \"Git remote URL for repository context\")\n .option(\"--source-repo-commit <sha>\", \"Git commit SHA (40 hex characters) for repository context\")\n .option(\"--clear-source-reference\", \"Remove source reference from element\")\n .addHelpText(\n \"after\",\n `\nNote: Changes are written immediately to model files.\nTo track changes for review, activate a changeset first:\n $ dr changeset activate my-changeset\n\nExamples:\n $ dr update api-endpoint-create-customer --name \"Create Customer (v2)\"\n $ dr update business-service-order --description \"Updated description\"\n $ dr update application-applicationfunction-process-orders --type applicationservice\n $ dr update security-policy-auth --source-file \"src/auth/policy.ts\" --source-provenance \"extracted\"`\n )\n .action(updateCommand);\n\nprogram\n .command(\"delete <id>\")\n .description(\"Delete an element\")\n .option(\"--force\", \"Skip dependency checks (confirmation is also skipped in non-TTY environments)\")\n .option(\"--cascade\", \"Remove dependent elements automatically\")\n .option(\"--dry-run\", \"Show what would be removed without actually removing\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr delete api-endpoint-old-endpoint\n $ dr delete api-endpoint-old-endpoint --force\n $ dr delete api-endpoint-old-endpoint --cascade\n $ dr delete api-endpoint-old-endpoint --dry-run\n $ dr delete api-endpoint-old-endpoint --cascade --dry-run`\n )\n .action(deleteCommand);\n\nprogram\n .command(\"show <id>\")\n .description(\"Display element details\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr show api-endpoint-create-customer\n $ dr show business-service-order-mgmt`\n )\n .action((id, options) => showCommand(id, options));\n\nprogram\n .command(\"list [layer]\")\n .description(\"List elements in a layer (or all layers if omitted)\")\n .option(\"--type <type>\", \"Filter by element type\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr list\n $ dr list api\n $ dr list business --type businessservice\n $ dr list api --json\n $ dr list --json`\n )\n .action(listCommand);\n\nprogram\n .command(\"search <query>\")\n .description(\"Search for elements by name or ID\")\n .option(\"--layer <layer>\", \"Limit search to specific layer\")\n .option(\"--type <type>\", \"Filter by element type\")\n .option(\n \"--source-file <path>\",\n \"Find elements referencing a source file (takes precedence over pattern matching)\"\n )\n .option(\"--json\", \"Output as JSON\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr search customer\n $ dr search \"order processing\" --layer business\n $ dr search create-* --type endpoint\n $ dr search \"\" --source-file src/api/customer.ts`\n )\n .action(searchCommand);\n\nprogram\n .command(\"validate\")\n .description(\"Validate the architecture model\")\n .option(\"--layers <layers...>\", \"Specific layers to validate\")\n .option(\"--strict\", \"Treat warnings as errors\")\n .option(\"--verbose\", \"Show detailed validation output with relationship breakdown\")\n .option(\"--quiet\", \"Show minimal output\")\n .option(\"--output <path>\", \"Export validation report to file (JSON or Markdown)\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .option(\"--orphans\", \"Show only orphaned elements grouped by layer with relationship suggestions\")\n .option(\"--all\", \"Run all validations (default behavior)\")\n .option(\"--markdown\", \"Validate markdown structure\")\n .option(\"--schemas\", \"Validate JSON schemas\")\n .option(\"--schema\", \"Validate JSON schemas (alias for --schemas)\")\n .option(\"--relationships\", \"Validate relationships\")\n .option(\"--structure\", \"Validate documentation structure\")\n .option(\"--naming\", \"Validate naming conventions\")\n .option(\"--references\", \"Validate cross-layer references\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr validate\n $ dr validate --all --strict\n $ dr validate --verbose\n $ dr validate --quiet\n $ dr validate --output report.json\n $ dr validate --output report.md\n $ dr validate --schemas\n $ dr validate --relationships\n $ dr validate --layers business api\n $ dr validate --orphans\n $ dr validate --orphans --output orphans.json`\n )\n .action(validateCommand);\n\nprogram\n .command(\"export <format>\")\n .description(\"Export the architecture model to various formats\")\n .option(\"--output <path>\", \"Output file path (default: print to stdout)\")\n .option(\"--layers <layers...>\", \"Specific layers to export\")\n .option(\"--model <path>\", \"Path to model root directory or manifest.yaml file\")\n .option(\"--include-sources\", \"Include source file paths in PlantUML diagrams as notes\")\n .addHelpText(\n \"after\",\n `\nSupported formats:\n archimate Export to ArchiMate XML (layers 1, 2, 5, 6)\n openapi Export to OpenAPI 3.0 specification (layer 7)\n jsonschema Export to JSON Schema (layer 8)\n plantuml Export to PlantUML diagram\n graphml Export to GraphML (graph visualization)\n markdown Export to Markdown documentation\n\nExamples:\n $ dr export archimate --output model.xml\n $ dr export openapi --layers api\n $ dr export plantuml --include-sources --output diagram.puml\n $ dr export markdown --output docs/architecture.md`\n )\n .action(async (format, options) => {\n await exportCommand({\n format,\n output: options.output,\n layers: options.layers,\n model: options.model,\n includeSources: options.includeSources,\n });\n });\n\nprogram\n .command(\"import <format>\")\n .description(\"Import architecture model from various formats\")\n .option(\"--input <path>\", \"Input file path (required)\", undefined)\n .option(\"--model <path>\", \"Path to model root directory or manifest.yaml file\")\n .option(\n \"--merge-strategy <strategy>\",\n \"How to handle existing elements: add, update, skip (default: add)\"\n )\n .addHelpText(\n \"after\",\n `\nSupported formats:\n archimate Import from ArchiMate XML (layers 1, 2, 5, 6)\n openapi Import from OpenAPI 3.0 specification (layer 7)\n\nExamples:\n $ dr import archimate --input model.xml\n $ dr import openapi --input api.json --merge-strategy add\n $ dr import archimate --input model.xml --model ./myproject`\n )\n .action(async (format, options) => {\n if (!options.input) {\n console.error(\"Error: --input path is required\");\n process.exit(1);\n }\n await importCommand({\n format,\n input: options.input,\n model: options.model,\n mergeStrategy: options.mergeStrategy as \"add\" | \"update\" | \"skip\" | undefined,\n });\n });\n\nprogram\n .command(\"info\")\n .description(\"Show model information\")\n .option(\"--layer <layer>\", \"Show specific layer details\")\n .option(\"--verbose\", \"Show detailed breakdown by element type\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr info\n $ dr info --layer business\n $ dr info --layer api --verbose`\n )\n .action(infoCommand);\n\nprogram\n .command(\"stats\")\n .description(\"Display model statistics and health metrics\")\n .option(\"--model <path>\", \"Path to the model directory\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown, compact\")\n .option(\"--output <path>\", \"Output file path (auto-detects format from extension)\")\n .option(\"--compact\", \"Show compact one-line summary\")\n .option(\"--verbose\", \"Show detailed information\")\n .addHelpText(\n \"after\",\n `\nOutput formats:\n text Full formatted statistics (default)\n json JSON output for automation\n markdown Markdown report format\n compact Single-line summary\n\nExamples:\n $ dr stats # Show full statistics\n $ dr stats --compact # Show one-line summary\n $ dr stats --format json # Output as JSON\n $ dr stats --output stats.md # Save as markdown file\n $ dr stats --output stats.json # Save as JSON file\n $ dr stats --verbose # Show detailed information`\n )\n .action((options) => statsCommand(options));\n\nprogram\n .command(\"report\")\n .description(\"Generate comprehensive architecture reports\")\n .option(\"--model <path>\", \"Path to the model directory\")\n .option(\"--type <type>\", \"Report type: comprehensive (default), statistics, relationships, data-model, quality\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown\")\n .option(\"--output <path>\", \"Output file path (auto-detects format from extension)\")\n .option(\"--verbose\", \"Show detailed information\")\n .option(\"--include-data-model\", \"Include data model analysis (default: true)\")\n .option(\"--include-quality\", \"Include quality metrics (default: true)\")\n .addHelpText(\n \"after\",\n `\nReport types:\n comprehensive Full report with statistics, relationships, and data model (default)\n statistics Statistics and quality metrics\n relationships Relationship analysis and classification\n data-model Layer 8 data model analysis\n quality Quality metrics and recommendations\n\nOutput formats:\n text Full formatted report (default)\n json JSON output for automation\n markdown Markdown report format\n\nExamples:\n $ dr report # Show comprehensive report\n $ dr report --type relationships # Show relationship analysis\n $ dr report --format json # Output as JSON\n $ dr report --output report.md # Save as markdown file\n $ dr report --type data-model --output dm.md # Data model report as markdown\n $ dr report --verbose # Show detailed information`\n )\n .action((options) => reportCommand(options));\n\n// Reports subcommands (managed layer report files)\nconst reportsGroup = program.command(\"reports\").description(\"Manage architecture layer reports\");\nreportsCommands(reportsGroup);\n\n// Audit command - Relationship analysis\nprogram\n .command(\"audit [layer]\")\n .description(\"Analyze relationship coverage, gaps, duplicates, and balance\")\n .option(\"--type <type>\", \"Audit type: relationships (default), nodes, all\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown\")\n .option(\"--output <path>\", \"Output file path (auto-detects format from extension)\")\n .option(\"--verbose\", \"Show detailed analysis\")\n .option(\"--save-snapshot\", \"Save audit report as snapshot for differential analysis\")\n .addHelpText(\n \"after\",\n `\nAudit types:\n relationships Relationship coverage, gaps, duplicates, balance (default)\n nodes Node type usage distribution across model layers\n all Both relationship and node audits\n\nOutput formats:\n text Full formatted audit report (default)\n json JSON output for automation\n markdown Markdown audit report format\n\nExamples:\n $ dr audit # Full relationship audit of all layers\n $ dr audit security # Audit security layer only\n $ dr audit --type nodes # Node type distribution audit\n $ dr audit --type all # Combined relationship + node audit\n $ dr audit --format json # Output as JSON\n $ dr audit --output audit.md # Save as markdown file\n $ dr audit --verbose # Show detailed analysis\n $ dr audit --save-snapshot # Save snapshot for later comparison\n $ dr audit api --output api-audit.json # API layer audit as JSON`\n )\n .action((layer, options) =>\n auditCommand({ ...options, layer, verbose: options.verbose ?? program.opts().verbose }));\n\n// Audit diff command - Compare snapshots\nprogram\n .command(\"audit:diff\")\n .description(\"Compare before/after audit snapshots\")\n .option(\"--before <id>\", \"Before snapshot ID or timestamp\")\n .option(\"--after <id>\", \"After snapshot ID or timestamp\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown\")\n .option(\"--output <path>\", \"Output file path\")\n .option(\"--verbose\", \"Show detailed comparison\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr audit:diff # Compare latest two snapshots\n $ dr audit:diff --before 20260220-100000 --after 20260220-150000\n $ dr audit:diff --format markdown --output diff.md\n $ dr audit:diff --verbose # Show detailed changes`\n )\n .action((options) => auditDiffCommand(options));\n\n// Audit snapshots command - Manage snapshots\nprogram\n .command(\"audit:snapshots <action>\")\n .description(\"Manage audit snapshots (list, delete, clear)\")\n .option(\"--id <id>\", \"Snapshot ID (for delete action)\")\n .addHelpText(\n \"after\",\n `\nActions:\n list List all available snapshots\n delete Delete a specific snapshot (requires --id)\n clear Delete all snapshots\n\nExamples:\n $ dr audit:snapshots list\n $ dr audit:snapshots delete --id 20260220-100000\n $ dr audit:snapshots clear`\n )\n .action((action, options) => auditSnapshotsCommand({ ...options, action }));\n\n// Repair command - Detect and recover data lost to fixed data-integrity bugs\nprogram\n .command(\"repair:attribute-collision\")\n .description(\n 'Find and best-effort-recover model data lost to a fixed bug where saveLayer() stripped \"source\"/\"x-source-reference\" attributes from every element, even when a node type\\'s schema declared one as a real (sometimes required) attribute'\n )\n .option(\"--apply\", \"Restore recoverable values found in changeset history (default: report only)\")\n .option(\"--format <format>\", \"Output format: text (default), json\")\n .option(\"--output <path>\", \"Write the report to a file instead of stdout\")\n .addHelpText(\n \"after\",\n `\nThis repairs damage from a fixed bug in Model.saveLayer(): a hardcoded, type-blind \"internal\nfields\" blocklist unconditionally stripped any attribute literally named \"source\" or\n\"x-source-reference\" from every element's attributes before writing YAML, regardless of whether\nthe element's own schema declared it as a real domain attribute. 41 of 191 node schemas across 8\nlayers do (3 mark it required, meaning affected elements fail validation today).\n\nRecovery is best-effort: values can only be restored if they still exist in changeset history\n(committing a changeset does not delete it). Elements with no recoverable value are always\nreported, never fabricated \u2014 you'll need to re-supply those manually with\n\"dr update <id> --attributes '{...}'\".\n\nExamples:\n $ dr repair:attribute-collision # Report only \u2014 no changes made\n $ dr repair:attribute-collision --apply # Restore every recoverable value\n $ dr repair:attribute-collision --format json --output report.json`\n )\n .action((options) => repairAttributeCollisionCommand(options));\n\n// Relationship subcommands\nconst relationshipGroup = program.command(\"relationship\").description(\"Relationship operations\");\nrelationshipCommands(relationshipGroup);\n\n// Element subcommands\nconst elementGroup = program.command(\"element\").description(\"Element operations\");\nelementCommands(elementGroup);\n\n// Schema introspection subcommands\nschemaCommands(program);\n\n// Catalog subcommands (modern relationship catalog)\ncatalogCommands(program);\n\n// Documentation subcommands (schema-driven generation)\ndocsCommands(program);\n\n// Dependency analysis commands\nprogram\n .command(\"trace <elementId>\")\n .description(\"Trace dependencies for an element\")\n .option(\n \"--direction <dir>\",\n \"Trace direction: up (dependencies), down (dependents), both (default)\"\n )\n .option(\"--depth <num>\", \"Maximum traversal depth\")\n .option(\"--metrics\", \"Show graph and element metrics\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr trace api-endpoint-create-customer\n $ dr trace business-service-order --direction down --metrics\n $ dr trace application-component-api --depth 3`\n )\n .action(async (elementId, options) => {\n await traceCommand(elementId, {\n direction: options.direction as \"up\" | \"down\" | \"both\" | undefined,\n depth: options.depth ? parseInt(options.depth) : undefined,\n showMetrics: options.metrics,\n model: options.model,\n });\n });\n\nprogram\n .command(\"visualize\")\n .description(\"Launch visualization server with WebSocket support\")\n .option(\"--port <num>\", \"Server port (default: 8080)\")\n .option(\"--no-browser\", \"Do not auto-open browser\")\n .option(\"--no-auth\", \"Disable authentication (enabled by default)\")\n .option(\"--token <token>\", \"Custom auth token (auto-generated by default)\")\n .option(\"--with-danger\", \"Enable dangerous mode for chat (skip permissions)\")\n .option(\n \"--viewer-path <path>\",\n \"Path to custom viewer build (e.g., ./dist/embedded/dr-viewer-bundle)\"\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr visualize\n $ dr visualize --port 3000\n $ dr visualize --no-browser\n $ dr visualize --no-auth\n $ dr visualize --token my-secret-token\n $ dr visualize --with-danger\n $ dr visualize --viewer-path ./dist/embedded/dr-viewer-bundle\n\nThe --with-danger flag enables dangerous mode for chat functionality:\n - Claude Code: --dangerously-skip-permissions\n - GitHub Copilot: --allow-all-tools\n\nThe --viewer-path option allows loading a local build of the web UI:\n - Point to a directory containing index.html and supporting files\n - Useful for developing custom viewers or using bundled distributions`\n )\n .action(async (options) => {\n const { visualizeCommand } = await import(\"./commands/visualize.js\");\n await visualizeCommand({\n port: options.port,\n noBrowser: options.browser === false, // Commander sets 'browser' to false when --no-browser is used\n noAuth: options.auth === false, // Commander sets 'auth' to false when --no-auth is used\n token: options.token,\n withDanger: options.withDanger,\n viewerPath: options.viewerPath,\n });\n });\n\n// AI Integration command\nprogram\n .command(\"chat [client] [withDanger]\")\n .description(\"Interactive chat with AI about the architecture model\")\n .addHelpText(\n \"after\",\n `\nArguments:\n client Optional AI client to use: \"claude-code\" or \"github-copilot\"\n withDanger Enable dangerous mode: \"with-danger\"\n\nExamples:\n $ dr chat # Auto-detect or use saved preference\n $ dr chat claude-code # Use Claude Code, save as preference\n $ dr chat github-copilot # Use GitHub Copilot, save as preference\n $ dr chat with-danger # Auto-detect with dangerous mode\n $ dr chat claude-code with-danger # Use Claude Code with dangerous mode\n $ dr chat github-copilot with-danger # Use GitHub Copilot with dangerous mode\n\nDangerous mode enables:\n - Claude Code: --dangerously-skip-permissions\n - GitHub Copilot: --allow-all-tools\n\nThis launches an interactive chat interface where you can ask AI questions\nabout your architecture model. Supports Claude Code CLI and GitHub Copilot CLI.\n\nInstall instructions:\n - Claude Code: https://claude.ai\n - GitHub Copilot: gh extension install github/gh-copilot`\n )\n .action(async (client?: string, withDangerArg?: string) => {\n // Parse arguments - handle both \"with-danger\" as first or second arg\n let selectedClient: string | undefined;\n let withDanger = false;\n\n if (client === \"with-danger\") {\n // Format: dr chat with-danger\n withDanger = true;\n selectedClient = undefined;\n } else if (withDangerArg === \"with-danger\") {\n // Format: dr chat <client> with-danger\n withDanger = true;\n selectedClient = client;\n } else {\n // Format: dr chat <client>\n selectedClient = client;\n }\n\n await chatCommand(selectedClient, withDanger);\n });\n\n// Advanced commands\nprogram\n .command(\"version\")\n .description(\"Show CLI and embedded spec version information\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr version`\n )\n .action(async () => {\n await versionCommand();\n });\n\nprogram\n .command(\"upgrade\")\n .description(\"Upgrade spec reference and migrate model to latest versions\")\n .option(\"-y, --yes\", \"Automatically upgrade without prompting\")\n .option(\"--dry-run\", \"Show what would be upgraded without making changes\")\n .option(\"--force\", \"Force all upgrades regardless of current versions; skips migration validation\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr upgrade # Scan, show plan, and prompt for upgrades\n $ dr upgrade --dry-run # Preview available upgrades\n $ dr upgrade --yes # Upgrade without prompting\n $ dr upgrade --force # Force all upgrades, ignoring version checks`\n )\n .action(async (options) => {\n await upgradeCommand({\n yes: options.yes,\n dryRun: options.dryRun,\n force: options.force,\n });\n });\n\nprogram\n .command(\"conformance\")\n .description(\"Check model conformance to layer specifications\")\n .option(\"--layers <layers...>\", \"Specific layers to check\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--verbose\", \"Verbose output\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr conformance\n $ dr conformance --layers business api application\n $ dr conformance --json\n $ dr conformance --verbose`\n )\n .action(async (options) => {\n await conformanceCommand({\n layers: options.layers,\n json: options.json,\n verbose: options.verbose ?? program.opts().verbose,\n });\n });\n\n// Changeset subcommands\nchangesetCommands(program);\n\n// Claude Code integration subcommands\nclaudeCommands(program);\n\n// GitHub Copilot integration subcommands\ncopilotCommands(program);\n\n// Analyzer integration subcommands\nanalyzerCommands(program);\n\n// Execute CLI with proper telemetry span wrapping\n// This creates a root span that all child spans will be linked to\n(async () => {\n let exitCode = 0;\n try {\n if (isTelemetryEnabled) {\n // Initialize telemetry before execution\n await initTelemetry();\n\n // Only install console interceptor for commands that need it\n const commandName = process.argv[2] || \"unknown\";\n if (CONSOLE_LOGGING_COMMANDS.has(commandName)) {\n await installConsoleInterceptor();\n }\n\n const args = process.argv.slice(3).join(\" \");\n\n // Wrap entire CLI execution in active span for proper context propagation\n await startActiveSpan(\n \"cli.execute\",\n async (span) => {\n // Attributes already set via options parameter - no duplicate setAttributes needed\n try {\n // Execute command - all child spans will now link to this root span\n await program.parseAsync(process.argv);\n\n // Set success status\n span.setStatus({ code: 0 }); // SpanStatusCode.OK\n } catch (error) {\n // Record exception and set error status\n // CommanderError with exitCode 0 is help text / unknown subcommand shown \u2014 not a real error\n if (error instanceof CommanderError) {\n if (error.exitCode === 0) {\n span.setStatus({ code: 0 }); // SpanStatusCode.OK\n } else {\n span.recordException(error as Error);\n span.setStatus({\n code: 2, // SpanStatusCode.ERROR\n message: error.message,\n });\n }\n } else {\n span.recordException(error as Error);\n span.setStatus({\n code: 2, // SpanStatusCode.ERROR\n message: getErrorMessage(error),\n });\n }\n\n // Print error message for CLIError instances\n // Skip CommanderError \u2014 Commander already printed its own output (e.g. help text, unknown command)\n const { CLIError } = await import(\"./utils/errors.js\");\n if (error instanceof CommanderError) {\n // Commander handled its own output; nothing to print\n } else if (error instanceof CLIError) {\n console.error(error.format());\n } else if (error instanceof Error) {\n console.error(error.message);\n } else {\n console.error(String(error));\n }\n\n // Extract exit code from CLIError if available\n exitCode = await extractExitCode(error);\n // Don't throw - let telemetry shutdown complete\n }\n },\n {\n \"cli.command\": commandName,\n \"cli.args\": args,\n \"cli.cwd\": process.cwd(),\n \"cli.version\": cliVersion,\n }\n );\n\n // Shutdown telemetry after execution completes\n await shutdownTelemetry();\n\n // Exit with exit code (keepAlive disabled in exporters prevents hanging)\n process.exit(exitCode);\n } else {\n // No telemetry - just parse normally with error handling\n try {\n await program.parseAsync(process.argv);\n } catch (error) {\n // Extract exit code from CLIError if available\n // Skip CommanderError \u2014 Commander already printed its own output (e.g. help text, unknown command)\n const { CLIError } = await import(\"./utils/errors.js\");\n if (error instanceof CommanderError) {\n // Commander handled its own output; nothing to print\n } else if (error instanceof CLIError) {\n console.error(error.format());\n } else {\n // Unexpected exceptions need to be printed\n if (error instanceof Error) {\n console.error(error.message);\n } else {\n console.error(String(error));\n }\n }\n const exitCodeFromError = await extractExitCode(error);\n process.exit(exitCodeFromError);\n }\n }\n } catch (error) {\n // Error during telemetry init or shutdown\n if (!isTelemetryEnabled) {\n // No telemetry - exit immediately with error\n process.exit(1);\n }\n // Telemetry enabled - try to shutdown before exit\n await shutdownTelemetry();\n process.exit(1);\n }\n})();\n"],
|
|
5
|
-
"mappings": ";AAUA,SAAS,SAAS,sBAAsB;AACxC,SAAS,wBAAwB;AACjC,SAAS,mBAAmB;AAC5B,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB;AAC5B,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AACr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AC;EAChB;AACF,GAAE;",
|
|
6
|
-
"names": []
|
|
4
|
+
"sourcesContent": ["#!/usr/bin/env node\n\n/**\n * Documentation Robotics CLI - Bun Implementation\n * Entry point for the command-line interface\n *\n * Instrumented with OpenTelemetry to create root spans for command execution.\n * Telemetry is controlled by the TELEMETRY_ENABLED build-time constant.\n */\n\nimport { Command, CommanderError } from \"commander\";\nimport { setGlobalOptions } from \"./utils/globals.js\";\nimport { installAnsiSuppressor } from \"./utils/ansi-suppressor.js\";\nimport { initCommand } from \"./commands/init.js\";\nimport { addCommand } from \"./commands/add.js\";\nimport { updateCommand } from \"./commands/update.js\";\nimport { deleteCommand } from \"./commands/delete.js\";\nimport { showCommand } from \"./commands/show.js\";\nimport { listCommand } from \"./commands/list.js\";\nimport { searchCommand } from \"./commands/search.js\";\nimport { validateCommand } from \"./commands/validate.js\";\nimport { infoCommand } from \"./commands/info.js\";\nimport { relationshipCommands } from \"./commands/relationship.js\";\nimport { elementCommands } from \"./commands/element.js\";\nimport { schemaCommands } from \"./commands/schema.js\";\nimport { catalogCommands } from \"./commands/catalog.js\";\nimport { docsCommands } from \"./commands/docs.js\";\nimport { traceCommand } from \"./commands/trace.js\";\nimport { exportCommand } from \"./commands/export.js\";\nimport { importCommand } from \"./commands/import.js\";\nimport { chatCommand } from \"./commands/chat.js\";\nimport { upgradeCommand } from \"./commands/upgrade.js\";\nimport { conformanceCommand } from \"./commands/conformance.js\";\nimport { changesetCommands } from \"./commands/changeset.js\";\nimport { farmCommands } from \"./commands/farm.js\";\nimport { claudeCommands } from \"./commands/claude.js\";\nimport { copilotCommands } from \"./commands/copilot.js\";\nimport { analyzerCommands } from \"./commands/analyzer.js\";\nimport { versionCommand } from \"./commands/version.js\";\nimport { statsCommand } from \"./commands/stats.js\";\nimport { reportCommand } from \"./commands/report.js\";\nimport { reportsCommands } from \"./commands/reports.js\";\nimport { auditCommand } from \"./commands/audit.js\";\nimport { auditDiffCommand } from \"./commands/audit-diff.js\";\nimport { auditSnapshotsCommand } from \"./commands/audit-snapshots.js\";\nimport { repairAttributeCollisionCommand } from \"./commands/repair.js\";\nimport { initTelemetry, startActiveSpan, shutdownTelemetry } from \"./telemetry/index.js\";\nimport { installConsoleInterceptor } from \"./telemetry/console-interceptor.js\";\nimport { getErrorMessage, CLIError } from \"./utils/errors.js\";\nimport { getCliVersion } from \"./utils/spec-version.js\";\n\n// Declare TELEMETRY_ENABLED as a build-time constant (substituted by esbuild)\n// Provide runtime fallback when not running through esbuild\ndeclare const TELEMETRY_ENABLED: boolean;\nconst isTelemetryEnabled = typeof TELEMETRY_ENABLED !== \"undefined\" ? TELEMETRY_ENABLED : false;\n\n// Commands that require console interceptor for telemetry logging\nconst CONSOLE_LOGGING_COMMANDS = new Set(['chat', 'validate', 'import', 'export']);\n\n// Suppress ANSI color output on non-TTY stdout\nif (!process.stdout.isTTY) {\n process.env.FORCE_COLOR = \"0\";\n process.env.NO_COLOR = \"1\";\n}\n\n// Install the ANSI suppressor to strip color codes from console output when not on TTY\ninstallAnsiSuppressor();\n\n/**\n * Extract exit code from an error object.\n * Handles CLIError instances and duck-typed objects with exitCode property.\n */\nasync function extractExitCode(error: unknown): Promise<number> {\n const { CLIError } = await import(\"./utils/errors.js\");\n\n if (error instanceof CLIError) {\n return error.exitCode;\n }\n\n // Commander's own errors (--help, unknown commands, etc.) carry exitCode as\n // expected control flow \u2014 handle them directly without duck-typing.\n if (error instanceof CommanderError) {\n return error.exitCode;\n }\n\n // Fallback for duck-typing (handles bundling/module issues)\n if (error && typeof error === \"object\" && \"exitCode\" in error) {\n const errorObj = error as any;\n if (typeof errorObj.exitCode === \"number\") {\n // Validate this looks like a CLIError before accepting\n if (errorObj.name === \"CLIError\" || errorObj.message) {\n if (process.argv.includes(\"--debug\")) {\n console.warn(\n \"[DEBUG] Using duck-typed error object as fallback - this may indicate a module loading issue\"\n );\n }\n return errorObj.exitCode;\n }\n }\n }\n\n return 1;\n}\n\nconst cliVersion = getCliVersion();\n\nconst program = new Command();\n\n// Handle --version and -V flags by redirecting to version command\n// This ensures they go through the telemetry wrapper\nif (process.argv.includes(\"--version\") || process.argv.includes(\"-V\")) {\n process.argv = [\"node\", \"dr\", \"version\"];\n}\n\nprogram\n .name(\"dr\")\n .description(\"Documentation Robotics CLI - Architecture Model Management\")\n .option(\"-v, --verbose\", \"Enable verbose output\")\n .option(\"--debug\", \"Enable debug mode\")\n .option(\"--json\", \"Output as JSON (supported on mutating and query commands)\")\n .option(\"--codebase-path <path>\", \"Override codebase root path (default: resolved from manifest or project root)\")\n .exitOverride() // Prevent Commander from calling process.exit() - we handle exit ourselves\n .showSuggestionAfterError() // \"Did you mean X?\" on unknown commands/options\n .hook(\"preAction\", async (thisCommand) => {\n // Set up global state (verbose/debug/json flags)\n const options = thisCommand.opts();\n setGlobalOptions({\n verbose: options.verbose as boolean | undefined,\n debug: options.debug as boolean | undefined,\n json: options.json as boolean | undefined,\n codebasePath: options.codebasePath as string | undefined,\n });\n });\n\n// Model commands\nprogram\n .command(\"init [name]\")\n .description(\"Initialize a new architecture model\")\n .option(\"--name <name>\", \"Model name (overrides positional argument)\")\n .option(\"--author <author>\", \"Model author\")\n .option(\"--description <desc>\", \"Model description\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr init\n $ dr init claudetoreum\n $ dr init \"Enterprise Architecture\" --author \"Team A\"\n $ dr init --name \"My Project\" --description \"13-layer federated model\"`\n )\n .action((name, options) => initCommand({ ...options, name: options.name || name }));\n\nprogram\n .command(\"add <layer> <type> <name>\")\n .description(\"Add an element to a layer\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .option(\"--name <name>\", \"Element display name (defaults to the name argument)\")\n .option(\"--description <desc>\", \"Element description\")\n .option(\"--attributes <json>\", \"Element type-specific attributes as JSON object\")\n .option(\"--source-file <path>\", \"Source file path (relative from repository root)\")\n .option(\"--source-symbol <name>\", \"Symbol name (class, function, variable) in source file\")\n .option(\"--source-provenance <type>\", \"Provenance type: extracted, manual, inferred, generated\")\n .option(\"--source-repo-remote <url>\", \"Git remote URL for repository context\")\n .option(\"--source-repo-commit <sha>\", \"Git commit SHA (40 hex characters) for repository context\")\n .option(\"--verbose\", \"Show detailed output (can also use global -v flag)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr add business service \"Customer Management\"\n $ dr add api operation \"Create Customer\" --attributes '{\"operationId\":\"createCustomer\",\"summary\":\"Create a customer\",\"tags\":\"customers\"}'\n $ dr add application component \"Customer API\" --description \"REST API for customer operations\"\n $ dr add security policy \"Auth Validator\" --source-file \"src/auth/validator.ts\" --source-symbol \"validateToken\" --source-provenance \"extracted\"\n\nNote: Element IDs are generated automatically in format {layer}.{type}.{kebab-name}`\n )\n .action((layer, type, name, options) =>\n addCommand(layer, type, name, { ...options, verbose: options.verbose ?? program.opts().verbose }));\n\nprogram\n .command(\"update <id>\")\n .description(\"Update an element\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .option(\"--name <name>\", \"New element name\")\n .option(\"--description <desc>\", \"New description\")\n .option(\"--type <new-type>\", \"Change element type (must be valid for the element's layer; incompatible attributes must be cleaned up manually)\")\n .option(\"--attributes <json>\", \"Updated type-specific attributes (JSON)\")\n .option(\"--source-file <path>\", \"Source file path (relative from repository root)\")\n .option(\"--source-symbol <name>\", \"Symbol name (class, function, variable) in source file\")\n .option(\"--source-provenance <type>\", \"Provenance type: extracted, manual, inferred, generated\")\n .option(\"--source-repo-remote <url>\", \"Git remote URL for repository context\")\n .option(\"--source-repo-commit <sha>\", \"Git commit SHA (40 hex characters) for repository context\")\n .option(\"--clear-source-reference\", \"Remove source reference from element\")\n .option(\"--verbose\", \"Show detailed output (can also use global -v flag)\")\n .addHelpText(\n \"after\",\n `\nNote: Changes are written immediately to model files.\nTo track changes for review, activate a changeset first:\n $ dr changeset activate my-changeset\n\nExamples:\n $ dr update api-endpoint-create-customer --name \"Create Customer (v2)\"\n $ dr update business-service-order --description \"Updated description\"\n $ dr update application-applicationfunction-process-orders --type applicationservice\n $ dr update security-policy-auth --source-file \"src/auth/policy.ts\" --source-provenance \"extracted\"`\n )\n .action((id, options) =>\n updateCommand(id, { ...options, verbose: options.verbose ?? program.opts().verbose }));\n\nprogram\n .command(\"delete <id>\")\n .description(\"Delete an element\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .option(\"--force\", \"Skip dependency checks (confirmation is also skipped in non-TTY environments)\")\n .option(\"--cascade\", \"Remove dependent elements automatically\")\n .option(\"--dry-run\", \"Show what would be removed without actually removing\")\n .option(\"--verbose\", \"Show detailed output (can also use global -v flag)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr delete api-endpoint-old-endpoint\n $ dr delete api-endpoint-old-endpoint --force\n $ dr delete api-endpoint-old-endpoint --cascade\n $ dr delete api-endpoint-old-endpoint --dry-run\n $ dr delete api-endpoint-old-endpoint --cascade --dry-run`\n )\n .action((id, options) =>\n deleteCommand(id, { ...options, verbose: options.verbose ?? program.opts().verbose }));\n\nprogram\n .command(\"show <id>\")\n .description(\"Display element details\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr show api-endpoint-create-customer\n $ dr show business-service-order-mgmt`\n )\n .action((id, options) => showCommand(id, options));\n\nprogram\n .command(\"list [layer]\")\n .description(\"List elements in a layer (or all layers if omitted)\")\n .option(\"--type <type>\", \"Filter by element type\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr list\n $ dr list api\n $ dr list business --type businessservice\n $ dr list api --json\n $ dr list --json`\n )\n .action((layer, options) => {\n return listCommand(layer, { ...options, json: options.json ?? program.opts().json });\n });\n\nprogram\n .command(\"search <query>\")\n .description(\"Search for elements by name or ID\")\n .option(\"--layer <layer>\", \"Limit search to specific layer\")\n .option(\"--type <type>\", \"Filter by element type\")\n .option(\n \"--source-file <path>\",\n \"Find elements referencing a source file (takes precedence over pattern matching)\"\n )\n .option(\"--json\", \"Output as JSON\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr search customer\n $ dr search \"order processing\" --layer business\n $ dr search create-* --type endpoint\n $ dr search \"\" --source-file src/api/customer.ts`\n )\n .action((query, options) => {\n return searchCommand(query, { ...options, json: options.json ?? program.opts().json });\n });\n\nprogram\n .command(\"validate\")\n .description(\"Validate the architecture model\")\n .option(\"--layers <layers...>\", \"Specific layers to validate\")\n .option(\"--strict\", \"Treat warnings as errors\")\n .option(\"--verbose\", \"Show detailed validation output with relationship breakdown\")\n .option(\"--quiet\", \"Show minimal output\")\n .option(\"--output <path>\", \"Export validation report to file (JSON or Markdown)\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .option(\"--orphans\", \"Show only orphaned elements grouped by layer with relationship suggestions\")\n .option(\"--all\", \"Run all validations (default behavior)\")\n .option(\"--markdown\", \"Validate markdown structure\")\n .option(\"--schemas\", \"Validate JSON schemas\")\n .option(\"--schema\", \"Validate JSON schemas (alias for --schemas)\")\n .option(\"--relationships\", \"Validate relationships\")\n .option(\"--structure\", \"Validate documentation structure\")\n .option(\"--naming\", \"Validate naming conventions\")\n .option(\"--references\", \"Validate cross-layer references\")\n .option(\"--scope <scope>\", \"Validation scope: 'local' (default) or 'composed' for cross-model validation\")\n .option(\"--model-path <mapping...>\", \"Override filesystem path for external model (format: model-name=/path/to/project-root, can be repeated)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr validate\n $ dr validate --all --strict\n $ dr validate --verbose\n $ dr validate --quiet\n $ dr validate --output report.json\n $ dr validate --output report.md\n $ dr validate --schemas\n $ dr validate --relationships\n $ dr validate --layers business api\n $ dr validate --orphans\n $ dr validate --orphans --output orphans.json\n $ dr validate --scope composed --model-path auth-service=/path/to/auth-service-repo\n $ dr validate --scope composed --model-path auth-service=/path/to/auth-service-repo --model-path payment-service=/path/to/payment-repo\n\nNote: When using --model-path, pass the project root (where documentation-robotics/model/ is located).`\n )\n .action(validateCommand);\n\nprogram\n .command(\"export <format>\")\n .description(\"Export the architecture model to various formats\")\n .option(\"--output <path>\", \"Output file path (default: print to stdout)\")\n .option(\"--layers <layers...>\", \"Specific layers to export\")\n .option(\"--model <path>\", \"Path to model root directory or manifest.yaml file\")\n .option(\"--include-sources\", \"Include source file paths in PlantUML diagrams as notes\")\n .addHelpText(\n \"after\",\n `\nSupported formats:\n archimate Export to ArchiMate XML (layers 1, 2, 5, 6)\n openapi Export to OpenAPI 3.0 specification (layer 7)\n jsonschema Export to JSON Schema (layer 8)\n plantuml Export to PlantUML diagram\n graphml Export to GraphML (graph visualization)\n markdown Export to Markdown documentation\n\nExamples:\n $ dr export archimate --output model.xml\n $ dr export openapi --layers api\n $ dr export plantuml --include-sources --output diagram.puml\n $ dr export markdown --output docs/architecture.md`\n )\n .action(async (format, options) => {\n await exportCommand({\n format,\n output: options.output,\n layers: options.layers,\n model: options.model,\n includeSources: options.includeSources,\n });\n });\n\nprogram\n .command(\"import <format>\")\n .description(\"Import architecture model from various formats\")\n .option(\"--input <path>\", \"Input file path (required)\", undefined)\n .option(\"--model <path>\", \"Path to model root directory or manifest.yaml file\")\n .option(\n \"--merge-strategy <strategy>\",\n \"How to handle existing elements: add, update, skip (default: add)\"\n )\n .addHelpText(\n \"after\",\n `\nSupported formats:\n archimate Import from ArchiMate XML (layers 1, 2, 5, 6)\n openapi Import from OpenAPI 3.0 specification (layer 7)\n\nExamples:\n $ dr import archimate --input model.xml\n $ dr import openapi --input api.json --merge-strategy add\n $ dr import archimate --input model.xml --model ./myproject`\n )\n .action(async (format, options) => {\n if (!options.input) {\n console.error(\"Error: --input path is required\");\n process.exit(1);\n }\n await importCommand({\n format,\n input: options.input,\n model: options.model,\n mergeStrategy: options.mergeStrategy as \"add\" | \"update\" | \"skip\" | undefined,\n });\n });\n\nprogram\n .command(\"info\")\n .description(\"Show model information\")\n .option(\"--layer <layer>\", \"Show specific layer details\")\n .option(\"--verbose\", \"Show detailed breakdown by element type\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr info\n $ dr info --layer business\n $ dr info --layer api --verbose`\n )\n .action(infoCommand);\n\nprogram\n .command(\"stats\")\n .description(\"Display model statistics and health metrics\")\n .option(\"--model <path>\", \"Path to the model directory\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown, compact\")\n .option(\"--output <path>\", \"Output file path (auto-detects format from extension)\")\n .option(\"--compact\", \"Show compact one-line summary\")\n .option(\"--verbose\", \"Show detailed information\")\n .addHelpText(\n \"after\",\n `\nOutput formats:\n text Full formatted statistics (default)\n json JSON output for automation\n markdown Markdown report format\n compact Single-line summary\n\nExamples:\n $ dr stats # Show full statistics\n $ dr stats --compact # Show one-line summary\n $ dr stats --format json # Output as JSON\n $ dr stats --output stats.md # Save as markdown file\n $ dr stats --output stats.json # Save as JSON file\n $ dr stats --verbose # Show detailed information`\n )\n .action((options) => statsCommand(options));\n\nprogram\n .command(\"report\")\n .description(\"Generate comprehensive architecture reports\")\n .option(\"--model <path>\", \"Path to the model directory\")\n .option(\"--type <type>\", \"Report type: comprehensive (default), statistics, relationships, data-model, quality\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown\")\n .option(\"--output <path>\", \"Output file path (auto-detects format from extension)\")\n .option(\"--verbose\", \"Show detailed information\")\n .option(\"--include-data-model\", \"Include data model analysis (default: true)\")\n .option(\"--include-quality\", \"Include quality metrics (default: true)\")\n .addHelpText(\n \"after\",\n `\nReport types:\n comprehensive Full report with statistics, relationships, and data model (default)\n statistics Statistics and quality metrics\n relationships Relationship analysis and classification\n data-model Layer 8 data model analysis\n quality Quality metrics and recommendations\n\nOutput formats:\n text Full formatted report (default)\n json JSON output for automation\n markdown Markdown report format\n\nExamples:\n $ dr report # Show comprehensive report\n $ dr report --type relationships # Show relationship analysis\n $ dr report --format json # Output as JSON\n $ dr report --output report.md # Save as markdown file\n $ dr report --type data-model --output dm.md # Data model report as markdown\n $ dr report --verbose # Show detailed information`\n )\n .action((options) => reportCommand(options));\n\n// Reports subcommands (managed layer report files)\nconst reportsGroup = program.command(\"reports\").description(\"Manage architecture layer reports\");\nreportsCommands(reportsGroup);\n\n// Audit command - Relationship analysis\nprogram\n .command(\"audit [layer]\")\n .description(\"Analyze relationship coverage, gaps, duplicates, and balance\")\n .option(\"--type <type>\", \"Audit type: relationships (default), nodes, all\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown\")\n .option(\"--output <path>\", \"Output file path (auto-detects format from extension)\")\n .option(\"--verbose\", \"Show detailed analysis\")\n .option(\"--save-snapshot\", \"Save audit report as snapshot for differential analysis\")\n .addHelpText(\n \"after\",\n `\nAudit types:\n relationships Relationship coverage, gaps, duplicates, balance (default)\n nodes Node type usage distribution across model layers\n all Both relationship and node audits\n\nOutput formats:\n text Full formatted audit report (default)\n json JSON output for automation\n markdown Markdown audit report format\n\nExamples:\n $ dr audit # Full relationship audit of all layers\n $ dr audit security # Audit security layer only\n $ dr audit --type nodes # Node type distribution audit\n $ dr audit --type all # Combined relationship + node audit\n $ dr audit --format json # Output as JSON\n $ dr audit --output audit.md # Save as markdown file\n $ dr audit --verbose # Show detailed analysis\n $ dr audit --save-snapshot # Save snapshot for later comparison\n $ dr audit api --output api-audit.json # API layer audit as JSON`\n )\n .action((layer, options) =>\n auditCommand({ ...options, layer, verbose: options.verbose ?? program.opts().verbose }));\n\n// Audit diff command - Compare snapshots\nprogram\n .command(\"audit:diff\")\n .description(\"Compare before/after audit snapshots\")\n .option(\"--before <id>\", \"Before snapshot ID or timestamp\")\n .option(\"--after <id>\", \"After snapshot ID or timestamp\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown\")\n .option(\"--output <path>\", \"Output file path\")\n .option(\"--verbose\", \"Show detailed comparison\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr audit:diff # Compare latest two snapshots\n $ dr audit:diff --before 20260220-100000 --after 20260220-150000\n $ dr audit:diff --format markdown --output diff.md\n $ dr audit:diff --verbose # Show detailed changes`\n )\n .action((options) => auditDiffCommand(options));\n\n// Audit snapshots command - Manage snapshots\nprogram\n .command(\"audit:snapshots <action>\")\n .description(\"Manage audit snapshots (list, delete, clear)\")\n .option(\"--id <id>\", \"Snapshot ID (for delete action)\")\n .addHelpText(\n \"after\",\n `\nActions:\n list List all available snapshots\n delete Delete a specific snapshot (requires --id)\n clear Delete all snapshots\n\nExamples:\n $ dr audit:snapshots list\n $ dr audit:snapshots delete --id 20260220-100000\n $ dr audit:snapshots clear`\n )\n .action((action, options) => auditSnapshotsCommand({ ...options, action }));\n\n// Repair command - Detect and recover data lost to fixed data-integrity bugs\nprogram\n .command(\"repair:attribute-collision\")\n .description(\n 'Find and best-effort-recover model data lost to a fixed bug where saveLayer() stripped \"source\"/\"x-source-reference\" attributes from every element, even when a node type\\'s schema declared one as a real (sometimes required) attribute'\n )\n .option(\"--apply\", \"Restore recoverable values found in changeset history (default: report only)\")\n .option(\"--format <format>\", \"Output format: text (default), json\")\n .option(\"--output <path>\", \"Write the report to a file instead of stdout\")\n .addHelpText(\n \"after\",\n `\nThis repairs damage from a fixed bug in Model.saveLayer(): a hardcoded, type-blind \"internal\nfields\" blocklist unconditionally stripped any attribute literally named \"source\" or\n\"x-source-reference\" from every element's attributes before writing YAML, regardless of whether\nthe element's own schema declared it as a real domain attribute. 41 of 191 node schemas across 8\nlayers do (3 mark it required, meaning affected elements fail validation today).\n\nRecovery is best-effort: values can only be restored if they still exist in changeset history\n(committing a changeset does not delete it). Elements with no recoverable value are always\nreported, never fabricated \u2014 you'll need to re-supply those manually with\n\"dr update <id> --attributes '{...}'\".\n\nExamples:\n $ dr repair:attribute-collision # Report only \u2014 no changes made\n $ dr repair:attribute-collision --apply # Restore every recoverable value\n $ dr repair:attribute-collision --format json --output report.json`\n )\n .action((options) => repairAttributeCollisionCommand(options));\n\n// Relationship subcommands\nconst relationshipGroup = program.command(\"relationship\").description(\"Relationship operations\");\nrelationshipCommands(relationshipGroup, program);\n\n// Element subcommands\nconst elementGroup = program.command(\"element\").description(\"Element operations\");\nelementCommands(elementGroup, program);\n\n// Schema introspection subcommands\nschemaCommands(program);\n\n// Catalog subcommands (modern relationship catalog)\ncatalogCommands(program);\n\n// Documentation subcommands (schema-driven generation)\ndocsCommands(program);\n\n// Dependency analysis commands\nprogram\n .command(\"trace <elementId>\")\n .description(\"Trace dependencies for an element\")\n .option(\n \"--direction <dir>\",\n \"Trace direction: up (dependencies), down (dependents), both (default)\"\n )\n .option(\"--depth <num>\", \"Maximum traversal depth\")\n .option(\"--metrics\", \"Show graph and element metrics\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr trace api-endpoint-create-customer\n $ dr trace business-service-order --direction down --metrics\n $ dr trace application-component-api --depth 3`\n )\n .action(async (elementId, options) => {\n await traceCommand(elementId, {\n direction: options.direction as \"up\" | \"down\" | \"both\" | undefined,\n depth: options.depth ? parseInt(options.depth) : undefined,\n showMetrics: options.metrics,\n model: options.model,\n });\n });\n\nprogram\n .command(\"visualize\")\n .description(\"Launch visualization server with WebSocket support\")\n .option(\"--port <num>\", \"Server port (default: 8080)\")\n .option(\"--no-browser\", \"Do not auto-open browser\")\n .option(\"--no-auth\", \"Disable authentication (enabled by default)\")\n .option(\"--token <token>\", \"Custom auth token (auto-generated by default)\")\n .option(\"--with-danger\", \"Enable dangerous mode for chat (skip permissions)\")\n .option(\n \"--viewer-path <path>\",\n \"Path to custom viewer build (e.g., ./dist/embedded/dr-viewer-bundle)\"\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr visualize\n $ dr visualize --port 3000\n $ dr visualize --no-browser\n $ dr visualize --no-auth\n $ dr visualize --token my-secret-token\n $ dr visualize --with-danger\n $ dr visualize --viewer-path ./dist/embedded/dr-viewer-bundle\n\nDefault mode (read-safe permissions) enables:\n - Running 'dr' CLI commands to query the architecture model\n - Reading the codebase\n - Reading the documentation-robotics/ model folder\n - Reading the .dr/ configuration folder\n\nDangerous mode (--with-danger) enables unrestricted access:\n - Claude Code: --dangerously-skip-permissions (full tool access)\n - GitHub Copilot: --allow-all-tools (full tool access)\n\nThe --viewer-path option allows loading a local build of the web UI:\n - Point to a directory containing index.html and supporting files\n - Useful for developing custom viewers or using bundled distributions`\n )\n .action(async (options) => {\n const { visualizeCommand } = await import(\"./commands/visualize.js\");\n await visualizeCommand({\n port: options.port,\n noBrowser: options.browser === false, // Commander sets 'browser' to false when --no-browser is used\n noAuth: options.auth === false, // Commander sets 'auth' to false when --no-auth is used\n token: options.token,\n withDanger: options.withDanger,\n viewerPath: options.viewerPath,\n });\n });\n\nprogram\n .command(\"mcp\")\n .description(\"Start MCP server for AI assistant integration\")\n .option(\n \"--regenerate-key\",\n \"Generate a new MCP API key, overwrite it at the configured storage path, and print it (does not start the server)\"\n )\n .option(\n \"--transport <type>\",\n \"Transport type: stdio or http (default: stdio)\",\n \"stdio\"\n )\n .option(\n \"--port <number>\",\n \"Port for HTTP transport (default: 3100, only meaningful with --transport http)\",\n \"3100\"\n )\n .option(\n \"--host <address>\",\n \"Host address for HTTP transport (default: 127.0.0.1, only meaningful with --transport http)\",\n \"127.0.0.1\"\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n\nStdio transport (default):\n $ dr mcp\n\nHTTP transport:\n $ dr mcp --transport http # HTTP on localhost:3100\n $ dr mcp --transport http --port 8200 # HTTP on custom port\n $ dr mcp --transport http --host 0.0.0.0 --port 3100 # Listen on all interfaces\n\nKey management:\n $ dr mcp --regenerate-key # Generate new API key\n\nInitial Setup:\nOn first launch, generates an API key and asks where to store it (interactive\nsessions only; non-interactive launches default to ~/.dr-mcp-key). The key is\nprinted to stderr on every launch and must be supplied via environment variable.\n\nStdio Configuration:\nFor stdio transport, supply the key via environment variable:\n\n {\n \"command\": \"dr\",\n \"args\": [\"mcp\"],\n \"env\": { \"DR_MCP_API_KEY\": \"<your-api-key>\" }\n }\n\nHTTP Configuration:\nFor HTTP transport, include the API key as a Bearer token in the Authorization header:\n\n {\n \"url\": \"http://localhost:3100/mcp\",\n \"headers\": {\n \"Authorization\": \"Bearer <your-api-key>\"\n }\n }\n\nUse --regenerate-key to rotate the key (e.g. after a suspected leak) without\nmanually deleting the stored key file or config.`\n )\n .action(async (options) => {\n const { mcpCommand } = await import(\"./commands/mcp.js\");\n const transport = (options.transport as string).toLowerCase();\n if (transport !== \"stdio\" && transport !== \"http\") {\n throw new CLIError(`Invalid transport: ${transport}. Allowed values: stdio, http`, 1);\n }\n const port = parseInt(options.port as string, 10);\n if (!Number.isFinite(port) || port < 1 || port > 65535) {\n throw new CLIError(`Invalid port: ${options.port}. Must be a number between 1 and 65535`, 1);\n }\n await mcpCommand({\n regenerateKey: options.regenerateKey,\n transport: transport as \"stdio\" | \"http\",\n port,\n host: options.host as string,\n });\n });\n\n// AI Integration command\nprogram\n .command(\"chat [client] [withDanger]\")\n .description(\"Interactive chat with AI about the architecture model\")\n .addHelpText(\n \"after\",\n `\nArguments:\n client Optional AI client to use: \"claude-code\" or \"github-copilot\"\n withDanger Enable dangerous mode: \"with-danger\"\n\nExamples:\n $ dr chat # Auto-detect or use saved preference\n $ dr chat claude-code # Use Claude Code, save as preference\n $ dr chat github-copilot # Use GitHub Copilot, save as preference\n $ dr chat with-danger # Auto-detect with dangerous mode\n $ dr chat claude-code with-danger # Use Claude Code with dangerous mode\n $ dr chat github-copilot with-danger # Use GitHub Copilot with dangerous mode\n\nDefault mode (read-safe permissions) enables:\n - Running 'dr' CLI commands to query the architecture model\n - Reading the codebase\n - Reading the documentation-robotics/ model folder\n - Reading the .dr/ configuration folder\n\nDangerous mode (--with-danger) enables unrestricted access:\n - Claude Code: --dangerously-skip-permissions (full tool access)\n - GitHub Copilot: --allow-all-tools (full tool access)\n\nThis launches an interactive chat interface where you can ask AI questions\nabout your architecture model. Supports Claude Code CLI and GitHub Copilot CLI.\n\nInstall instructions:\n - Claude Code: https://claude.ai\n - GitHub Copilot: gh extension install github/gh-copilot`\n )\n .action(async (client?: string, withDangerArg?: string) => {\n // Parse arguments - handle both \"with-danger\" as first or second arg\n let selectedClient: string | undefined;\n let withDanger = false;\n\n if (client === \"with-danger\") {\n // Format: dr chat with-danger\n withDanger = true;\n selectedClient = undefined;\n } else if (withDangerArg === \"with-danger\") {\n // Format: dr chat <client> with-danger\n withDanger = true;\n selectedClient = client;\n } else {\n // Format: dr chat <client>\n selectedClient = client;\n }\n\n await chatCommand(selectedClient, withDanger);\n });\n\n// Advanced commands\nprogram\n .command(\"version\")\n .description(\"Show CLI and embedded spec version information\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr version`\n )\n .action(async () => {\n await versionCommand();\n });\n\nprogram\n .command(\"upgrade\")\n .description(\"Upgrade spec reference and migrate model to latest versions\")\n .option(\"-y, --yes\", \"Automatically upgrade without prompting\")\n .option(\"--dry-run\", \"Show what would be upgraded without making changes\")\n .option(\"--force\", \"Force all upgrades regardless of current versions; skips migration validation\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr upgrade # Scan, show plan, and prompt for upgrades\n $ dr upgrade --dry-run # Preview available upgrades\n $ dr upgrade --yes # Upgrade without prompting\n $ dr upgrade --force # Force all upgrades, ignoring version checks`\n )\n .action(async (options) => {\n await upgradeCommand({\n yes: options.yes,\n dryRun: options.dryRun,\n force: options.force,\n });\n });\n\nprogram\n .command(\"conformance\")\n .description(\"Check model conformance to layer specifications\")\n .option(\"--layers <layers...>\", \"Specific layers to check\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--verbose\", \"Verbose output\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr conformance\n $ dr conformance --layers business api application\n $ dr conformance --json\n $ dr conformance --verbose`\n )\n .action(async (options) => {\n await conformanceCommand({\n layers: options.layers,\n json: options.json ?? program.opts().json,\n verbose: options.verbose ?? program.opts().verbose,\n });\n });\n\n// Changeset subcommands\nchangesetCommands(program);\n\n// Farm subcommands\nfarmCommands(program);\n\n// Claude Code integration subcommands\nclaudeCommands(program);\n\n// GitHub Copilot integration subcommands\ncopilotCommands(program);\n\n// Analyzer integration subcommands\nanalyzerCommands(program);\n\n// Execute CLI with proper telemetry span wrapping\n// This creates a root span that all child spans will be linked to\n(async () => {\n let exitCode = 0;\n try {\n if (isTelemetryEnabled) {\n // Initialize telemetry before execution\n await initTelemetry();\n\n // Only install console interceptor for commands that need it\n const commandName = process.argv[2] || \"unknown\";\n if (CONSOLE_LOGGING_COMMANDS.has(commandName)) {\n await installConsoleInterceptor();\n }\n\n const args = process.argv.slice(3).join(\" \");\n\n // Wrap entire CLI execution in active span for proper context propagation\n await startActiveSpan(\n \"cli.execute\",\n async (span) => {\n // Attributes already set via options parameter - no duplicate setAttributes needed\n try {\n // Execute command - all child spans will now link to this root span\n await program.parseAsync(process.argv);\n\n // Set success status\n span.setStatus({ code: 0 }); // SpanStatusCode.OK\n } catch (error) {\n // Record exception and set error status\n // CommanderError with exitCode 0 is help text / unknown subcommand shown \u2014 not a real error\n if (error instanceof CommanderError) {\n if (error.exitCode === 0) {\n span.setStatus({ code: 0 }); // SpanStatusCode.OK\n } else {\n span.recordException(error as Error);\n span.setStatus({\n code: 2, // SpanStatusCode.ERROR\n message: error.message,\n });\n }\n } else {\n span.recordException(error as Error);\n span.setStatus({\n code: 2, // SpanStatusCode.ERROR\n message: getErrorMessage(error),\n });\n }\n\n // Print error message for CLIError instances\n // Skip CommanderError \u2014 Commander already printed its own output (e.g. help text, unknown command)\n const { CLIError } = await import(\"./utils/errors.js\");\n const { isJson } = await import(\"./utils/globals.js\");\n if (error instanceof CommanderError) {\n // Commander handled its own output; nothing to print\n } else if (error instanceof CLIError) {\n // In JSON mode, handleError already output structured JSON; skip text formatting\n if (!isJson()) {\n console.error(error.format());\n }\n } else if (error instanceof Error) {\n console.error(error.message);\n } else {\n console.error(String(error));\n }\n\n // Extract exit code from CLIError if available\n exitCode = await extractExitCode(error);\n // Don't throw - let telemetry shutdown complete\n }\n },\n {\n \"cli.command\": commandName,\n \"cli.args\": args,\n \"cli.cwd\": process.cwd(),\n \"cli.version\": cliVersion,\n }\n );\n\n // Shutdown telemetry after execution completes\n await shutdownTelemetry();\n\n // Exit with exit code (keepAlive disabled in exporters prevents hanging)\n process.exit(exitCode);\n } else {\n // No telemetry - just parse normally with error handling\n try {\n await program.parseAsync(process.argv);\n } catch (error) {\n // Extract exit code from CLIError if available\n // Skip CommanderError \u2014 Commander already printed its own output (e.g. help text, unknown command)\n const { CLIError } = await import(\"./utils/errors.js\");\n const { isJson } = await import(\"./utils/globals.js\");\n if (error instanceof CommanderError) {\n // Commander handled its own output; nothing to print\n } else if (error instanceof CLIError) {\n // In JSON mode, handleError already output structured JSON; skip text formatting\n if (!isJson()) {\n console.error(error.format());\n }\n } else {\n // Unexpected exceptions need to be printed\n if (error instanceof Error) {\n console.error(error.message);\n } else {\n console.error(String(error));\n }\n }\n const exitCodeFromError = await extractExitCode(error);\n process.exit(exitCodeFromError);\n }\n }\n } catch (error) {\n // Error during telemetry init or shutdown\n if (!isTelemetryEnabled) {\n // No telemetry - exit immediately with error\n process.exit(1);\n }\n // Telemetry enabled - try to shutdown before exit\n await shutdownTelemetry();\n process.exit(1);\n }\n})();\n"],
|
|
5
|
+
"mappings": ";AAUA,SAAS,SAAS,sBAAsB;AACxC,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,mBAAmB;AAC5B,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB;AAC5B,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AACrC,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB;AAC5B,SAAS,sBAAsB;AAC/B,SA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EAAE,UAAAA,UAAQ,IAAK,MAAM,OAAO,mBAAmB,GAC/C,EAAE,OAAM,IAAK,MAAM,OAAO,oBAAoB;AACpD,QAAI,iBAAiB,mBAEV,iBAAiBA,YAErB,OAAM,KACT,QAAQ,MAAM,MAAM,OAAM,CAAE,IAI1B,iBAAiB,QACnB,QAAQ,MAAM,MAAM,OAAO,IAE3B,QAAQ,MAAM,OAAO,KAAK,CAAC;AAG/B,cAAM,oBAAoB,MAAM,gBAAgB,KAAK;AACrD,gBAAQ,KAAK,iBAAiB;MAChC;EAEJ,QAAgB;AAEd,IAAK,sBAEH,QAAQ,KAAK,CAAC,GAGhB,MAAM,kBAAiB,GACvB,QAAQ,KAAK,CAAC;EAChB;AACF,GAAE;",
|
|
6
|
+
"names": ["CLIError"]
|
|
7
7
|
}
|
|
@@ -37,7 +37,9 @@ class ClaudeCodeAgent {
|
|
|
37
37
|
cwd,
|
|
38
38
|
stdio: ["pipe", "pipe", "pipe"]
|
|
39
39
|
});
|
|
40
|
-
proc.stdin
|
|
40
|
+
proc.stdin?.on("error", (error) => {
|
|
41
|
+
error.code !== "EPIPE" && console.error(`Unexpected stdin error (${error.code}): ${error.message}`);
|
|
42
|
+
}), proc.stdin.write(message), proc.stdin.end();
|
|
41
43
|
const completion = this.monitorProcess(proc, conversationId);
|
|
42
44
|
return {
|
|
43
45
|
process: proc,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/coding-agents/agents/claude-code.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Claude Code CLI Agent Implementation\n *\n * Integrates Claude Code CLI (https://claude.ai) for AI-powered\n * architecture model exploration. Supports the dr-architect agent\n * with streaming JSON output parsing.\n */\n\nimport { spawnSync, spawn } from \"child_process\";\nimport {\n CodingAgent,\n AgentProcess,\n ChatEvent,\n SpawnAgentOptions,\n AgentProcessResult,\n} from \"./types.js\";\n\n/**\n * Claude Code CLI agent implementation\n *\n * Uses `claude` command with:\n * - dr-architect agent for DR-specific knowledge\n * - --output-format stream-json for structured events\n * - stdin for message input\n * - stdout for JSON event stream\n */\nexport class ClaudeCodeAgent implements CodingAgent {\n readonly name = \"Claude Code\";\n readonly command = \"claude\";\n\n /**\n * Check if Claude Code CLI is available\n * Uses 'which' on Unix-like systems or 'where' on Windows\n */\n async isAvailable(): Promise<boolean> {\n try {\n const isWindows = process.platform === \"win32\";\n const checkCommand = isWindows ? \"where\" : \"which\";\n\n const result = spawnSync(checkCommand, [this.command], {\n stdio: \"pipe\",\n encoding: \"utf-8\",\n });\n return result.status === 0;\n } catch {\n return false;\n }\n }\n\n /**\n * Spawn Claude Code CLI process\n *\n * Creates subprocess with dr-architect agent, sends initial message via stdin,\n * and monitors stdout for JSON events.\n */\n spawn(options: SpawnAgentOptions): AgentProcess {\n const { cwd, message, agentName = \"dr-architect\", additionalArgs = [] } = options;\n\n // Generate conversation ID\n const conversationId = `claude-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n\n // Build command arguments\n const args = [\n \"--agent\",\n agentName,\n \"--print\",\n \"--dangerously-skip-permissions\",\n \"--verbose\",\n \"--output-format\",\n \"stream-json\",\n ...additionalArgs,\n ];\n\n // Spawn process\n const proc = spawn(this.command, args, {\n cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n\n // Send initial message via stdin\n proc.stdin.write(message);\n proc.stdin.end();\n\n // Set up completion promise\n const completion = this.monitorProcess(proc, conversationId);\n\n return {\n process: proc,\n conversationId,\n completion,\n };\n }\n\n /**\n * Parse Claude Code JSON output into chat events\n *\n * Claude Code outputs line-delimited JSON events:\n * - {\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"...\"}]}}\n * - {\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"tool_use\",\"name\":\"...\"}]}}\n *\n * Non-JSON lines are treated as plain text output.\n */\n parseOutput(chunk: string): ChatEvent[] {\n const events: ChatEvent[] = [];\n const lines = chunk.split(\"\\n\");\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n const event = JSON.parse(line);\n\n if (event.type === \"assistant\") {\n const content = event.message?.content || [];\n for (const block of content) {\n if (block.type === \"text\") {\n events.push({\n type: \"text\",\n content: block.text,\n });\n } else if (block.type === \"tool_use\") {\n events.push({\n type: \"tool_use\",\n toolName: block.name,\n toolInput: block.input,\n });\n }\n }\n } else if (event.type === \"result\") {\n events.push({\n type: \"tool_result\",\n toolResult: event.result,\n });\n } else if (event.type === \"error\") {\n events.push({\n type: \"error\",\n error: event.message || \"Unknown error\",\n });\n }\n } catch {\n // Non-JSON line - treat as plain text\n events.push({\n type: \"text\",\n content: line,\n });\n }\n }\n\n return events;\n }\n\n /**\n * Monitor process execution and accumulate results\n *\n * Collects all output, parses events, and resolves when process completes.\n */\n private monitorProcess(\n proc: ReturnType<typeof spawn>,\n _conversationId: string\n ): Promise<AgentProcessResult> {\n return new Promise((resolve) => {\n let buffer = \"\";\n const allEvents: ChatEvent[] = [];\n let fullResponse = \"\";\n let errorMessage: string | undefined;\n\n // Collect stdout\n proc.stdout?.on(\"data\", (data: Buffer) => {\n const chunk = data.toString();\n buffer += chunk;\n\n // Process complete lines\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n const lineChunk = lines.join(\"\\n\");\n if (lineChunk) {\n const events = this.parseOutput(lineChunk);\n allEvents.push(...events);\n\n // Accumulate text content\n for (const event of events) {\n if (event.type === \"text\" && event.content) {\n fullResponse += event.content;\n }\n }\n }\n });\n\n // Collect stderr for errors\n proc.stderr?.on(\"data\", (data: Buffer) => {\n const error = data.toString();\n if (error.trim()) {\n errorMessage = error;\n }\n });\n\n // Handle process completion\n proc.on(\"close\", (exitCode) => {\n // Process any remaining buffer\n if (buffer.trim()) {\n const events = this.parseOutput(buffer);\n allEvents.push(...events);\n for (const event of events) {\n if (event.type === \"text\" && event.content) {\n fullResponse += event.content;\n }\n }\n }\n\n // Add completion event\n allEvents.push({ type: \"complete\" });\n\n resolve({\n exitCode: exitCode || 0,\n fullResponse,\n events: allEvents,\n error: errorMessage,\n });\n });\n\n // Handle process errors\n proc.on(\"error\", (error) => {\n allEvents.push({\n type: \"error\",\n error: error.message,\n });\n\n resolve({\n exitCode: 1,\n fullResponse,\n events: allEvents,\n error: error.message,\n });\n });\n });\n }\n}\n"],
|
|
5
|
-
"mappings": "AAQA,SAAS,WAAW,aAAa;AAkB3B,MAAO,gBAAe;EACjB,OAAO;EACP,UAAU;;;;;EAMnB,MAAM,cAAW;AACf,QAAI;AAEF,YAAM,eADY,QAAQ,aAAa,UACN,UAAU;AAM3C,aAJe,UAAU,cAAc,CAAC,KAAK,OAAO,GAAG;QACrD,OAAO;QACP,UAAU;OACX,EACa,WAAW;IAC3B,QAAQ;AACN,aAAO;IACT;EACF;;;;;;;EAQA,MAAM,SAA0B;AAC9B,UAAM,EAAE,KAAK,SAAS,YAAY,gBAAgB,iBAAiB,CAAA,EAAE,IAAK,SAGpE,iBAAiB,UAAU,KAAK,IAAG,CAAE,IAAI,KAAK,OAAM,EAAG,SAAS,EAAE,EAAE,UAAU,GAAG,CAAC,CAAC,IAGnF,OAAO;MACX;MACA;MACA;MACA;MACA;MACA;MACA;MACA,GAAG;OAIC,OAAO,MAAM,KAAK,SAAS,MAAM;MACrC;MACA,OAAO,CAAC,QAAQ,QAAQ,MAAM;KAC/B;AAGD,SAAK,MAAM,MAAM,OAAO,GACxB,KAAK,MAAM,IAAG;AAGd,UAAM,aAAa,KAAK,eAAe,MAAM,cAAc;AAE3D,WAAO;MACL,SAAS;MACT;MACA;;EAEJ;;;;;;;;;;EAWA,YAAY,OAAa;AACvB,UAAM,SAAsB,CAAA,GACtB,QAAQ,MAAM,MAAM;CAAI;AAE9B,eAAW,QAAQ;AACjB,UAAK,KAAK,KAAI;AAEd,YAAI;AACF,gBAAM,QAAQ,KAAK,MAAM,IAAI;AAE7B,cAAI,MAAM,SAAS,aAAa;AAC9B,kBAAM,UAAU,MAA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ACxB,qBAAW,SAAS;AAClB,YAAI,MAAM,SAAS,UAAU,MAAM,YACjC,gBAAgB,MAAM;QAG5B;AAGA,kBAAU,KAAK,EAAE,MAAM,WAAU,CAAE,GAEnC,QAAQ;UACN,UAAU,YAAY;UACtB;UACA,QAAQ;UACR,OAAO;SACR;MACH,CAAC,GAGD,KAAK,GAAG,SAAS,CAAC,UAAS;AACzB,kBAAU,KAAK;UACb,MAAM;UACN,OAAO,MAAM;SACd,GAED,QAAQ;UACN,UAAU;UACV;UACA,QAAQ;UACR,OAAO,MAAM;SACd;MACH,CAAC;IACH,CAAC;EACH;;",
|
|
4
|
+
"sourcesContent": ["/**\n * Claude Code CLI Agent Implementation\n *\n * Integrates Claude Code CLI (https://claude.ai) for AI-powered\n * architecture model exploration. Supports the dr-architect agent\n * with streaming JSON output parsing.\n */\n\nimport { spawnSync, spawn } from \"child_process\";\nimport {\n CodingAgent,\n AgentProcess,\n ChatEvent,\n SpawnAgentOptions,\n AgentProcessResult,\n} from \"./types.js\";\n\n/**\n * Claude Code CLI agent implementation\n *\n * Uses `claude` command with:\n * - dr-architect agent for DR-specific knowledge\n * - --output-format stream-json for structured events\n * - stdin for message input\n * - stdout for JSON event stream\n */\nexport class ClaudeCodeAgent implements CodingAgent {\n readonly name = \"Claude Code\";\n readonly command = \"claude\";\n\n /**\n * Check if Claude Code CLI is available\n * Uses 'which' on Unix-like systems or 'where' on Windows\n */\n async isAvailable(): Promise<boolean> {\n try {\n const isWindows = process.platform === \"win32\";\n const checkCommand = isWindows ? \"where\" : \"which\";\n\n const result = spawnSync(checkCommand, [this.command], {\n stdio: \"pipe\",\n encoding: \"utf-8\",\n });\n return result.status === 0;\n } catch {\n return false;\n }\n }\n\n /**\n * Spawn Claude Code CLI process\n *\n * Creates subprocess with dr-architect agent, sends initial message via stdin,\n * and monitors stdout for JSON events.\n */\n spawn(options: SpawnAgentOptions): AgentProcess {\n const { cwd, message, agentName = \"dr-architect\", additionalArgs = [] } = options;\n\n // Generate conversation ID\n const conversationId = `claude-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n\n // Build command arguments\n const args = [\n \"--agent\",\n agentName,\n \"--print\",\n \"--dangerously-skip-permissions\",\n \"--verbose\",\n \"--output-format\",\n \"stream-json\",\n ...additionalArgs,\n ];\n\n // Spawn process\n const proc = spawn(this.command, args, {\n cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n\n // Handle stdin errors (e.g., EPIPE when process exits unexpectedly)\n proc.stdin?.on(\"error\", (error: NodeJS.ErrnoException) => {\n if (error.code !== \"EPIPE\") {\n console.error(\n `Unexpected stdin error (${error.code}): ${error.message}`\n );\n }\n // Silently ignore EPIPE - this is expected when process exits before stdin write completes\n });\n\n // Send initial message via stdin\n proc.stdin.write(message);\n proc.stdin.end();\n\n // Set up completion promise\n const completion = this.monitorProcess(proc, conversationId);\n\n return {\n process: proc,\n conversationId,\n completion,\n };\n }\n\n /**\n * Parse Claude Code JSON output into chat events\n *\n * Claude Code outputs line-delimited JSON events:\n * - {\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"...\"}]}}\n * - {\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"tool_use\",\"name\":\"...\"}]}}\n *\n * Non-JSON lines are treated as plain text output.\n */\n parseOutput(chunk: string): ChatEvent[] {\n const events: ChatEvent[] = [];\n const lines = chunk.split(\"\\n\");\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n const event = JSON.parse(line);\n\n if (event.type === \"assistant\") {\n const content = event.message?.content || [];\n for (const block of content) {\n if (block.type === \"text\") {\n events.push({\n type: \"text\",\n content: block.text,\n });\n } else if (block.type === \"tool_use\") {\n events.push({\n type: \"tool_use\",\n toolName: block.name,\n toolInput: block.input,\n });\n }\n }\n } else if (event.type === \"result\") {\n events.push({\n type: \"tool_result\",\n toolResult: event.result,\n });\n } else if (event.type === \"error\") {\n events.push({\n type: \"error\",\n error: event.message || \"Unknown error\",\n });\n }\n } catch {\n // Non-JSON line - treat as plain text\n events.push({\n type: \"text\",\n content: line,\n });\n }\n }\n\n return events;\n }\n\n /**\n * Monitor process execution and accumulate results\n *\n * Collects all output, parses events, and resolves when process completes.\n */\n private monitorProcess(\n proc: ReturnType<typeof spawn>,\n _conversationId: string\n ): Promise<AgentProcessResult> {\n return new Promise((resolve) => {\n let buffer = \"\";\n const allEvents: ChatEvent[] = [];\n let fullResponse = \"\";\n let errorMessage: string | undefined;\n\n // Collect stdout\n proc.stdout?.on(\"data\", (data: Buffer) => {\n const chunk = data.toString();\n buffer += chunk;\n\n // Process complete lines\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n const lineChunk = lines.join(\"\\n\");\n if (lineChunk) {\n const events = this.parseOutput(lineChunk);\n allEvents.push(...events);\n\n // Accumulate text content\n for (const event of events) {\n if (event.type === \"text\" && event.content) {\n fullResponse += event.content;\n }\n }\n }\n });\n\n // Collect stderr for errors\n proc.stderr?.on(\"data\", (data: Buffer) => {\n const error = data.toString();\n if (error.trim()) {\n errorMessage = error;\n }\n });\n\n // Handle process completion\n proc.on(\"close\", (exitCode) => {\n // Process any remaining buffer\n if (buffer.trim()) {\n const events = this.parseOutput(buffer);\n allEvents.push(...events);\n for (const event of events) {\n if (event.type === \"text\" && event.content) {\n fullResponse += event.content;\n }\n }\n }\n\n // Add completion event\n allEvents.push({ type: \"complete\" });\n\n resolve({\n exitCode: exitCode || 0,\n fullResponse,\n events: allEvents,\n error: errorMessage,\n });\n });\n\n // Handle process errors\n proc.on(\"error\", (error) => {\n allEvents.push({\n type: \"error\",\n error: error.message,\n });\n\n resolve({\n exitCode: 1,\n fullResponse,\n events: allEvents,\n error: error.message,\n });\n });\n });\n }\n}\n"],
|
|
5
|
+
"mappings": "AAQA,SAAS,WAAW,aAAa;AAkB3B,MAAO,gBAAe;EACjB,OAAO;EACP,UAAU;;;;;EAMnB,MAAM,cAAW;AACf,QAAI;AAEF,YAAM,eADY,QAAQ,aAAa,UACN,UA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B,kBAAU,KAAK;UACb,MAAM;UACN,OAAO,MAAM;SACd,GAED,QAAQ;UACN,UAAU;UACV;UACA,QAAQ;UACR,OAAO,MAAM;SACd;MACH,CAAC;IACH,CAAC;EACH;;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -3,6 +3,7 @@ import { spawnSync, spawn } from "child_process";
|
|
|
3
3
|
import ansis from "ansis";
|
|
4
4
|
import { getChatLogger } from "../utils/chat-logger.js";
|
|
5
5
|
import { getErrorMessage } from "../utils/errors.js";
|
|
6
|
+
import { formatForClaudeCode } from "./default-permissions.js";
|
|
6
7
|
import { isTelemetryEnabled, startSpan, endSpan, emitLog, SeverityNumber } from "../telemetry/index.js";
|
|
7
8
|
class ClaudeCodeClient extends BaseChatClient {
|
|
8
9
|
isFirstMessage = !0;
|
|
@@ -191,7 +192,7 @@ class ClaudeCodeClient extends BaseChatClient {
|
|
|
191
192
|
*/
|
|
192
193
|
getProcessArgs(options, isFirstMessage = !0) {
|
|
193
194
|
const args = ["--print"];
|
|
194
|
-
return options?.withDanger
|
|
195
|
+
return options?.withDanger ? args.push("--dangerously-skip-permissions") : args.push("--allowedTools", formatForClaudeCode()), args.push("--verbose", "--output-format", "stream-json"), isFirstMessage && options?.sessionId ? args.push("--session-id", options.sessionId) : !isFirstMessage && options?.sessionId && args.push("--resume", options.sessionId), options?.agent && args.unshift("--agent", options.agent), args;
|
|
195
196
|
}
|
|
196
197
|
/**
|
|
197
198
|
* Spawn the Claude Code CLI process
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/coding-agents/claude-code-client.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Claude Code CLI Client\n *\n * Implements chat functionality using Claude Code CLI subprocess.\n * Uses structured JSON streaming output for reliable parsing.\n *\n * Key features:\n * - Availability detection via `which claude`\n * - JSON event stream parsing\n * - Agent support (dr-architect)\n * - Tool use detection and display\n * - Session management per process invocation\n */\n\nimport { BaseChatClient, ChatOptions } from \"./base-chat-client.js\";\nimport { spawnSync, spawn, ChildProcess } from \"child_process\";\nimport ansis from \"ansis\";\nimport { getChatLogger } from \"../utils/chat-logger.js\";\nimport { getErrorMessage } from \"../utils/errors.js\";\nimport {\n isTelemetryEnabled,\n startSpan,\n endSpan,\n emitLog,\n SeverityNumber,\n} from \"../telemetry/index.js\";\n\n/**\n * Claude Code CLI event types\n */\ninterface ClaudeEvent {\n type: string;\n message?: {\n content?: Array<{\n type: string;\n text?: string;\n name?: string;\n }>;\n };\n}\n\n/**\n * Claude Code CLI Client\n */\nexport class ClaudeCodeClient extends BaseChatClient {\n private isFirstMessage: boolean = true; // Track first message for session management\n\n /**\n * Check if Claude Code CLI is available\n */\n async isAvailable(): Promise<boolean> {\n const span = isTelemetryEnabled ? startSpan(\"claude-code.availability-check\") : null;\n\n try {\n const result = spawnSync(\"which\", [\"claude\"], {\n stdio: \"pipe\",\n encoding: \"utf-8\",\n });\n const available = result.status === 0;\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"client.available\", available);\n (span as any).setAttribute(\"client.name\", \"Claude Code\");\n (span as any).setStatus({ code: 0 });\n }\n\n return available;\n } catch (error) {\n if (isTelemetryEnabled && span) {\n (span as any).recordException(error as Error);\n (span as any).setAttribute(\"client.available\", false);\n (span as any).setAttribute(\"client.name\", \"Claude Code\");\n (span as any).setStatus({\n code: 2,\n message: getErrorMessage(error),\n });\n }\n return false;\n } finally {\n endSpan(span);\n }\n }\n\n /**\n * Send a message to Claude Code CLI and stream the response\n * @param message The user's message\n * @param options Chat options\n */\n async sendMessage(message: string, options?: ChatOptions): Promise<string> {\n const span = isTelemetryEnabled\n ? startSpan(\"claude-code.send-message\", {\n \"message.length\": message.length,\n \"message.content\": message.substring(0, 500), // First 500 chars for context\n \"client.name\": \"Claude Code\",\n \"client.agent\": options?.agent,\n \"client.withDanger\": options?.withDanger === true,\n \"client.isFirstMessage\": this.isFirstMessage,\n \"options.workingDirectory\": options?.workingDirectory,\n \"options.sessionId\": options?.sessionId,\n \"client.workingDirectory\": options?.workingDirectory,\n \"client.sessionId\": options?.sessionId,\n })\n : null;\n\n // Log the user message\n const logger = getChatLogger();\n if (logger) {\n await logger.logUserMessage(message, {\n client: \"Claude Code\",\n agent: options?.agent,\n });\n }\n\n // Create NEW internal session for this message invocation\n // The sessionId in options (if provided) is passed to Claude CLI subprocess\n // to maintain conversation continuity at the Claude CLI level, not internally\n this.createSession();\n this.updateSessionTimestamp();\n\n // Capture isFirstMessage state before spawning, then mark subsequent messages as not-first\n const currentIsFirst = this.isFirstMessage;\n if (this.isFirstMessage) {\n this.isFirstMessage = false;\n }\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"client.sessionCreated\", true);\n (span as any).setAttribute(\n \"client.internalSessionId\",\n this.getCurrentSession()?.id ?? \"none\"\n );\n }\n\n return new Promise((resolve, reject) => {\n const proc = this.spawnClaudeProcess(message, options, currentIsFirst);\n\n let buffer = \"\";\n let assistantOutput = \"\";\n let eventCount = 0;\n let toolUseCount = 0;\n\n // Handle stdout - JSON event stream\n proc.stdout?.on(\"data\", (data: Buffer) => {\n const chunk = data.toString();\n buffer += chunk;\n\n // Process complete lines (each line is a JSON event)\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n const event: ClaudeEvent = JSON.parse(line);\n eventCount++;\n const result = this.handleClaudeEvent(event, options?.outputStream);\n if (result.output) {\n assistantOutput += result.output;\n }\n if (result.usedTool) {\n toolUseCount++;\n }\n } catch (error) {\n // Log JSON parse failure - this indicates a protocol mismatch or CLI bug\n if (isTelemetryEnabled && span) {\n emitLog(SeverityNumber.WARN, \"Failed to parse Claude event JSON\", {\n \"error.message\": getErrorMessage(error),\n \"event.rawLine\": line.substring(0, 200),\n \"event.lineLength\": line.length,\n });\n }\n if (logger) {\n void logger.logError(\n `Failed to parse Claude event: ${getErrorMessage(error)}`,\n {\n source: \"json-parse\",\n client: \"Claude Code\",\n rawLine: line.substring(0, 200),\n }\n );\n }\n\n // Non-JSON line \u2014 route through the same output stream as text content\n const outStream = options?.outputStream !== null\n ? (options?.outputStream ?? process.stdout)\n : null;\n if (outStream) {\n outStream.write(line + \"\\n\");\n }\n assistantOutput += line + \"\\n\";\n }\n }\n });\n\n // Handle stderr - always log for debugging, with severity detection\n proc.stderr?.on(\"data\", (data: Buffer) => {\n const stderrText = data.toString().trim();\n if (!stderrText) return; // Skip empty lines\n\n // Determine severity based on content patterns\n const isError = /\\b(error|failed|exception|fatal|critical)\\b/i.test(stderrText);\n const isWarning = /\\b(warning|warn|deprecated)\\b/i.test(stderrText);\n\n // Always log to telemetry and ChatLogger for debugging\n if (isTelemetryEnabled && span) {\n const severity = isError\n ? SeverityNumber.ERROR\n : isWarning\n ? SeverityNumber.WARN\n : SeverityNumber.DEBUG;\n emitLog(severity, \"Claude Code stderr output\", {\n \"stderr.source\": \"claude-cli\",\n \"stderr.text\": stderrText.substring(0, 500),\n \"stderr.isError\": isError,\n \"stderr.isWarning\": isWarning,\n });\n }\n\n if (logger) {\n if (isError) {\n void logger.logError(stderrText, {\n source: \"stderr\",\n client: \"Claude Code\",\n });\n } else {\n // Log non-errors as events for complete session history\n void logger.logEvent(\"stderr_output\", {\n text: stderrText.substring(0, 500),\n isWarning,\n client: \"Claude Code\",\n });\n }\n }\n\n // Display errors and warnings to user\n if (isError || isWarning) {\n const prefix = isError ? \"[ERROR]\" : \"[WARNING]\";\n process.stderr.write(`${ansis.yellow(prefix)} ${stderrText}\\n`);\n }\n });\n\n // Handle errors\n proc.on(\"error\", (error) => {\n const errorContext = {\n \"error.message\": error.message,\n \"error.stack\": error.stack,\n \"error.code\": (error as any).code, // ENOENT, EACCES, etc.\n \"process.command\": \"claude\",\n \"process.args\": JSON.stringify(this.getProcessArgs(options)),\n \"process.sessionId\": options?.sessionId,\n \"process.agent\": options?.agent,\n \"process.workingDirectory\": options?.workingDirectory || process.cwd(),\n \"message.length\": message.length,\n \"message.preview\": message.substring(0, 100),\n };\n\n if (isTelemetryEnabled && span) {\n emitLog(SeverityNumber.ERROR, \"Claude Code process error\", errorContext);\n (span as any).recordException(error);\n }\n if (logger) {\n void logger.logError(\n `Claude process failed to spawn or encountered error: ${error.message}`,\n {\n source: \"process\",\n client: \"Claude Code\",\n ...errorContext,\n }\n );\n }\n\n // Log to console for immediate visibility\n console.error(\"[ClaudeCodeClient] Process error:\", error.message);\n console.error(\n \"[ClaudeCodeClient] Command:\",\n \"claude\",\n this.getProcessArgs(options).join(\" \")\n );\n if ((error as any).code === \"ENOENT\") {\n console.error(\n \"[ClaudeCodeClient] Claude CLI not found - ensure it is installed and in PATH\"\n );\n } else if ((error as any).code === \"EACCES\") {\n console.error(\n \"[ClaudeCodeClient] Permission denied - check Claude CLI executable permissions\"\n );\n }\n\n endSpan(span);\n reject(error);\n });\n\n // Handle process exit\n proc.on(\"close\", (exitCode) => {\n // Print any remaining buffer\n if (buffer.trim()) {\n try {\n const event: ClaudeEvent = JSON.parse(buffer);\n eventCount++;\n const result = this.handleClaudeEvent(event, options?.outputStream);\n if (result.output) {\n assistantOutput += result.output;\n }\n if (result.usedTool) {\n toolUseCount++;\n }\n } catch (error) {\n // Log JSON parse failure for remaining buffer\n if (isTelemetryEnabled && span) {\n emitLog(SeverityNumber.WARN, \"Failed to parse remaining buffer as JSON\", {\n \"error.message\": getErrorMessage(error),\n \"buffer.content\": buffer.substring(0, 200),\n \"buffer.length\": buffer.length,\n });\n }\n if (logger) {\n void logger.logError(\n `Failed to parse remaining buffer: ${getErrorMessage(error)}`,\n {\n source: \"json-parse-buffer\",\n client: \"Claude Code\",\n bufferContent: buffer.substring(0, 200),\n }\n );\n }\n\n const outStream = options?.outputStream !== null\n ? (options?.outputStream ?? process.stdout)\n : null;\n if (outStream) {\n outStream.write(buffer);\n }\n assistantOutput += buffer;\n }\n }\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"client.eventCount\", eventCount);\n (span as any).setAttribute(\"client.toolUseCount\", toolUseCount);\n (span as any).setAttribute(\"client.outputLength\", assistantOutput.length);\n (span as any).setAttribute(\"client.exitCode\", exitCode || 0);\n (span as any).setAttribute(\"response.content\", assistantOutput.substring(0, 1000)); // First 1000 chars\n (span as any).setAttribute(\"response.preview\", assistantOutput.substring(0, 200)); // Short preview\n }\n\n if (exitCode === 0) {\n // Log assistant message if we got output\n if (logger && assistantOutput.trim()) {\n void logger.logAssistantMessage(assistantOutput, {\n client: \"Claude Code\",\n });\n }\n if (isTelemetryEnabled && span) {\n (span as any).setStatus({ code: 0 });\n }\n endSpan(span);\n resolve(assistantOutput);\n } else {\n const errorMsg = `Claude process exited with code ${exitCode}`;\n if (isTelemetryEnabled && span) {\n emitLog(SeverityNumber.ERROR, \"Claude Code process exited with error\", {\n \"process.exitCode\": exitCode,\n });\n (span as any).setStatus({ code: 2, message: errorMsg });\n }\n if (logger) {\n void logger.logError(errorMsg, {\n exitCode,\n client: \"Claude Code\",\n });\n }\n endSpan(span);\n reject(new Error(errorMsg));\n }\n });\n });\n }\n\n /**\n * Handle a Claude Code event from the JSON stream\n * @param event The Claude event to handle\n * @param outputStream Stream for text output. null = suppress, undefined = stdout.\n * @returns Object with output text and tool use flag\n */\n private handleClaudeEvent(\n event: ClaudeEvent,\n outputStream?: NodeJS.WriteStream | null\n ): { output: string; usedTool: boolean } {\n let output = \"\";\n let usedTool = false;\n\n if (event.type === \"assistant\") {\n const content = event.message?.content || [];\n for (const block of content) {\n if (block.type === \"text\") {\n const text = block.text || \"\";\n if (outputStream !== null) {\n (outputStream ?? process.stdout).write(text);\n }\n output += text;\n } else if (block.type === \"tool_use\") {\n usedTool = true;\n // Tool notifications are always progress indicators \u2014 always stderr.\n // Not added to output: they are display-only and would corrupt JSON parsing.\n process.stderr.write(ansis.dim(`\\n[Using tool: ${block.name}]\\n`));\n }\n }\n }\n\n return { output, usedTool };\n }\n\n /**\n * Get the process arguments that would be used for spawning\n * @param options Chat options\n * @param isFirstMessage Whether this is the first message in the chat session\n * @returns Array of command line arguments\n */\n private getProcessArgs(options?: ChatOptions, isFirstMessage: boolean = true): string[] {\n const args = [\"--print\"];\n\n // Add dangerously-skip-permissions flag if withDanger is enabled\n if (options?.withDanger) {\n args.push(\"--dangerously-skip-permissions\");\n }\n\n args.push(\"--verbose\", \"--output-format\", \"stream-json\");\n\n // Session management:\n // - First message: Start with our session ID for traceability\n // - Subsequent messages: Resume that specific session\n if (isFirstMessage && options?.sessionId) {\n args.push(\"--session-id\", options.sessionId);\n } else if (!isFirstMessage && options?.sessionId) {\n args.push(\"--resume\", options.sessionId);\n }\n\n // Add agent if specified\n if (options?.agent) {\n args.unshift(\"--agent\", options.agent);\n }\n\n return args;\n }\n\n /**\n * Spawn the Claude Code CLI process\n * @param message The message to send\n * @param options Chat options\n * @param isFirstMessage Whether this is the first message in the chat session\n * @returns The spawned child process\n */\n private spawnClaudeProcess(\n message: string,\n options?: ChatOptions,\n isFirstMessage: boolean = true\n ): ChildProcess {\n const span = isTelemetryEnabled ? startSpan(\"claude-code.spawn-process\") : null;\n\n try {\n const args = this.getProcessArgs(options, isFirstMessage);\n const cwd = options?.workingDirectory || process.cwd();\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"process.command\", \"claude\");\n (span as any).setAttribute(\"process.args\", args.join(\" \"));\n (span as any).setAttribute(\"process.argCount\", args.length);\n (span as any).setAttribute(\"process.isFirstMessage\", isFirstMessage);\n (span as any).setAttribute(\"process.hasResume\", args.includes(\"--resume\"));\n (span as any).setAttribute(\"process.hasSessionId\", args.includes(\"--session-id\"));\n (span as any).setAttribute(\"process.hasAgent\", !!options?.agent);\n (span as any).setAttribute(\"process.agent\", options?.agent);\n (span as any).setAttribute(\"process.withDanger\", options?.withDanger === true);\n (span as any).setAttribute(\"process.workingDirectory\", cwd);\n (span as any).setAttribute(\"process.messageLength\", message.length);\n }\n\n // Log the command that's being executed\n const logger = getChatLogger();\n if (logger) {\n void logger.logCommand(\"claude\", args, {\n client: \"Claude Code\",\n workingDirectory: cwd,\n agent: options?.agent,\n withDanger: options?.withDanger || false,\n messageLength: message.length,\n hasVerboseFlag: args.includes(\"--verbose\"),\n hasOutputFormat: args.includes(\"--output-format\"),\n sessionId: options?.sessionId,\n });\n }\n\n // Strip CLAUDECODE from the environment so Claude doesn't refuse to run\n // inside an existing Claude Code session (nested session protection).\n const env = { ...process.env };\n delete env.CLAUDECODE;\n\n const proc = spawn(\"claude\", args, {\n cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env,\n });\n\n // Send message via stdin\n proc.stdin?.write(message);\n proc.stdin?.end();\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"process.spawned\", true);\n (span as any).setAttribute(\"process.pid\", proc.pid);\n (span as any).setStatus({ code: 0 });\n }\n\n return proc;\n } catch (error) {\n if (isTelemetryEnabled && span) {\n (span as any).recordException(error as Error);\n (span as any).setStatus({\n code: 2,\n message: getErrorMessage(error),\n });\n }\n throw error;\n } finally {\n endSpan(span);\n }\n }\n\n /**\n * Get the name of this client\n */\n getClientName(): string {\n return \"Claude Code\";\n }\n}\n"],
|
|
5
|
-
"mappings": "AAcA,SAAS,sBAAmC;AAC5C,SAAS,WAAW,aAA2B;AAC/C,OAAO,WAAW;AAClB,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SACE,oBACA,WACA,SACA,SACA,sBACK;AAmBD,MAAO,yBAAyB,eAAc;EAC1C,iBAA0B;;;;;EAKlC,MAAM,cAAW;AACf,UAAM,OAAO,qBAAqB,UAAU,gCAAgC,IAAI;AAEhF,QAAI;AAKF,YAAM,YAJS,UAAU,SAAS,CAAC,QAAQ,GAAG;QAC5C,OAAO;QACP,UAAU;OACX,EACwB,WAAW;AAEpC,aAAI,sBAAsB,SACvB,KAAa,aAAa,oBAAoB,SAAS,GACvD,KAAa,aAAa,eAAe,aAAa,GACtD,KAAa,UAAU,EAAE,MAAM,EAAC,CAAE,IAG9B;IACT,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BAAgB,QAAQ,QAAQ,MAAM,IAAI,GAE7C,UAAU;QACZ,MAAO,CAAI,MAAM,SAAS,eACxB,WAAW,IAGX,QAAQ,OAAO,MAAM,MAAM,IAAI;eAAkB,MAAM,IAAI;CAAK,CAAC;IAGvE;AAEA,WAAO,EAAE,QAAQ,SAAQ;EAC3B;;;;;;;EAQQ,eAAe,SAAuB,iBAA0B,IAAI;AAC1E,UAAM,OAAO,CAAC,SAAS;AAGvB,WAAI,SAAS,
|
|
4
|
+
"sourcesContent": ["/**\n * Claude Code CLI Client\n *\n * Implements chat functionality using Claude Code CLI subprocess.\n * Uses structured JSON streaming output for reliable parsing.\n *\n * Key features:\n * - Availability detection via `which claude`\n * - JSON event stream parsing\n * - Agent support (dr-architect)\n * - Tool use detection and display\n * - Session management per process invocation\n */\n\nimport { BaseChatClient, ChatOptions } from \"./base-chat-client.js\";\nimport { spawnSync, spawn, ChildProcess } from \"child_process\";\nimport ansis from \"ansis\";\nimport { getChatLogger } from \"../utils/chat-logger.js\";\nimport { getErrorMessage } from \"../utils/errors.js\";\nimport { formatForClaudeCode } from \"./default-permissions.js\";\nimport {\n isTelemetryEnabled,\n startSpan,\n endSpan,\n emitLog,\n SeverityNumber,\n} from \"../telemetry/index.js\";\n\n/**\n * Claude Code CLI event types\n */\ninterface ClaudeEvent {\n type: string;\n message?: {\n content?: Array<{\n type: string;\n text?: string;\n name?: string;\n }>;\n };\n}\n\n/**\n * Claude Code CLI Client\n */\nexport class ClaudeCodeClient extends BaseChatClient {\n private isFirstMessage: boolean = true; // Track first message for session management\n\n /**\n * Check if Claude Code CLI is available\n */\n async isAvailable(): Promise<boolean> {\n const span = isTelemetryEnabled ? startSpan(\"claude-code.availability-check\") : null;\n\n try {\n const result = spawnSync(\"which\", [\"claude\"], {\n stdio: \"pipe\",\n encoding: \"utf-8\",\n });\n const available = result.status === 0;\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"client.available\", available);\n (span as any).setAttribute(\"client.name\", \"Claude Code\");\n (span as any).setStatus({ code: 0 });\n }\n\n return available;\n } catch (error) {\n if (isTelemetryEnabled && span) {\n (span as any).recordException(error as Error);\n (span as any).setAttribute(\"client.available\", false);\n (span as any).setAttribute(\"client.name\", \"Claude Code\");\n (span as any).setStatus({\n code: 2,\n message: getErrorMessage(error),\n });\n }\n return false;\n } finally {\n endSpan(span);\n }\n }\n\n /**\n * Send a message to Claude Code CLI and stream the response\n * @param message The user's message\n * @param options Chat options\n */\n async sendMessage(message: string, options?: ChatOptions): Promise<string> {\n const span = isTelemetryEnabled\n ? startSpan(\"claude-code.send-message\", {\n \"message.length\": message.length,\n \"message.content\": message.substring(0, 500), // First 500 chars for context\n \"client.name\": \"Claude Code\",\n \"client.agent\": options?.agent,\n \"client.withDanger\": options?.withDanger === true,\n \"client.isFirstMessage\": this.isFirstMessage,\n \"options.workingDirectory\": options?.workingDirectory,\n \"options.sessionId\": options?.sessionId,\n \"client.workingDirectory\": options?.workingDirectory,\n \"client.sessionId\": options?.sessionId,\n })\n : null;\n\n // Log the user message\n const logger = getChatLogger();\n if (logger) {\n await logger.logUserMessage(message, {\n client: \"Claude Code\",\n agent: options?.agent,\n });\n }\n\n // Create NEW internal session for this message invocation\n // The sessionId in options (if provided) is passed to Claude CLI subprocess\n // to maintain conversation continuity at the Claude CLI level, not internally\n this.createSession();\n this.updateSessionTimestamp();\n\n // Capture isFirstMessage state before spawning, then mark subsequent messages as not-first\n const currentIsFirst = this.isFirstMessage;\n if (this.isFirstMessage) {\n this.isFirstMessage = false;\n }\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"client.sessionCreated\", true);\n (span as any).setAttribute(\n \"client.internalSessionId\",\n this.getCurrentSession()?.id ?? \"none\"\n );\n }\n\n return new Promise((resolve, reject) => {\n const proc = this.spawnClaudeProcess(message, options, currentIsFirst);\n\n let buffer = \"\";\n let assistantOutput = \"\";\n let eventCount = 0;\n let toolUseCount = 0;\n\n // Handle stdout - JSON event stream\n proc.stdout?.on(\"data\", (data: Buffer) => {\n const chunk = data.toString();\n buffer += chunk;\n\n // Process complete lines (each line is a JSON event)\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n const event: ClaudeEvent = JSON.parse(line);\n eventCount++;\n const result = this.handleClaudeEvent(event, options?.outputStream);\n if (result.output) {\n assistantOutput += result.output;\n }\n if (result.usedTool) {\n toolUseCount++;\n }\n } catch (error) {\n // Log JSON parse failure - this indicates a protocol mismatch or CLI bug\n if (isTelemetryEnabled && span) {\n emitLog(SeverityNumber.WARN, \"Failed to parse Claude event JSON\", {\n \"error.message\": getErrorMessage(error),\n \"event.rawLine\": line.substring(0, 200),\n \"event.lineLength\": line.length,\n });\n }\n if (logger) {\n void logger.logError(\n `Failed to parse Claude event: ${getErrorMessage(error)}`,\n {\n source: \"json-parse\",\n client: \"Claude Code\",\n rawLine: line.substring(0, 200),\n }\n );\n }\n\n // Non-JSON line \u2014 route through the same output stream as text content\n const outStream = options?.outputStream !== null\n ? (options?.outputStream ?? process.stdout)\n : null;\n if (outStream) {\n outStream.write(line + \"\\n\");\n }\n assistantOutput += line + \"\\n\";\n }\n }\n });\n\n // Handle stderr - always log for debugging, with severity detection\n proc.stderr?.on(\"data\", (data: Buffer) => {\n const stderrText = data.toString().trim();\n if (!stderrText) return; // Skip empty lines\n\n // Determine severity based on content patterns\n const isError = /\\b(error|failed|exception|fatal|critical)\\b/i.test(stderrText);\n const isWarning = /\\b(warning|warn|deprecated)\\b/i.test(stderrText);\n\n // Always log to telemetry and ChatLogger for debugging\n if (isTelemetryEnabled && span) {\n const severity = isError\n ? SeverityNumber.ERROR\n : isWarning\n ? SeverityNumber.WARN\n : SeverityNumber.DEBUG;\n emitLog(severity, \"Claude Code stderr output\", {\n \"stderr.source\": \"claude-cli\",\n \"stderr.text\": stderrText.substring(0, 500),\n \"stderr.isError\": isError,\n \"stderr.isWarning\": isWarning,\n });\n }\n\n if (logger) {\n if (isError) {\n void logger.logError(stderrText, {\n source: \"stderr\",\n client: \"Claude Code\",\n });\n } else {\n // Log non-errors as events for complete session history\n void logger.logEvent(\"stderr_output\", {\n text: stderrText.substring(0, 500),\n isWarning,\n client: \"Claude Code\",\n });\n }\n }\n\n // Display errors and warnings to user\n if (isError || isWarning) {\n const prefix = isError ? \"[ERROR]\" : \"[WARNING]\";\n process.stderr.write(`${ansis.yellow(prefix)} ${stderrText}\\n`);\n }\n });\n\n // Handle errors\n proc.on(\"error\", (error) => {\n const errorContext = {\n \"error.message\": error.message,\n \"error.stack\": error.stack,\n \"error.code\": (error as any).code, // ENOENT, EACCES, etc.\n \"process.command\": \"claude\",\n \"process.args\": JSON.stringify(this.getProcessArgs(options)),\n \"process.sessionId\": options?.sessionId,\n \"process.agent\": options?.agent,\n \"process.workingDirectory\": options?.workingDirectory || process.cwd(),\n \"message.length\": message.length,\n \"message.preview\": message.substring(0, 100),\n };\n\n if (isTelemetryEnabled && span) {\n emitLog(SeverityNumber.ERROR, \"Claude Code process error\", errorContext);\n (span as any).recordException(error);\n }\n if (logger) {\n void logger.logError(\n `Claude process failed to spawn or encountered error: ${error.message}`,\n {\n source: \"process\",\n client: \"Claude Code\",\n ...errorContext,\n }\n );\n }\n\n // Log to console for immediate visibility\n console.error(\"[ClaudeCodeClient] Process error:\", error.message);\n console.error(\n \"[ClaudeCodeClient] Command:\",\n \"claude\",\n this.getProcessArgs(options).join(\" \")\n );\n if ((error as any).code === \"ENOENT\") {\n console.error(\n \"[ClaudeCodeClient] Claude CLI not found - ensure it is installed and in PATH\"\n );\n } else if ((error as any).code === \"EACCES\") {\n console.error(\n \"[ClaudeCodeClient] Permission denied - check Claude CLI executable permissions\"\n );\n }\n\n endSpan(span);\n reject(error);\n });\n\n // Handle process exit\n proc.on(\"close\", (exitCode) => {\n // Print any remaining buffer\n if (buffer.trim()) {\n try {\n const event: ClaudeEvent = JSON.parse(buffer);\n eventCount++;\n const result = this.handleClaudeEvent(event, options?.outputStream);\n if (result.output) {\n assistantOutput += result.output;\n }\n if (result.usedTool) {\n toolUseCount++;\n }\n } catch (error) {\n // Log JSON parse failure for remaining buffer\n if (isTelemetryEnabled && span) {\n emitLog(SeverityNumber.WARN, \"Failed to parse remaining buffer as JSON\", {\n \"error.message\": getErrorMessage(error),\n \"buffer.content\": buffer.substring(0, 200),\n \"buffer.length\": buffer.length,\n });\n }\n if (logger) {\n void logger.logError(\n `Failed to parse remaining buffer: ${getErrorMessage(error)}`,\n {\n source: \"json-parse-buffer\",\n client: \"Claude Code\",\n bufferContent: buffer.substring(0, 200),\n }\n );\n }\n\n const outStream = options?.outputStream !== null\n ? (options?.outputStream ?? process.stdout)\n : null;\n if (outStream) {\n outStream.write(buffer);\n }\n assistantOutput += buffer;\n }\n }\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"client.eventCount\", eventCount);\n (span as any).setAttribute(\"client.toolUseCount\", toolUseCount);\n (span as any).setAttribute(\"client.outputLength\", assistantOutput.length);\n (span as any).setAttribute(\"client.exitCode\", exitCode || 0);\n (span as any).setAttribute(\"response.content\", assistantOutput.substring(0, 1000)); // First 1000 chars\n (span as any).setAttribute(\"response.preview\", assistantOutput.substring(0, 200)); // Short preview\n }\n\n if (exitCode === 0) {\n // Log assistant message if we got output\n if (logger && assistantOutput.trim()) {\n void logger.logAssistantMessage(assistantOutput, {\n client: \"Claude Code\",\n });\n }\n if (isTelemetryEnabled && span) {\n (span as any).setStatus({ code: 0 });\n }\n endSpan(span);\n resolve(assistantOutput);\n } else {\n const errorMsg = `Claude process exited with code ${exitCode}`;\n if (isTelemetryEnabled && span) {\n emitLog(SeverityNumber.ERROR, \"Claude Code process exited with error\", {\n \"process.exitCode\": exitCode,\n });\n (span as any).setStatus({ code: 2, message: errorMsg });\n }\n if (logger) {\n void logger.logError(errorMsg, {\n exitCode,\n client: \"Claude Code\",\n });\n }\n endSpan(span);\n reject(new Error(errorMsg));\n }\n });\n });\n }\n\n /**\n * Handle a Claude Code event from the JSON stream\n * @param event The Claude event to handle\n * @param outputStream Stream for text output. null = suppress, undefined = stdout.\n * @returns Object with output text and tool use flag\n */\n private handleClaudeEvent(\n event: ClaudeEvent,\n outputStream?: NodeJS.WriteStream | null\n ): { output: string; usedTool: boolean } {\n let output = \"\";\n let usedTool = false;\n\n if (event.type === \"assistant\") {\n const content = event.message?.content || [];\n for (const block of content) {\n if (block.type === \"text\") {\n const text = block.text || \"\";\n if (outputStream !== null) {\n (outputStream ?? process.stdout).write(text);\n }\n output += text;\n } else if (block.type === \"tool_use\") {\n usedTool = true;\n // Tool notifications are always progress indicators \u2014 always stderr.\n // Not added to output: they are display-only and would corrupt JSON parsing.\n process.stderr.write(ansis.dim(`\\n[Using tool: ${block.name}]\\n`));\n }\n }\n }\n\n return { output, usedTool };\n }\n\n /**\n * Get the process arguments that would be used for spawning\n * @param options Chat options\n * @param isFirstMessage Whether this is the first message in the chat session\n * @returns Array of command line arguments\n */\n private getProcessArgs(options?: ChatOptions, isFirstMessage: boolean = true): string[] {\n const args = [\"--print\"];\n\n // Apply permissions: either full access or read-safe allowlist\n if (options?.withDanger) {\n args.push(\"--dangerously-skip-permissions\");\n } else {\n args.push(\"--allowedTools\", formatForClaudeCode());\n }\n\n args.push(\"--verbose\", \"--output-format\", \"stream-json\");\n\n // Session management:\n // - First message: Start with our session ID for traceability\n // - Subsequent messages: Resume that specific session\n if (isFirstMessage && options?.sessionId) {\n args.push(\"--session-id\", options.sessionId);\n } else if (!isFirstMessage && options?.sessionId) {\n args.push(\"--resume\", options.sessionId);\n }\n\n // Add agent if specified\n if (options?.agent) {\n args.unshift(\"--agent\", options.agent);\n }\n\n return args;\n }\n\n /**\n * Spawn the Claude Code CLI process\n * @param message The message to send\n * @param options Chat options\n * @param isFirstMessage Whether this is the first message in the chat session\n * @returns The spawned child process\n */\n private spawnClaudeProcess(\n message: string,\n options?: ChatOptions,\n isFirstMessage: boolean = true\n ): ChildProcess {\n const span = isTelemetryEnabled ? startSpan(\"claude-code.spawn-process\") : null;\n\n try {\n const args = this.getProcessArgs(options, isFirstMessage);\n const cwd = options?.workingDirectory || process.cwd();\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"process.command\", \"claude\");\n (span as any).setAttribute(\"process.args\", args.join(\" \"));\n (span as any).setAttribute(\"process.argCount\", args.length);\n (span as any).setAttribute(\"process.isFirstMessage\", isFirstMessage);\n (span as any).setAttribute(\"process.hasResume\", args.includes(\"--resume\"));\n (span as any).setAttribute(\"process.hasSessionId\", args.includes(\"--session-id\"));\n (span as any).setAttribute(\"process.hasAgent\", !!options?.agent);\n (span as any).setAttribute(\"process.agent\", options?.agent);\n (span as any).setAttribute(\"process.withDanger\", options?.withDanger === true);\n (span as any).setAttribute(\"process.workingDirectory\", cwd);\n (span as any).setAttribute(\"process.messageLength\", message.length);\n }\n\n // Log the command that's being executed\n const logger = getChatLogger();\n if (logger) {\n void logger.logCommand(\"claude\", args, {\n client: \"Claude Code\",\n workingDirectory: cwd,\n agent: options?.agent,\n withDanger: options?.withDanger || false,\n messageLength: message.length,\n hasVerboseFlag: args.includes(\"--verbose\"),\n hasOutputFormat: args.includes(\"--output-format\"),\n sessionId: options?.sessionId,\n });\n }\n\n // Strip CLAUDECODE from the environment so Claude doesn't refuse to run\n // inside an existing Claude Code session (nested session protection).\n const env = { ...process.env };\n delete env.CLAUDECODE;\n\n const proc = spawn(\"claude\", args, {\n cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env,\n });\n\n // Send message via stdin\n proc.stdin?.write(message);\n proc.stdin?.end();\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"process.spawned\", true);\n (span as any).setAttribute(\"process.pid\", proc.pid);\n (span as any).setStatus({ code: 0 });\n }\n\n return proc;\n } catch (error) {\n if (isTelemetryEnabled && span) {\n (span as any).recordException(error as Error);\n (span as any).setStatus({\n code: 2,\n message: getErrorMessage(error),\n });\n }\n throw error;\n } finally {\n endSpan(span);\n }\n }\n\n /**\n * Get the name of this client\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,sBAAsB,SACvB,KAAa,gBAAgB,KAAc,GAC3C,KAAa,UAAU;QACtB,MAAM;QACN,SAAS,gBAAgB,KAAK;OAC/B,IAEG;IACR;AACE,cAAQ,IAAI;IACd;EACF;;;;EAKA,gBAAa;AACX,WAAO;EACT;;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -3,6 +3,7 @@ import { spawnSync, spawn } from "child_process";
|
|
|
3
3
|
import ansis from "ansis";
|
|
4
4
|
import { getChatLogger } from "../utils/chat-logger.js";
|
|
5
5
|
import { getErrorMessage } from "../utils/errors.js";
|
|
6
|
+
import { applyCopilotPermissions } from "./default-permissions.js";
|
|
6
7
|
import { isTelemetryEnabled, startSpan, endSpan, emitLog, SeverityNumber } from "../telemetry/index.js";
|
|
7
8
|
class CopilotOutputParser {
|
|
8
9
|
inCodeBlock = !1;
|
|
@@ -160,23 +161,27 @@ class CopilotClient extends BaseChatClient {
|
|
|
160
161
|
const span = isTelemetryEnabled ? startSpan("copilot.spawn-process") : null;
|
|
161
162
|
try {
|
|
162
163
|
const args = [], cwd = options?.workingDirectory || process.cwd(), isFirst = this.isFirstMessage;
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
}
|
|
164
|
+
isFirst ? (args.push("--prompt", message), this.isFirstMessage = !1) : args.push("--continue", "--prompt", message), isFirst && options?.agent && args.push("--agent", options.agent);
|
|
165
|
+
const withDanger = options?.withDanger === !0, variant = this.copilotCommand === "copilot" ? "copilot" : "gh copilot";
|
|
166
|
+
applyCopilotPermissions(args, variant, this.copilotCommand || "copilot", withDanger, (attr, value) => {
|
|
167
|
+
isTelemetryEnabled && span && (span.setAttribute(attr, value), attr === "process.allowAllToolsSupported" && value === !1 && withDanger ? emitLog(SeverityNumber.WARN, "GitHub Copilot --allow-all-tools flag not available", {
|
|
168
|
+
"copilot.variant": this.copilotCommand,
|
|
169
|
+
withDanger: !0
|
|
170
|
+
}) : attr === "process.readSafePermissionsApplied" && value === !1 ? emitLog(SeverityNumber.WARN, "Copilot --allowedTools flag not supported, using default permissions", {
|
|
171
|
+
"copilot.variant": this.copilotCommand,
|
|
172
|
+
"copilot.note": "Installed Copilot CLI version may be outdated. Consider upgrading for permission controls."
|
|
173
|
+
}) : attr === "process.readSafePermissionCheckFailed" && emitLog(SeverityNumber.WARN, "Failed to check Copilot permission support", {
|
|
174
|
+
"error.message": "",
|
|
175
|
+
"copilot.variant": this.copilotCommand
|
|
176
|
+
}));
|
|
177
|
+
});
|
|
173
178
|
const command = "copilot";
|
|
174
|
-
isTelemetryEnabled && span && (span.setAttribute("process.command", command), span.setAttribute("process.args", args.join(" ")), span.setAttribute("process.argCount", args.length), span.setAttribute("process.isFirstMessage", isFirst), span.setAttribute("process.hasContinue", args.includes("--continue")), span.setAttribute("process.hasAgent", !!options?.agent), span.setAttribute("process.agent", options?.agent), span.setAttribute("process.withDanger",
|
|
179
|
+
isTelemetryEnabled && span && (span.setAttribute("process.command", command), span.setAttribute("process.args", args.join(" ")), span.setAttribute("process.argCount", args.length), span.setAttribute("process.isFirstMessage", isFirst), span.setAttribute("process.hasContinue", args.includes("--continue")), span.setAttribute("process.hasAgent", !!options?.agent), span.setAttribute("process.agent", options?.agent), span.setAttribute("process.withDanger", withDanger), span.setAttribute("process.workingDirectory", cwd), span.setAttribute("process.messageLength", message.length), span.setAttribute("process.variant", this.copilotCommand));
|
|
175
180
|
const logger = getChatLogger();
|
|
176
181
|
logger && logger.logCommand(command, args, {
|
|
177
182
|
client: "GitHub Copilot",
|
|
178
183
|
workingDirectory: cwd,
|
|
179
|
-
withDanger
|
|
184
|
+
withDanger,
|
|
180
185
|
copilotVariant: this.copilotCommand,
|
|
181
186
|
messageLength: message.length,
|
|
182
187
|
hasAgent: !!options?.agent,
|