nexakit 0.10.0 → 0.13.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 +13 -6
- package/assets/runtime/package-lock.json +415 -6
- package/bench/casos/arquitectura/alta-usuarios/base/controladores/usuarios.js +16 -0
- package/bench/casos/arquitectura/alta-usuarios/base/db.js +14 -0
- package/bench/casos/arquitectura/alta-usuarios/base/docs/adr/0003-capas.md +15 -0
- package/bench/casos/arquitectura/alta-usuarios/base/errores.js +3 -0
- package/bench/casos/arquitectura/alta-usuarios/base/repositorios/usuarios.js +14 -0
- package/bench/casos/arquitectura/alta-usuarios/base/servicios/usuarios.js +20 -0
- package/bench/casos/arquitectura/alta-usuarios/cambio/controladores/usuarios.js +47 -0
- package/bench/casos/arquitectura/alta-usuarios/cambio/repositorios/usuarios.js +21 -0
- package/bench/casos/arquitectura/alta-usuarios/cambio/servicios/perfil.js +14 -0
- package/bench/casos/arquitectura/alta-usuarios/esperado.json +53 -0
- package/bench/casos/arquitectura/pedidos-facturacion/base/docs/adr/0001-capas.md +18 -0
- package/bench/casos/arquitectura/pedidos-facturacion/base/src/aplicacion/confirmar.ts +8 -0
- package/bench/casos/arquitectura/pedidos-facturacion/base/src/dominio/pedido.ts +15 -0
- package/bench/casos/arquitectura/pedidos-facturacion/base/src/dominio/puertos.ts +6 -0
- package/bench/casos/arquitectura/pedidos-facturacion/base/src/infra/db.ts +14 -0
- package/bench/casos/arquitectura/pedidos-facturacion/base/src/main.ts +9 -0
- package/bench/casos/arquitectura/pedidos-facturacion/cambio/src/aplicacion/facturar.ts +19 -0
- package/bench/casos/arquitectura/pedidos-facturacion/cambio/src/dominio/informe.ts +7 -0
- package/bench/casos/arquitectura/pedidos-facturacion/cambio/src/dominio/pedido.ts +21 -0
- package/bench/casos/arquitectura/pedidos-facturacion/cambio/src/infra/db.ts +22 -0
- package/bench/casos/arquitectura/pedidos-facturacion/esperado.json +53 -0
- package/bench/casos/arquitectura/resumen-cliente/base/docs/adr/0001-capas.md +18 -0
- package/bench/casos/arquitectura/resumen-cliente/base/src/aplicacion/confirmar.ts +8 -0
- package/bench/casos/arquitectura/resumen-cliente/base/src/dominio/pedido.ts +15 -0
- package/bench/casos/arquitectura/resumen-cliente/base/src/dominio/puertos.ts +6 -0
- package/bench/casos/arquitectura/resumen-cliente/base/src/infra/db.ts +14 -0
- package/bench/casos/arquitectura/resumen-cliente/base/src/main.ts +9 -0
- package/bench/casos/arquitectura/resumen-cliente/cambio/src/aplicacion/resumen.ts +6 -0
- package/bench/casos/arquitectura/resumen-cliente/cambio/src/dominio/pedido.ts +33 -0
- package/bench/casos/arquitectura/resumen-cliente/cambio/src/dominio/puertos.ts +7 -0
- package/bench/casos/arquitectura/resumen-cliente/cambio/src/infra/db.ts +18 -0
- package/bench/casos/arquitectura/resumen-cliente/cambio/src/main.ts +14 -0
- package/bench/casos/arquitectura/resumen-cliente/esperado.json +23 -0
- package/bench/casos/documentacion/comentario-obsoleto/base/README.md +18 -0
- package/bench/casos/documentacion/comentario-obsoleto/base/src/usuarios.ts +35 -0
- package/bench/casos/documentacion/comentario-obsoleto/cambio/src/copia.ts +8 -0
- package/bench/casos/documentacion/comentario-obsoleto/cambio/src/usuarios.ts +43 -0
- package/bench/casos/documentacion/comentario-obsoleto/esperado.json +42 -0
- package/bench/casos/documentacion/reportes-config/base/README.md +23 -0
- package/bench/casos/documentacion/reportes-config/base/src/cli.js +33 -0
- package/bench/casos/documentacion/reportes-config/base/src/config.js +15 -0
- package/bench/casos/documentacion/reportes-config/base/src/envio.js +23 -0
- package/bench/casos/documentacion/reportes-config/cambio/src/cli.js +35 -0
- package/bench/casos/documentacion/reportes-config/cambio/src/config.js +15 -0
- package/bench/casos/documentacion/reportes-config/esperado.json +42 -0
- package/bench/casos/documentacion/tiempo-espera/base/README.md +10 -0
- package/bench/casos/documentacion/tiempo-espera/base/src/config.js +8 -0
- package/bench/casos/documentacion/tiempo-espera/cambio/README.md +10 -0
- package/bench/casos/documentacion/tiempo-espera/cambio/src/config.js +8 -0
- package/bench/casos/documentacion/tiempo-espera/esperado.json +16 -0
- package/bench/casos/pruebas/calendario-laboral/base/src/fechas.js +3 -0
- package/bench/casos/pruebas/calendario-laboral/base/test/fechas.test.js +7 -0
- package/bench/casos/pruebas/calendario-laboral/cambio/src/fechas.js +37 -0
- package/bench/casos/pruebas/calendario-laboral/cambio/test/calendario.test.js +31 -0
- package/bench/casos/pruebas/calendario-laboral/esperado.json +49 -0
- package/bench/casos/pruebas/fin-de-semana/base/src/fechas.js +3 -0
- package/bench/casos/pruebas/fin-de-semana/base/test/fechas.test.js +7 -0
- package/bench/casos/pruebas/fin-de-semana/cambio/src/fechas.js +8 -0
- package/bench/casos/pruebas/fin-de-semana/cambio/test/fines-de-semana.test.js +13 -0
- package/bench/casos/pruebas/fin-de-semana/esperado.json +16 -0
- package/bench/casos/pruebas/precios-carrito/base/src/precio.ts +3 -0
- package/bench/casos/pruebas/precios-carrito/base/test/precio.test.js +11 -0
- package/bench/casos/pruebas/precios-carrito/cambio/src/precio.ts +34 -0
- package/bench/casos/pruebas/precios-carrito/cambio/test/precio.test.js +42 -0
- package/bench/casos/pruebas/precios-carrito/esperado.json +42 -0
- package/bench/casos/rendimiento/boletin-correo/base/src/correo.html +1 -0
- package/bench/casos/rendimiento/boletin-correo/base/src/plantilla.ts +11 -0
- package/bench/casos/rendimiento/boletin-correo/cambio/src/envios.ts +44 -0
- package/bench/casos/rendimiento/boletin-correo/cambio/src/plantilla.ts +10 -0
- package/bench/casos/rendimiento/boletin-correo/esperado.json +42 -0
- package/bench/casos/rendimiento/clientes-por-lote/base/src/informe.js +8 -0
- package/bench/casos/rendimiento/clientes-por-lote/cambio/src/informe.js +6 -0
- package/bench/casos/rendimiento/clientes-por-lote/esperado.json +14 -0
- package/bench/casos/rendimiento/informe-ventas/base/src/informe.js +6 -0
- package/bench/casos/rendimiento/informe-ventas/base/src/tasas.json +1 -0
- package/bench/casos/rendimiento/informe-ventas/cambio/src/informe.js +33 -0
- package/bench/casos/rendimiento/informe-ventas/cambio/src/tasas.js +7 -0
- package/bench/casos/rendimiento/informe-ventas/esperado.json +42 -0
- package/bench/casos/seguridad/inyeccion-orden/base/src/respaldo.ts +13 -0
- package/bench/casos/seguridad/inyeccion-orden/cambio/src/respaldo.ts +69 -0
- package/bench/casos/seguridad/inyeccion-orden/esperado.json +42 -0
- package/bench/casos/seguridad/limpio-validacion/base/servidor.js +11 -0
- package/bench/casos/seguridad/limpio-validacion/cambio/servidor.js +39 -0
- package/bench/casos/seguridad/limpio-validacion/esperado.json +14 -0
- package/bench/casos/seguridad/servidor-archivos/base/servidor.js +21 -0
- package/bench/casos/seguridad/servidor-archivos/cambio/servidor.js +79 -0
- package/bench/casos/seguridad/servidor-archivos/esperado.json +42 -0
- package/bin/nexakit-fabrica-mcp.js +12 -0
- package/dist/fabrica/banco/casos.js +304 -0
- package/dist/fabrica/banco/ejecutar.js +483 -0
- package/dist/fabrica/banco/medir.js +120 -0
- package/dist/fabrica/cli.js +737 -0
- package/dist/fabrica/conectores/antigravity.js +1040 -0
- package/dist/fabrica/conectores/codex.js +967 -0
- package/dist/fabrica/conectores/tipos.js +8 -0
- package/dist/fabrica/config.js +44 -0
- package/dist/fabrica/consolidar.js +218 -0
- package/dist/fabrica/decision.js +210 -0
- package/dist/fabrica/diff.js +247 -0
- package/dist/fabrica/disco.js +356 -0
- package/dist/fabrica/ejecutor.js +597 -0
- package/dist/fabrica/encargo/candado.js +274 -0
- package/dist/fabrica/encargo/ejecutar.js +827 -0
- package/dist/fabrica/encargo/evidencia.js +308 -0
- package/dist/fabrica/encargo/parche.js +146 -0
- package/dist/fabrica/encargo/worktree.js +394 -0
- package/dist/fabrica/enrutador.js +425 -0
- package/dist/fabrica/errores.js +14 -0
- package/dist/fabrica/esquemas.js +57 -0
- package/dist/fabrica/estaciones.js +75 -0
- package/dist/fabrica/evidencia.js +406 -0
- package/dist/fabrica/indice.js +1 -0
- package/dist/fabrica/jsonrpc.js +274 -0
- package/dist/fabrica/lecciones.js +363 -0
- package/dist/fabrica/mcp.js +376 -0
- package/dist/fabrica/preferencias.js +56 -0
- package/dist/fabrica/protocolos/codex/AbsolutePathBuf.js +2 -0
- package/dist/fabrica/protocolos/codex/ApplyPatchApprovalResponse.js +2 -0
- package/dist/fabrica/protocolos/codex/ClientInfo.js +2 -0
- package/dist/fabrica/protocolos/codex/ExecCommandApprovalParams.js +2 -0
- package/dist/fabrica/protocolos/codex/ExecCommandApprovalResponse.js +2 -0
- package/dist/fabrica/protocolos/codex/ExecPolicyAmendment.js +2 -0
- package/dist/fabrica/protocolos/codex/FunctionCallOutputBody.js +2 -0
- package/dist/fabrica/protocolos/codex/FunctionCallOutputContentItem.js +2 -0
- package/dist/fabrica/protocolos/codex/ImageDetail.js +2 -0
- package/dist/fabrica/protocolos/codex/InitializeCapabilities.js +2 -0
- package/dist/fabrica/protocolos/codex/InitializeParams.js +2 -0
- package/dist/fabrica/protocolos/codex/InitializeResponse.js +2 -0
- package/dist/fabrica/protocolos/codex/InputModality.js +2 -0
- package/dist/fabrica/protocolos/codex/LegacyAppPathString.js +2 -0
- package/dist/fabrica/protocolos/codex/NetworkPolicyAmendment.js +2 -0
- package/dist/fabrica/protocolos/codex/NetworkPolicyRuleAction.js +2 -0
- package/dist/fabrica/protocolos/codex/ParsedCommand.js +2 -0
- package/dist/fabrica/protocolos/codex/Personality.js +2 -0
- package/dist/fabrica/protocolos/codex/ReasoningEffort.js +2 -0
- package/dist/fabrica/protocolos/codex/ReasoningSummary.js +2 -0
- package/dist/fabrica/protocolos/codex/ReviewDecision.js +2 -0
- package/dist/fabrica/protocolos/codex/ThreadId.js +2 -0
- package/dist/fabrica/protocolos/codex/serde_json/JsonValue.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/AdditionalFileSystemPermissions.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/AdditionalNetworkPermissions.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ApprovalsReviewer.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/AskForApproval.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ByteRange.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/CommandAction.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/CommandExecutionApprovalDecision.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/CommandExecutionApprovalKind.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/CommandExecutionRequestApprovalParams.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/CommandExecutionRequestApprovalResponse.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ConfigReadParams.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/CyberAccessProgram.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ExecPolicyAmendment.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/FileChangeApprovalDecision.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/FileChangeRequestApprovalResponse.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/FileSystemAccessMode.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/FileSystemPath.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/FileSystemSandboxEntry.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/FileSystemSpecialPath.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/GrantedPermissionProfile.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ListMcpServerStatusParams.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/McpServerElicitationAction.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/McpServerElicitationRequestResponse.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/McpServerStatusDetail.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/Model.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ModelAccessPrograms.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ModelAvailabilityNux.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ModelListParams.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ModelListResponse.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ModelServiceTier.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ModelUpgradeInfo.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/MultiAgentVersion.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/NetworkAccess.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/NetworkApprovalContext.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/NetworkApprovalProtocol.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/NetworkPolicyAmendment.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/NetworkPolicyRuleAction.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/PermissionGrantScope.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/PermissionsRequestApprovalResponse.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ReasoningEffortOption.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/SandboxMode.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/SandboxPolicy.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/TextElement.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ThreadSource.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ThreadStartParams.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ThreadStartSource.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ThreadTokenUsage.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ThreadTokenUsageUpdatedNotification.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/TokenUsageBreakdown.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ToolRequestUserInputAnswer.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/ToolRequestUserInputResponse.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/TurnInterruptParams.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/TurnStartParams.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/TurnToolOutput.js +2 -0
- package/dist/fabrica/protocolos/codex/v2/UserInput.js +2 -0
- package/dist/fabrica/rastro.js +487 -0
- package/dist/fabrica/sesion.js +230 -0
- package/dist/fabrica/tabla-modelos.json +29 -0
- package/dist/fabrica/veredictos.js +327 -0
- package/package.json +16 -8
- package/plugins/huellas.json +6 -6
- package/plugins/nexakit-lecciones/.claude-plugin/plugin.json +1 -1
- package/plugins/nexakit-lecciones/README.md +6 -5
- package/plugins/nexakit-lecciones/hooks/lecciones.js +29 -5
- package/plugins/nexakit-lecciones/hooks/register.js +7 -3
- package/plugins/nexakit-modelo/.claude-plugin/plugin.json +1 -1
- package/plugins/nexakit-modelo/hooks/barra.js +100 -4
- package/plugins/nexakit-modelo/hooks/decidir.js +2 -2
- package/plugins/nexakit-modelo/hooks/recomendar.js +1 -1
- package/plugins/nexakit-modelo/hooks/register.js +122 -7
- package/plugins/nexakit-modelo/tests/register.test.ts +301 -0
- package/plugins/niveles/.claude-plugin/plugin.json +1 -1
- package/plugins/niveles/agents/cazador-de-flakes.md +1 -0
- package/plugins/niveles/agents/cierre-de-memoria.md +1 -0
- package/plugins/niveles/agents/investigador.md +1 -0
- package/plugins/niveles/agents/nivel-alto.md +1 -0
- package/plugins/niveles/agents/nivel-exigente.md +1 -0
- package/plugins/niveles/agents/nivel-ligero.md +1 -0
- package/plugins/niveles/agents/nivel-normal.md +1 -0
- package/plugins/niveles/agents/revisor-de-calidad.md +1 -0
- package/plugins/niveles/agents/sincronizador-docs.md +1 -0
- package/plugins/niveles/agents/subir-al-repo.md +1 -0
- package/skills/elegir-modelo/SKILL.md +4 -3
- package/skills/elegir-modelo/modelos.mjs +100 -1
- package/skills/fabrica/SKILL.md +55 -0
- package/skills/gemini/SKILL.md +2 -3
- package/skills/quality-gate/SKILL.md +2 -2
- package/src/agent-models.js +6 -4
- package/src/antigravity-barra.js +64 -12
- package/src/antigravity-command.js +4 -2
- package/src/antigravity-models.js +61 -0
- package/src/antigravity-pre-tool.js +11 -3
- package/src/antigravity-recommendation.js +15 -9
- package/src/antigravity-setup.js +4 -31
- package/src/cli-executable.d.ts +11 -0
- package/src/codex-pre-tool.js +3 -3
- package/src/codex-recommendation.js +1 -2
- package/src/codex-setup.js +3 -20
- package/src/codex-team.js +31 -4
- package/src/fabrica/banco/casos.ts +315 -0
- package/src/fabrica/banco/ejecutar.ts +587 -0
- package/src/fabrica/banco/medir.ts +160 -0
- package/src/fabrica/cli.ts +781 -0
- package/src/fabrica/conectores/antigravity.ts +1090 -0
- package/src/fabrica/conectores/codex.ts +1013 -0
- package/src/fabrica/conectores/tipos.ts +54 -0
- package/src/fabrica/config.ts +43 -0
- package/src/fabrica/consolidar.ts +277 -0
- package/src/fabrica/decision.ts +285 -0
- package/src/fabrica/diff.ts +294 -0
- package/src/fabrica/disco.ts +380 -0
- package/src/fabrica/ejecutor.ts +716 -0
- package/src/fabrica/encargo/candado.ts +287 -0
- package/src/fabrica/encargo/ejecutar.ts +953 -0
- package/src/fabrica/encargo/evidencia.ts +301 -0
- package/src/fabrica/encargo/parche.ts +151 -0
- package/src/fabrica/encargo/worktree.ts +427 -0
- package/src/fabrica/enrutador.ts +494 -0
- package/src/fabrica/errores.ts +15 -0
- package/src/fabrica/esquemas.ts +92 -0
- package/src/fabrica/estaciones.ts +83 -0
- package/src/fabrica/evidencia.ts +445 -0
- package/src/fabrica/indice.ts +1 -0
- package/src/fabrica/jsonrpc.ts +314 -0
- package/src/fabrica/lecciones.ts +411 -0
- package/src/fabrica/mcp.ts +450 -0
- package/src/fabrica/preferencias.ts +66 -0
- package/src/fabrica/protocolos/codex/AbsolutePathBuf.ts +14 -0
- package/src/fabrica/protocolos/codex/ApplyPatchApprovalResponse.ts +6 -0
- package/src/fabrica/protocolos/codex/ClientInfo.ts +5 -0
- package/src/fabrica/protocolos/codex/ExecCommandApprovalParams.ts +16 -0
- package/src/fabrica/protocolos/codex/ExecCommandApprovalResponse.ts +6 -0
- package/src/fabrica/protocolos/codex/ExecPolicyAmendment.ts +12 -0
- package/src/fabrica/protocolos/codex/FunctionCallOutputBody.ts +6 -0
- package/src/fabrica/protocolos/codex/FunctionCallOutputContentItem.ts +10 -0
- package/src/fabrica/protocolos/codex/ImageDetail.ts +5 -0
- package/src/fabrica/protocolos/codex/InitializeCapabilities.ts +42 -0
- package/src/fabrica/protocolos/codex/InitializeParams.ts +7 -0
- package/src/fabrica/protocolos/codex/InitializeResponse.ts +20 -0
- package/src/fabrica/protocolos/codex/InputModality.ts +8 -0
- package/src/fabrica/protocolos/codex/LegacyAppPathString.ts +27 -0
- package/src/fabrica/protocolos/codex/NetworkPolicyAmendment.ts +6 -0
- package/src/fabrica/protocolos/codex/NetworkPolicyRuleAction.ts +5 -0
- package/src/fabrica/protocolos/codex/ParsedCommand.ts +12 -0
- package/src/fabrica/protocolos/codex/Personality.ts +8 -0
- package/src/fabrica/protocolos/codex/ReasoningEffort.ts +8 -0
- package/src/fabrica/protocolos/codex/ReasoningSummary.ts +10 -0
- package/src/fabrica/protocolos/codex/ReviewDecision.ts +10 -0
- package/src/fabrica/protocolos/codex/ThreadId.ts +10 -0
- package/src/fabrica/protocolos/codex/VERSION +1 -0
- package/src/fabrica/protocolos/codex/serde_json/JsonValue.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/AdditionalFileSystemPermissions.ts +15 -0
- package/src/fabrica/protocolos/codex/v2/AdditionalNetworkPermissions.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/ApprovalsReviewer.ts +12 -0
- package/src/fabrica/protocolos/codex/v2/AskForApproval.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/ByteRange.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/CommandAction.ts +6 -0
- package/src/fabrica/protocolos/codex/v2/CommandExecutionApprovalDecision.ts +7 -0
- package/src/fabrica/protocolos/codex/v2/CommandExecutionApprovalKind.ts +8 -0
- package/src/fabrica/protocolos/codex/v2/CommandExecutionRequestApprovalParams.ts +51 -0
- package/src/fabrica/protocolos/codex/v2/CommandExecutionRequestApprovalResponse.ts +6 -0
- package/src/fabrica/protocolos/codex/v2/ConfigReadParams.ts +11 -0
- package/src/fabrica/protocolos/codex/v2/CyberAccessProgram.ts +9 -0
- package/src/fabrica/protocolos/codex/v2/ExecPolicyAmendment.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/FileChangeApprovalDecision.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/FileChangeRequestApprovalResponse.ts +6 -0
- package/src/fabrica/protocolos/codex/v2/FileSystemAccessMode.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/FileSystemPath.ts +7 -0
- package/src/fabrica/protocolos/codex/v2/FileSystemSandboxEntry.ts +7 -0
- package/src/fabrica/protocolos/codex/v2/FileSystemSpecialPath.ts +6 -0
- package/src/fabrica/protocolos/codex/v2/GrantedPermissionProfile.ts +7 -0
- package/src/fabrica/protocolos/codex/v2/ListMcpServerStatusParams.ts +23 -0
- package/src/fabrica/protocolos/codex/v2/McpServerElicitationAction.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/McpServerElicitationRequestResponse.ts +17 -0
- package/src/fabrica/protocolos/codex/v2/McpServerStatusDetail.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/Model.ts +33 -0
- package/src/fabrica/protocolos/codex/v2/ModelAccessPrograms.ts +13 -0
- package/src/fabrica/protocolos/codex/v2/ModelAvailabilityNux.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/ModelListParams.ts +17 -0
- package/src/fabrica/protocolos/codex/v2/ModelListResponse.ts +11 -0
- package/src/fabrica/protocolos/codex/v2/ModelServiceTier.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/ModelUpgradeInfo.ts +9 -0
- package/src/fabrica/protocolos/codex/v2/MultiAgentVersion.ts +8 -0
- package/src/fabrica/protocolos/codex/v2/NetworkAccess.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/NetworkApprovalContext.ts +6 -0
- package/src/fabrica/protocolos/codex/v2/NetworkApprovalProtocol.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/NetworkPolicyAmendment.ts +6 -0
- package/src/fabrica/protocolos/codex/v2/NetworkPolicyRuleAction.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/PermissionGrantScope.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/PermissionsRequestApprovalResponse.ts +11 -0
- package/src/fabrica/protocolos/codex/v2/ReasoningEffortOption.ts +6 -0
- package/src/fabrica/protocolos/codex/v2/SandboxMode.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/SandboxPolicy.ts +7 -0
- package/src/fabrica/protocolos/codex/v2/TextElement.ts +14 -0
- package/src/fabrica/protocolos/codex/v2/ThreadSource.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/ThreadStartParams.ts +22 -0
- package/src/fabrica/protocolos/codex/v2/ThreadStartSource.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/ThreadTokenUsage.ts +6 -0
- package/src/fabrica/protocolos/codex/v2/ThreadTokenUsageUpdatedNotification.ts +6 -0
- package/src/fabrica/protocolos/codex/v2/TokenUsageBreakdown.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/ToolRequestUserInputAnswer.ts +8 -0
- package/src/fabrica/protocolos/codex/v2/ToolRequestUserInputResponse.ts +9 -0
- package/src/fabrica/protocolos/codex/v2/TurnInterruptParams.ts +5 -0
- package/src/fabrica/protocolos/codex/v2/TurnStartParams.ts +75 -0
- package/src/fabrica/protocolos/codex/v2/TurnToolOutput.ts +10 -0
- package/src/fabrica/protocolos/codex/v2/UserInput.ts +11 -0
- package/src/fabrica/rastro.ts +508 -0
- package/src/fabrica/sesion.ts +280 -0
- package/src/fabrica/tabla-modelos.json +29 -0
- package/src/fabrica/veredictos.ts +365 -0
- package/src/gemini-cli.js +15 -12
- package/src/gemini-tools.js +1 -1
- package/src/gemini-usage-store.js +32 -0
- package/src/instructions-block.js +69 -0
- package/src/lecciones-command.js +105 -4
- package/src/lecciones-instructions.js +178 -0
- package/src/legacy-repair.js +1 -1
- package/src/level-agents.js +5 -3
- package/src/memory-mcp-policy.js +1 -1
- package/src/missing-dependencies.js +5 -0
- package/src/model-command.d.ts +29 -0
- package/src/model-command.js +4 -27
- package/src/regla-ordenes-simples.d.ts +2 -0
- package/src/regla-ordenes-simples.js +4 -0
- package/src/review-instructions.js +69 -81
- package/src/safe-paths.js +38 -0
- package/src/setup-apply.js +24 -2
- package/src/setup-plan.js +57 -1
- package/src/setup-state.js +14 -0
- package/src/shell-quote.js +2 -0
- package/src/skill-recommendations.js +101 -28
- package/src/stable-command.js +2 -2
- package/src/stable-install.js +4 -2
- package/src/superpowers.js +0 -7
- package/src/task-document.js +59 -0
- package/src/terminal-text.js +2 -19
- package/src/toolkit-cli.js +63 -8
- package/src/toolkit-setup.js +192 -37
- package/templates/agent-team/README.md +7 -19
- package/bin/agent-task.js +0 -14
- package/bin/agent-toolkit-inbox.js +0 -14
- package/bin/agent-toolkit-mcp.js +0 -17
- package/schemas/agent-client-adapter.schema.json +0 -786
- package/schemas/agent-client-auth-diagnostic.schema.json +0 -801
- package/schemas/agent-client-isolated-variant.schema.json +0 -105
- package/schemas/agent-client-isolated-verification.schema.json +0 -99
- package/schemas/agent-client-managed-preferences-invocation.schema.json +0 -67
- package/schemas/agent-client-managed-preferences.schema.json +0 -63
- package/schemas/agent-client-native-diagnostics.schema.json +0 -85
- package/schemas/agent-client-native-evaluation.schema.json +0 -171
- package/schemas/agent-client-native-preflight.schema.json +0 -90
- package/schemas/agent-client-output.schema.json +0 -551
- package/schemas/agent-client-runtime-fixture.schema.json +0 -90
- package/schemas/agent-client-runtime-local.schema.json +0 -95
- package/schemas/agent-client-runtime.schema.json +0 -1288
- package/schemas/agent-client-selective-config.schema.json +0 -77
- package/schemas/agent-client-supervised-local.schema.json +0 -135
- package/schemas/agent-client-supervised.schema.json +0 -186
- package/schemas/agent-task-approvals.schema.json +0 -362
- package/schemas/agent-task-prepare.schema.json +0 -1324
- package/schemas/agent-task-verify.schema.json +0 -198
- package/schemas/task-workflow-plan-output.schema.json +0 -35
- package/skills/revisar/SKILL.md +0 -51
- package/src/claude-code-runner.js +0 -642
- package/src/client-adapter-plan.js +0 -271
- package/src/client-auth-diagnostic-parser.js +0 -211
- package/src/client-auth-diagnostic.js +0 -257
- package/src/client-isolated-variant.js +0 -106
- package/src/client-isolated-verification.js +0 -130
- package/src/client-local-platform.js +0 -14
- package/src/client-managed-preferences-invocation.js +0 -209
- package/src/client-managed-preferences.js +0 -78
- package/src/client-native-access.js +0 -134
- package/src/client-native-diagnostics.js +0 -253
- package/src/client-native-evaluation.js +0 -106
- package/src/client-native-preflight-files.js +0 -68
- package/src/client-native-preflight.js +0 -95
- package/src/client-output-parser.js +0 -278
- package/src/client-runtime-admission.js +0 -80
- package/src/client-runtime-coordinator.js +0 -70
- package/src/client-runtime-core.js +0 -92
- package/src/client-runtime-fixture-permit.js +0 -20
- package/src/client-runtime-fixture-protocol.js +0 -39
- package/src/client-runtime-state.js +0 -67
- package/src/client-runtime-store-files.js +0 -91
- package/src/client-runtime-store.js +0 -239
- package/src/client-runtime-supervisor.js +0 -146
- package/src/client-selective-config.js +0 -195
- package/src/client-selective-files.js +0 -126
- package/src/client-supervised-codes.js +0 -32
- package/src/client-supervised-contract.js +0 -52
- package/src/client-supervised-coordinator.js +0 -36
- package/src/client-supervised-permit.js +0 -20
- package/src/client-supervised-protocol.js +0 -37
- package/src/client-supervised-store.js +0 -167
- package/src/client-supervised-supervisor.js +0 -167
- package/src/client-supervised.js +0 -160
- package/src/codex-cli-runner.js +0 -358
- package/src/codex-delivery.js +0 -101
- package/src/memory-connection-artifacts.js +0 -192
- package/src/memory-connection-descriptor.js +0 -158
- package/src/memory-connection-diagnostic.js +0 -177
- package/src/memory-connection-files.js +0 -191
- package/src/memory-connection-manifest.js +0 -118
- package/src/memory-connection-package.js +0 -176
- package/src/memory-connection-plan.js +0 -217
- package/src/memory-connection-skill.js +0 -211
- package/src/memory-connection-toml.js +0 -153
- package/src/native/managed-preferences.c +0 -100
- package/src/native/managed-preferences.h +0 -17
- package/src/package-lock-path.js +0 -13
- package/src/peer-handoff.js +0 -27
- package/src/peer-inbox-cli.js +0 -211
- package/src/peer-review-mcp.js +0 -210
- package/src/peer-review-store.js +0 -532
- package/src/review-policy.js +0 -35
- package/src/revision-adapters.js +0 -158
- package/src/revision-context.js +0 -86
- package/src/revision-isolation.js +0 -222
- package/src/revision-process.js +0 -103
- package/src/revision-provenance.js +0 -89
- package/src/revision-snapshot.js +0 -120
- package/src/revision.js +0 -242
- package/src/runtime-fixtures/runtime-supervisor/child.cjs +0 -3
- package/src/runtime-fixtures/runtime-supervisor/fixture.cjs +0 -49
- package/src/runtime-fixtures/supervised/child.cjs +0 -3
- package/src/runtime-fixtures/supervised/fixture.cjs +0 -47
- package/src/task-approvals.js +0 -367
- package/src/task-cli.js +0 -79
- package/src/task-external-verifier.js +0 -584
- package/src/task-prepare-files.js +0 -115
- package/src/task-prepare.js +0 -180
- package/src/task-verify-cli.js +0 -67
- package/src/task-verify-files.js +0 -188
- package/src/task-verify.js +0 -118
- package/src/task-workflow-mcp.js +0 -544
- package/src/task-workflow-store.js +0 -254
- package/src/toolkit-commands-guide.js +0 -115
package/src/codex-cli-runner.js
DELETED
|
@@ -1,358 +0,0 @@
|
|
|
1
|
-
import { randomBytes, createHash } from "node:crypto";
|
|
2
|
-
import { spawn as nodeSpawn, spawnSync } from "node:child_process";
|
|
3
|
-
import fs from "node:fs/promises";
|
|
4
|
-
import os from "node:os";
|
|
5
|
-
import path from "node:path";
|
|
6
|
-
import { fileURLToPath } from "node:url";
|
|
7
|
-
import { IS_WINDOWS, warnPlatformPermissions } from "./platform.js";
|
|
8
|
-
import { resolveCliInvocation } from "./cli-executable.js";
|
|
9
|
-
|
|
10
|
-
const PLAN_SCHEMA = fileURLToPath(new URL("../schemas/task-workflow-plan-output.schema.json", import.meta.url));
|
|
11
|
-
const MAX_PROMPT_BYTES = 48_000;
|
|
12
|
-
const MAX_OUTPUT_BYTES = 32_000;
|
|
13
|
-
const RUN_TIMEOUT_MS = 180_000;
|
|
14
|
-
const CODEX_EFFORTS = new Set(["low", "medium", "high", "xhigh", "max", "ultra"]);
|
|
15
|
-
const CLAUDE_EFFORTS = new Set(["low", "medium", "high", "xhigh", "max"]);
|
|
16
|
-
const CONTROL_PATTERN = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u;
|
|
17
|
-
|
|
18
|
-
const fail = code => { throw Object.assign(new Error("La invocación local de Codex no se pudo preparar."), { code }); };
|
|
19
|
-
|
|
20
|
-
function safeText(value, limit, required = false) {
|
|
21
|
-
return typeof value === "string" && value.length <= limit && (!required || value.trim().length > 0) &&
|
|
22
|
-
!/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u.test(value);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
function safePath(value, limit = 4096) {
|
|
26
|
-
return typeof value === "string" && value.length <= limit && !CONTROL_PATTERN.test(value);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function validateModel(value) {
|
|
30
|
-
if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/u.test(value)) fail("codex-model-invalid");
|
|
31
|
-
return value;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function validateEffort(value) {
|
|
35
|
-
if (!CODEX_EFFORTS.has(value)) fail("codex-effort-invalid");
|
|
36
|
-
return value;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function filteredEnvironment(source, executable) {
|
|
40
|
-
const env = {};
|
|
41
|
-
for (const key of ["HOME", "TMPDIR", "LANG", "LC_ALL", "CODEX_HOME", ...(IS_WINDOWS ? ["SystemRoot", "SYSTEMROOT", "WINDIR", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "TEMP", "TMP"] : [])]) {
|
|
42
|
-
const value = source[key];
|
|
43
|
-
if (typeof value === "string" && value.length > 0 && !/[\u0000-\u001f\u007f]/u.test(value)) env[key] = value;
|
|
44
|
-
}
|
|
45
|
-
const systemPaths = IS_WINDOWS
|
|
46
|
-
? [source.SystemRoot ?? source.SYSTEMROOT ?? source.WINDIR].filter(value => typeof value === "string" && path.isAbsolute(value) && !CONTROL_PATTERN.test(value)).map(value => path.join(value, "System32"))
|
|
47
|
-
: (process.platform === "darwin" ? "/usr/bin:/bin:/usr/sbin:/sbin" : "/usr/bin:/bin").split(path.delimiter);
|
|
48
|
-
env.PATH = [...new Set([path.dirname(executable), ...systemPaths])].join(path.delimiter);
|
|
49
|
-
env.NO_COLOR = "1";
|
|
50
|
-
return env;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
async function resolveExecutable(override, io, environment) {
|
|
54
|
-
try { return await resolveCliInvocation({ name: "codex", override, environment, fileIo: io }); }
|
|
55
|
-
catch { fail("codex-client-not-found"); }
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
async function validateProjectRoot(value, io, home) {
|
|
59
|
-
warnPlatformPermissions();
|
|
60
|
-
if (!safePath(value) || !value || !path.isAbsolute(value) || path.normalize(value) !== value) fail("codex-project-root-invalid");
|
|
61
|
-
let real;
|
|
62
|
-
let realHome;
|
|
63
|
-
let stat;
|
|
64
|
-
try { real = path.normalize(await io.realpath(value)); realHome = path.normalize(await io.realpath(home)); stat = await io.lstat(real); } catch { fail("codex-project-root-invalid"); }
|
|
65
|
-
if (real === path.parse(real).root || real === realHome || real === path.join(realHome, ".codex") ||
|
|
66
|
-
real === path.join(realHome, ".claude") || !stat.isDirectory() || stat.isSymbolicLink() ||
|
|
67
|
-
(!IS_WINDOWS && ((typeof process.getuid === "function" && stat.uid !== process.getuid()) || (stat.mode & 0o022)))) fail("codex-project-root-invalid");
|
|
68
|
-
return real;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function planPrompt({ task, modelCandidates, claudeEfforts }) {
|
|
72
|
-
const prompt = [
|
|
73
|
-
"Genera un plan verificable para esta tarea. Inspecciona el repositorio solo en modo de lectura. No edites archivos ni ejecutes comandos que cambien datos.",
|
|
74
|
-
"Devuelve únicamente el JSON exigido por el esquema de salida. Elige el modelo Claude más adecuado entre los candidatos permitidos y el esfuerzo entre los valores permitidos; no inventes disponibilidad ni afirmes que ejecutaste comprobaciones.",
|
|
75
|
-
"En `files`, enumera las rutas relativas concretas que Claude necesitaría editar o inspeccionar. Estas rutas son una propuesta, no una autorización para escribir.",
|
|
76
|
-
"Responde en español dentro de los campos de texto.",
|
|
77
|
-
"",
|
|
78
|
-
"## Tarea",
|
|
79
|
-
`Título: ${task.title}`,
|
|
80
|
-
`Proyecto: ${task.project}`,
|
|
81
|
-
`Modo: ${task.mode}`,
|
|
82
|
-
`Objetivo:\n${task.objective}`,
|
|
83
|
-
task.scope ? `Alcance declarado:\n${task.scope}` : "",
|
|
84
|
-
task.acceptance ? `Criterios declarados:\n${task.acceptance}` : "",
|
|
85
|
-
task.checks ? `Comprobaciones requeridas (no ejecutar):\n${task.checks}` : "",
|
|
86
|
-
"",
|
|
87
|
-
`Modelos Claude permitidos para la recomendación: ${modelCandidates.join(", ")}`,
|
|
88
|
-
`Esfuerzos permitidos para la recomendación: ${claudeEfforts.join(", ")}`
|
|
89
|
-
].filter(Boolean).join("\n");
|
|
90
|
-
if (Buffer.byteLength(prompt, "utf8") > MAX_PROMPT_BYTES) fail("codex-prompt-limit");
|
|
91
|
-
return prompt;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function reviewPrompt({ task, plan, proposal, implementation }) {
|
|
95
|
-
const prompt = [
|
|
96
|
-
"Eres el revisor final de una tarea de Agent Toolkit.",
|
|
97
|
-
"Revisa el cambio real del repositorio después de la implementación de Claude. Usa herramientas de solo lectura y compara el código con el plan, la propuesta aprobada y los criterios de aceptación.",
|
|
98
|
-
"No edites archivos, no crees ni borres datos, no hagas commits ni pushes, y no ejecutes comandos que escriban en el proyecto. No afirmes que corriste pruebas; indica como no ejecutadas las comprobaciones que no puedas confirmar con evidencia.",
|
|
99
|
-
"Devuelve hallazgos concretos primero, con severidad, ruta y ubicación cuando sea posible. Distingue hallazgos confirmados de preguntas o riesgos. Si no encuentras hallazgos, dilo y enumera los límites de la revisión.",
|
|
100
|
-
"Responde en español.",
|
|
101
|
-
"",
|
|
102
|
-
"## Tarea y permisos",
|
|
103
|
-
`Título: ${task.title}`,
|
|
104
|
-
`Proyecto: ${task.project}`,
|
|
105
|
-
`Objetivo:\n${task.objective}`,
|
|
106
|
-
task.scope ? `Alcance:\n${task.scope}` : "",
|
|
107
|
-
task.acceptance ? `Criterios de aceptación:\n${task.acceptance}` : "",
|
|
108
|
-
task.checks ? `Comprobaciones previstas (no ejecutar):\n${task.checks}` : "",
|
|
109
|
-
"",
|
|
110
|
-
"## Plan original de Codex",
|
|
111
|
-
plan,
|
|
112
|
-
"",
|
|
113
|
-
"## Propuesta aprobada de Claude",
|
|
114
|
-
proposal,
|
|
115
|
-
"",
|
|
116
|
-
"## Entrega de implementación de Claude",
|
|
117
|
-
implementation,
|
|
118
|
-
"",
|
|
119
|
-
"Inspecciona el estado actual del repositorio y sus diferencias. No tomes las afirmaciones del implementador como evidencia; verifica el código presente en disco."
|
|
120
|
-
].filter(Boolean).join("\n");
|
|
121
|
-
if (Buffer.byteLength(prompt, "utf8") > MAX_PROMPT_BYTES) fail("codex-prompt-limit");
|
|
122
|
-
return prompt;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
function codexArgs({ model, effort, cwd, outputFile, schema = PLAN_SCHEMA }) {
|
|
126
|
-
const args = [
|
|
127
|
-
"exec",
|
|
128
|
-
"--sandbox", "read-only",
|
|
129
|
-
"--ephemeral",
|
|
130
|
-
"--ignore-user-config",
|
|
131
|
-
"--config", 'approval_policy="never"',
|
|
132
|
-
"--cd", cwd,
|
|
133
|
-
"--model", model,
|
|
134
|
-
"--config", `model_reasoning_effort=${effort}`
|
|
135
|
-
];
|
|
136
|
-
if (schema) args.push("--output-schema", schema);
|
|
137
|
-
args.push("--output-last-message", outputFile, "-");
|
|
138
|
-
return args;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
function accountSummary(auth) {
|
|
142
|
-
return auth === "chatgpt"
|
|
143
|
-
? "Usaría la sesión de ChatGPT detectada por Codex CLI. La identidad, el plan y la cuota exactos no están expuestos al Toolkit."
|
|
144
|
-
: auth === "api-key"
|
|
145
|
-
? "Codex CLI informa una sesión de API key; esta etapa está bloqueada para evitar consumo de API no autorizado."
|
|
146
|
-
: "Codex CLI no informa una sesión autenticada con ChatGPT; no se ejecutará el modelo.";
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
function terminate(child, signal) {
|
|
150
|
-
if (!child?.pid) return;
|
|
151
|
-
try {
|
|
152
|
-
if (process.platform !== "win32") process.kill(-child.pid, signal);
|
|
153
|
-
else child.kill(signal);
|
|
154
|
-
} catch (error) {
|
|
155
|
-
if (error.code !== "ESRCH") child.kill(signal);
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
function runBounded({ executable, args, cwd, prompt, env, spawn = nodeSpawn, timeoutMs = RUN_TIMEOUT_MS }) {
|
|
160
|
-
return new Promise((resolve, rejectPromise) => {
|
|
161
|
-
let child;
|
|
162
|
-
let settled = false;
|
|
163
|
-
let failure = null;
|
|
164
|
-
let stdoutBytes = 0;
|
|
165
|
-
const stdout = [];
|
|
166
|
-
let timer;
|
|
167
|
-
let killTimer;
|
|
168
|
-
const failRun = error => {
|
|
169
|
-
if (settled || failure) return;
|
|
170
|
-
failure = error;
|
|
171
|
-
terminate(child, "SIGTERM");
|
|
172
|
-
killTimer = setTimeout(() => terminate(child, "SIGKILL"), 1_000);
|
|
173
|
-
killTimer.unref?.();
|
|
174
|
-
};
|
|
175
|
-
try {
|
|
176
|
-
child = spawn(executable, args, {
|
|
177
|
-
cwd, env, shell: false, detached: process.platform !== "win32",
|
|
178
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
179
|
-
});
|
|
180
|
-
} catch { rejectPromise(new Error("No se pudo iniciar Codex CLI.")); return; }
|
|
181
|
-
timer = setTimeout(() => failRun(new Error("La invocación de Codex superó el límite de tiempo.")), timeoutMs);
|
|
182
|
-
timer.unref?.();
|
|
183
|
-
child.stdout.on("data", chunk => {
|
|
184
|
-
stdoutBytes += chunk.length;
|
|
185
|
-
if (stdoutBytes > MAX_OUTPUT_BYTES) { failRun(new Error("La salida de Codex superó el límite permitido.")); return; }
|
|
186
|
-
stdout.push(chunk);
|
|
187
|
-
});
|
|
188
|
-
child.stderr.on("data", () => {});
|
|
189
|
-
child.stdin.on("error", () => failRun(new Error("No se pudo enviar el encargo a Codex.")));
|
|
190
|
-
child.on("error", () => failRun(new Error("No se pudo iniciar Codex CLI.")));
|
|
191
|
-
child.on("close", (code, signal) => {
|
|
192
|
-
if (settled) return;
|
|
193
|
-
settled = true;
|
|
194
|
-
clearTimeout(timer);
|
|
195
|
-
clearTimeout(killTimer);
|
|
196
|
-
if (failure) { rejectPromise(failure); return; }
|
|
197
|
-
if (code !== 0 || signal) { rejectPromise(new Error("Codex no terminó correctamente; no se guardó un plan.")); return; }
|
|
198
|
-
resolve(Buffer.concat(stdout).toString("utf8"));
|
|
199
|
-
});
|
|
200
|
-
child.stdin.end(prompt, "utf8");
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
function validatePlanOutput(raw, claudeModels, claudeEfforts) {
|
|
205
|
-
let plan;
|
|
206
|
-
try { plan = JSON.parse(raw); } catch { fail("codex-plan-invalid-json"); }
|
|
207
|
-
if (!plan || typeof plan !== "object" || Array.isArray(plan) ||
|
|
208
|
-
!safeText(plan.summary, 4_000, true) || !safeText(plan.claude?.model, 80, true) ||
|
|
209
|
-
!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/u.test(plan.claude.model) || !CLAUDE_EFFORTS.has(plan.claude.effort) ||
|
|
210
|
-
!claudeModels.includes(plan.claude.model) || !claudeEfforts.includes(plan.claude.effort) ||
|
|
211
|
-
!Array.isArray(plan.files) || plan.files.length > 64 ||
|
|
212
|
-
plan.files.some(file => !file || typeof file !== "object" || !safePath(file.path, 512) || !file.path || !safeText(file.reason, 1_000, true) ||
|
|
213
|
-
path.posix.isAbsolute(file.path) || file.path.includes("\\") || file.path.split("/").some(part => part === "" || part === "." || part === "..") ||
|
|
214
|
-
/(?:^|\/)(?:\.git|\.claude|\.codex|\.agents|\.ssh|\.aws)(?:\/|$)/iu.test(file.path) || !["inspect", "modify", "create"].includes(file.action)) ||
|
|
215
|
-
!Array.isArray(plan.acceptance) || plan.acceptance.length > 32 || plan.acceptance.some(item => !safeText(item, 1_000, true)) ||
|
|
216
|
-
!Array.isArray(plan.checks) || plan.checks.length > 32 || plan.checks.some(item => !safeText(item, 1_000, true))) fail("codex-plan-invalid");
|
|
217
|
-
return plan;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
export function createCodexCliRunner(dependencies = {}) {
|
|
221
|
-
const io = dependencies.fileIo ?? fs;
|
|
222
|
-
const sourceEnv = dependencies.env ?? process.env;
|
|
223
|
-
const home = dependencies.home ?? os.homedir();
|
|
224
|
-
const spawn = dependencies.spawn ?? nodeSpawn;
|
|
225
|
-
const runSync = dependencies.runSync ?? ((executable, args, env) => spawnSync(executable, args, {
|
|
226
|
-
encoding: "utf8", timeout: 5_000, maxBuffer: 16_384, shell: false,
|
|
227
|
-
stdio: ["ignore", "pipe", "pipe"], env
|
|
228
|
-
}));
|
|
229
|
-
|
|
230
|
-
async function inspectClient({ executable, argsPrefix }) {
|
|
231
|
-
const env = filteredEnvironment(sourceEnv, executable);
|
|
232
|
-
let versionResult;
|
|
233
|
-
let authResult;
|
|
234
|
-
try {
|
|
235
|
-
versionResult = runSync(executable, [...argsPrefix, "--version"], env);
|
|
236
|
-
authResult = runSync(executable, [...argsPrefix, "login", "status"], env);
|
|
237
|
-
} catch { fail("codex-client-preflight-failed"); }
|
|
238
|
-
if (versionResult?.error || versionResult?.status !== 0 || typeof versionResult.stdout !== "string" ||
|
|
239
|
-
authResult?.error || ![0, 1].includes(authResult?.status) || typeof authResult.stdout !== "string" ||
|
|
240
|
-
typeof authResult.stderr !== "string" ||
|
|
241
|
-
Buffer.byteLength(versionResult.stdout) + Buffer.byteLength(versionResult.stderr ?? "") +
|
|
242
|
-
Buffer.byteLength(authResult.stdout) + Buffer.byteLength(authResult.stderr) > 16_384) fail("codex-client-preflight-failed");
|
|
243
|
-
const versionMatch = /(?:codex(?:-cli)?\s+)(\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?)/iu.exec(versionResult.stdout.trim());
|
|
244
|
-
if (!versionMatch) fail("codex-client-version-unknown");
|
|
245
|
-
const status = [authResult.stdout, authResult.stderr].map(output => output.trim()).filter(Boolean).join("\n");
|
|
246
|
-
const auth = status === "Logged in using ChatGPT" ? "chatgpt" :
|
|
247
|
-
status === "Logged in using API key" ? "api-key" : "none";
|
|
248
|
-
return { version: versionMatch[1], auth, env };
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
async function createPreview({ projectRoot, model, effort, prompt, kind, claudeModels, claudeEfforts }) {
|
|
252
|
-
const cwd = await validateProjectRoot(projectRoot, io, home);
|
|
253
|
-
const invocation = await resolveExecutable(dependencies.codexPath, io, sourceEnv);
|
|
254
|
-
const { executable, argsPrefix } = invocation;
|
|
255
|
-
const client = await inspectClient(invocation);
|
|
256
|
-
let scratch;
|
|
257
|
-
try {
|
|
258
|
-
scratch = await io.mkdtemp(path.join(os.tmpdir(), `agent-toolkit-codex-${kind}-`));
|
|
259
|
-
await io.chmod(scratch, 0o700);
|
|
260
|
-
} catch { fail("codex-temporary-output-unavailable"); }
|
|
261
|
-
const outputFile = path.join(scratch, kind === "plan" ? "plan.json" : "review.txt");
|
|
262
|
-
const args = [...argsPrefix, ...codexArgs({ model, effort, cwd, outputFile, schema: kind === "plan" ? PLAN_SCHEMA : null })];
|
|
263
|
-
return Object.freeze({
|
|
264
|
-
previewId: randomBytes(16).toString("hex"),
|
|
265
|
-
confirmationCode: randomBytes(4).toString("hex").toUpperCase(),
|
|
266
|
-
state: client.auth === "chatgpt" ? "ready" : "blocked",
|
|
267
|
-
kind: `codex-${kind}`,
|
|
268
|
-
client: "Codex CLI",
|
|
269
|
-
version: client.version,
|
|
270
|
-
account: accountSummary(client.auth),
|
|
271
|
-
authMethod: client.auth,
|
|
272
|
-
model,
|
|
273
|
-
effort,
|
|
274
|
-
modelAvailabilityVerified: false,
|
|
275
|
-
...(claudeModels ? { claudeModels: [...claudeModels], claudeEfforts: [...claudeEfforts] } : {}),
|
|
276
|
-
command: { executable, args, cwd, shell: false, stdin: prompt, outputFile },
|
|
277
|
-
promptSha256: createHash("sha256").update(prompt, "utf8").digest("hex"),
|
|
278
|
-
promptBytes: Buffer.byteLength(prompt, "utf8"),
|
|
279
|
-
limits: { timeoutMs: RUN_TIMEOUT_MS, outputBytes: MAX_OUTPUT_BYTES, readOnly: true, projectWrite: false }
|
|
280
|
-
});
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
async function preview({ projectRoot, task, model, effort, claudeModels = ["sonnet", "opus", "haiku"], claudeEfforts = ["low", "medium", "high", "xhigh", "max"] }) {
|
|
284
|
-
if (!task || !safeText(task.title, 180, true) || !safeText(task.project, 240, true) || !safeText(task.objective, 4_000, true) ||
|
|
285
|
-
!["tutor", "autonomous"].includes(task.mode) || !safeText(task.scope ?? "", 4_000) ||
|
|
286
|
-
!safeText(task.acceptance ?? "", 4_000) || !safeText(task.checks ?? "", 2_000)) fail("codex-task-invalid");
|
|
287
|
-
model = validateModel(model);
|
|
288
|
-
effort = validateEffort(effort);
|
|
289
|
-
if (!Array.isArray(claudeModels) || claudeModels.length < 1 || claudeModels.length > 12 ||
|
|
290
|
-
claudeModels.some(value => typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/u.test(value)) ||
|
|
291
|
-
!Array.isArray(claudeEfforts) || claudeEfforts.length < 1 || claudeEfforts.length > 5 || claudeEfforts.some(value => !CLAUDE_EFFORTS.has(value))) {
|
|
292
|
-
fail("codex-claude-options-invalid");
|
|
293
|
-
}
|
|
294
|
-
const prompt = planPrompt({ task, modelCandidates: claudeModels, claudeEfforts });
|
|
295
|
-
return createPreview({ projectRoot, model, effort, prompt, kind: "plan", claudeModels, claudeEfforts });
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
async function previewReview({ projectRoot, task, plan, proposal, implementation, model, effort }) {
|
|
299
|
-
if (!task || task.mode !== "autonomous" || task.allowFinalReview !== true ||
|
|
300
|
-
!safeText(task.title, 180, true) || !safeText(task.project, 240, true) || !safeText(task.objective, 4_000, true) ||
|
|
301
|
-
!safeText(task.scope ?? "", 4_000) || !safeText(task.acceptance ?? "", 4_000) || !safeText(task.checks ?? "", 2_000) ||
|
|
302
|
-
!safeText(plan, 32_000, true) || !safeText(proposal, 32_000, true) || !safeText(implementation, 32_000, true)) {
|
|
303
|
-
fail("codex-review-input-invalid");
|
|
304
|
-
}
|
|
305
|
-
model = validateModel(model);
|
|
306
|
-
effort = validateEffort(effort);
|
|
307
|
-
const prompt = reviewPrompt({ task, plan, proposal, implementation });
|
|
308
|
-
return createPreview({ projectRoot, model, effort, prompt, kind: "review" });
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
async function run(preview) {
|
|
312
|
-
if (!preview || preview.client !== "Codex CLI" || preview.state !== "ready" ||
|
|
313
|
-
typeof preview.command?.executable !== "string" || !Array.isArray(preview.command.args) ||
|
|
314
|
-
!["codex-plan", "codex-review"].includes(preview.kind) ||
|
|
315
|
-
typeof preview.command.cwd !== "string" || typeof preview.command.stdin !== "string" || typeof preview.command.outputFile !== "string") fail("codex-preview-invalid");
|
|
316
|
-
const cwd = await validateProjectRoot(preview.command.cwd, io, home);
|
|
317
|
-
if (cwd !== preview.command.cwd) fail("codex-project-root-changed");
|
|
318
|
-
const invocation = await resolveExecutable(dependencies.codexPath, io, sourceEnv);
|
|
319
|
-
const { executable, argsPrefix } = invocation;
|
|
320
|
-
if (executable !== preview.command.executable || argsPrefix.some((arg, index) => preview.command.args[index] !== arg) ||
|
|
321
|
-
(argsPrefix.length === 0 && preview.command.args[0] !== "exec")) fail("codex-client-changed");
|
|
322
|
-
const client = await inspectClient(invocation);
|
|
323
|
-
if (client.auth !== "chatgpt") fail("codex-auth-changed");
|
|
324
|
-
const execute = dependencies.execute ?? runBounded;
|
|
325
|
-
let raw;
|
|
326
|
-
try {
|
|
327
|
-
raw = await execute({
|
|
328
|
-
executable,
|
|
329
|
-
args: [...preview.command.args],
|
|
330
|
-
cwd,
|
|
331
|
-
prompt: preview.command.stdin,
|
|
332
|
-
env: filteredEnvironment(sourceEnv, executable),
|
|
333
|
-
spawn,
|
|
334
|
-
timeoutMs: RUN_TIMEOUT_MS
|
|
335
|
-
});
|
|
336
|
-
if (typeof dependencies.execute === "function" && raw && typeof raw === "object" && typeof raw.stdout === "string") raw = raw.stdout;
|
|
337
|
-
if (typeof raw !== "string" || Buffer.byteLength(raw, "utf8") > MAX_OUTPUT_BYTES) fail("codex-plan-output-invalid");
|
|
338
|
-
let output;
|
|
339
|
-
try { output = await io.readFile(preview.command.outputFile, "utf8"); } catch { output = raw; }
|
|
340
|
-
if (typeof output !== "string" || !output.trim() || Buffer.byteLength(output, "utf8") > MAX_OUTPUT_BYTES) fail("codex-plan-output-invalid");
|
|
341
|
-
if (preview.kind === "codex-plan") return validatePlanOutput(output, preview.claudeModels, preview.claudeEfforts);
|
|
342
|
-
const review = output.trim();
|
|
343
|
-
if (!safeText(review, MAX_OUTPUT_BYTES, true)) fail("codex-review-output-invalid");
|
|
344
|
-
return review;
|
|
345
|
-
} finally {
|
|
346
|
-
const dir = path.dirname(preview.command.outputFile);
|
|
347
|
-
await io.rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
async function cleanup(preview) {
|
|
352
|
-
const outputFile = preview?.command?.outputFile;
|
|
353
|
-
if (typeof outputFile !== "string" || !path.isAbsolute(outputFile)) return;
|
|
354
|
-
await io.rm(path.dirname(outputFile), { recursive: true, force: true }).catch(() => {});
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
return Object.freeze({ preview, previewReview, run, cleanup });
|
|
358
|
-
}
|
package/src/codex-delivery.js
DELETED
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
import { execFile } from "node:child_process";
|
|
2
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
-
import fs from "node:fs/promises";
|
|
4
|
-
import os from "node:os";
|
|
5
|
-
import path from "node:path";
|
|
6
|
-
|
|
7
|
-
// Codex has no background wake-up, so a reviewer that waits costs a model turn per minute. Instead the reviewer
|
|
8
|
-
// registers its session once and ends its turn; after the user approves a review, the principal delivers a short
|
|
9
|
-
// fixed notice to that session with `codex queue`. The MCP stays passive: this is an explicit command.
|
|
10
|
-
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
|
|
11
|
-
const RECENT_MS = 120_000;
|
|
12
|
-
const FRESH_MS = 24 * 3_600_000;
|
|
13
|
-
|
|
14
|
-
export class DeliveryError extends Error {
|
|
15
|
-
constructor(message) { super(message); this.code = "codex-delivery"; }
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
const workflowDirectory = () => path.join(process.env.AGENT_TOOLKIT_WORKFLOW_DIR ?? path.join(os.homedir(), ".agent-toolkit", "workflows"), "reviewers");
|
|
19
|
-
const registryFile = (directory, projectRoot) => path.join(directory, createHash("sha256").update(projectRoot).digest("hex").slice(0, 24) + ".json");
|
|
20
|
-
|
|
21
|
-
async function* rollouts(directory) {
|
|
22
|
-
for (const entry of await fs.readdir(directory, { withFileTypes: true }).catch(() => [])) {
|
|
23
|
-
const full = path.join(directory, entry.name);
|
|
24
|
-
if (entry.isDirectory()) yield* rollouts(full);
|
|
25
|
-
else if (entry.isFile() && entry.name.endsWith(".jsonl")) yield full;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
async function firstLine(file) {
|
|
30
|
-
const handle = await fs.open(file, "r");
|
|
31
|
-
try {
|
|
32
|
-
const buffer = Buffer.alloc(65_536);
|
|
33
|
-
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
34
|
-
return buffer.subarray(0, bytesRead).toString("utf8").split("\n")[0];
|
|
35
|
-
} finally { await handle.close(); }
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// The command runs inside the reviewer's own session, so that session's rollout is the one written to right now.
|
|
39
|
-
export async function findCodexThread({ projectRoot, codexHome = process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex"), now = Date.now } = {}) {
|
|
40
|
-
const candidates = [];
|
|
41
|
-
for await (const file of rollouts(path.join(codexHome, "sessions"))) {
|
|
42
|
-
const stat = await fs.stat(file).catch(() => null);
|
|
43
|
-
if (!stat || now() - stat.mtimeMs > RECENT_MS) continue;
|
|
44
|
-
let meta;
|
|
45
|
-
try { meta = JSON.parse(await firstLine(file))?.payload; } catch { continue; }
|
|
46
|
-
const roots = [meta?.cwd, ...(Array.isArray(meta?.runtime_workspace_roots) ? meta.runtime_workspace_roots : [])];
|
|
47
|
-
if (typeof meta?.id === "string" && UUID.test(meta.id) && roots.includes(projectRoot)) candidates.push(meta.id);
|
|
48
|
-
}
|
|
49
|
-
const unique = [...new Set(candidates)];
|
|
50
|
-
if (unique.length === 1) return unique[0];
|
|
51
|
-
throw new DeliveryError(unique.length
|
|
52
|
-
? `Hay ${unique.length} sesiones de Codex activas en ese proyecto; indica la tuya con --thread <id> (en Codex, /status).`
|
|
53
|
-
: "No encontré tu sesión de Codex (ninguna escribió en los últimos 2 minutos en ese proyecto); indícala con --thread <id> (en Codex, /status).");
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export async function registerReviewer({ projectRoot, thread, directory = workflowDirectory(), ...options }) {
|
|
57
|
-
if (!path.isAbsolute(projectRoot) || path.normalize(projectRoot) !== projectRoot) throw new DeliveryError("La raíz del proyecto debe ser una ruta absoluta.");
|
|
58
|
-
if (thread !== undefined && !UUID.test(thread)) throw new DeliveryError("El id de sesión no es un UUID válido.");
|
|
59
|
-
const id = thread ?? await findCodexThread({ projectRoot, ...options });
|
|
60
|
-
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
61
|
-
const file = registryFile(directory, projectRoot), temporary = `${file}.${randomUUID()}.tmp`;
|
|
62
|
-
try {
|
|
63
|
-
await fs.writeFile(temporary, JSON.stringify({ schemaVersion: 1, agent: "codex", projectRoot, thread: id, registeredAt: new Date().toISOString() }) + "\n", { flag: "wx", mode: 0o600 });
|
|
64
|
-
await fs.rename(temporary, file);
|
|
65
|
-
} finally { await fs.unlink(temporary).catch(() => {}); }
|
|
66
|
-
return { registered: true, thread: id, projectRoot };
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
async function registeredReviewer(directory, projectRoot, now) {
|
|
70
|
-
let record;
|
|
71
|
-
try { record = JSON.parse(await fs.readFile(registryFile(directory, projectRoot), "utf8")); }
|
|
72
|
-
catch { throw new DeliveryError("Codex no se registró como revisor de este proyecto; en su terminal, ejecuta $revisar."); }
|
|
73
|
-
if (record?.schemaVersion !== 1 || record.projectRoot !== projectRoot || !UUID.test(record.thread ?? "")) throw new DeliveryError("El registro del revisor no es válido; ejecuta $revisar otra vez en Codex.");
|
|
74
|
-
if (now() - Date.parse(record.registeredAt) > FRESH_MS) throw new DeliveryError("El registro del revisor tiene más de 24 horas; ejecuta $revisar otra vez en Codex.");
|
|
75
|
-
return record;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
const message = ({ taskId, reviewId, projectRoot }) => [
|
|
79
|
-
`Encargo de revisión pendiente para ti. Colaboración ${taskId}, encargo ${reviewId}, proyecto ${projectRoot}.`,
|
|
80
|
-
"Atiéndelo ahora como revisor: reclámalo con claim_peer_review, revisa solo los archivos que indique y entrega el informe con submit_peer_review.",
|
|
81
|
-
"Si no esperabas este encargo o no tienes esas herramientas, no hagas nada y avísame."].join("\n");
|
|
82
|
-
|
|
83
|
-
const queue = (thread, text) => new Promise((resolve, reject) => {
|
|
84
|
-
execFile("codex", ["queue", "--thread", thread, "--message", text], { timeout: 30_000, windowsHide: true }, (error, stdout) => {
|
|
85
|
-
if (error) reject(new DeliveryError("`codex queue` falló o no está disponible; el encargo sigue pendiente en la bandeja."));
|
|
86
|
-
else resolve(String(stdout));
|
|
87
|
-
});
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
// Delivers one notice for one pending, user-approved review addressed to codex. Nothing else can be sent through here.
|
|
91
|
-
export async function deliverReview({ store, taskId, reviewId, projectRoot, directory = workflowDirectory(), run = queue, now = Date.now }) {
|
|
92
|
-
if (!UUID.test(taskId ?? "") || !UUID.test(reviewId ?? "")) throw new DeliveryError("El taskId y el reviewId deben ser UUID.");
|
|
93
|
-
const task = await store.getCollaboration({ taskId, projectRoot, freshness: false });
|
|
94
|
-
const review = task.reviews.find(item => item.id === reviewId);
|
|
95
|
-
if (task.state !== "open" || !review || review.to !== "codex" || review.state !== "pending") {
|
|
96
|
-
throw new DeliveryError("Solo se avisa de un encargo aprobado, pendiente y dirigido a Codex en una colaboración abierta.");
|
|
97
|
-
}
|
|
98
|
-
const reviewer = await registeredReviewer(directory, task.project.root, now);
|
|
99
|
-
const output = await run(reviewer.thread, message({ taskId, reviewId, projectRoot: task.project.root }));
|
|
100
|
-
return { delivered: true, thread: reviewer.thread, queued: /Queued message ([0-9a-f-]+)/iu.exec(output)?.[1] ?? null };
|
|
101
|
-
}
|
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
import { resolvePackageLock } from './package-lock-path.js';
|
|
2
|
-
import fs from "node:fs/promises";
|
|
3
|
-
import { constants } from "node:fs";
|
|
4
|
-
import path from "node:path";
|
|
5
|
-
import { createHash } from "node:crypto";
|
|
6
|
-
|
|
7
|
-
import {
|
|
8
|
-
createMemoryConnectionDescriptor, copyMemoryConnectionData, freezeMemoryConnectionData,
|
|
9
|
-
memoryConnectionHash, MEMORY_CONNECTION_FACTS, MEMORY_CONNECTION_VERSION
|
|
10
|
-
} from "./memory-connection-descriptor.js";
|
|
11
|
-
|
|
12
|
-
const MIB = 1048576;
|
|
13
|
-
export const MEMORY_CONNECTION_ARTIFACT_LIMITS = Object.freeze({
|
|
14
|
-
nodeBytes: 256 * MIB, smallBytes: MIB / 2, lockBytes: 2 * MIB,
|
|
15
|
-
totalBytes: 260 * MIB, chunkBytes: 65536,
|
|
16
|
-
pathChars: 4096, components: 64, reportBytes: 131072
|
|
17
|
-
});
|
|
18
|
-
export const MEMORY_CONNECTION_ARTIFACT_OPEN_FLAGS = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;
|
|
19
|
-
const HASH_KEYS = ["nodeSha256", "binSha256", "manifestSha256", "packageJsonSha256", "packageLockSha256"];
|
|
20
|
-
class Rejected extends Error {
|
|
21
|
-
constructor(code, state = "blocked") { super(code); this.code = code; this.state = state; }
|
|
22
|
-
}
|
|
23
|
-
const reject = (code, state) => { throw new Rejected(code, state); };
|
|
24
|
-
const errno = (e) => e instanceof Error && typeof e.code === "string" ? e.code : "";
|
|
25
|
-
const within = (root, full) => full === root || full.startsWith(root + "/");
|
|
26
|
-
const fileSignature = (s) => JSON.stringify([s.dev, s.ino, s.uid, s.gid, s.mode, s.nlink, s.size, s.mtimeMs, s.ctimeMs]);
|
|
27
|
-
const dirSignature = (s) => JSON.stringify([s.dev, s.ino, s.uid, s.gid, s.mode]);
|
|
28
|
-
const inode = (s) => JSON.stringify([s.dev, s.ino]);
|
|
29
|
-
|
|
30
|
-
function inputData(input) {
|
|
31
|
-
try {
|
|
32
|
-
const data = copyMemoryConnectionData(input);
|
|
33
|
-
if (!data || Array.isArray(data) || Object.keys(data).length !== 2 ||
|
|
34
|
-
!Object.hasOwn(data, "descriptor") || !Object.hasOwn(data, "expectedHashes")) reject("MC_ARTIFACT_INPUT", "invalid");
|
|
35
|
-
const descriptor = createMemoryConnectionDescriptor(data.descriptor?.identity);
|
|
36
|
-
if (memoryConnectionHash(data.descriptor) !== memoryConnectionHash(descriptor)) reject("MC_ARTIFACT_INPUT", "invalid");
|
|
37
|
-
const hashes = data.expectedHashes;
|
|
38
|
-
if (!hashes || Array.isArray(hashes) || Object.keys(hashes).length !== HASH_KEYS.length ||
|
|
39
|
-
!HASH_KEYS.every(key => Object.hasOwn(hashes, key) && typeof hashes[key] === "string" && /^[a-f0-9]{64}$/.test(hashes[key]))) {
|
|
40
|
-
reject("MC_ARTIFACT_INPUT", "invalid");
|
|
41
|
-
}
|
|
42
|
-
const { toolkitRoot, vaultPath, manifestPath, nodePath } = descriptor.identity;
|
|
43
|
-
if (within(toolkitRoot, vaultPath) || within(vaultPath, toolkitRoot) ||
|
|
44
|
-
!manifestPath.startsWith(vaultPath + "/")) reject("MC_ARTIFACT_INPUT", "invalid");
|
|
45
|
-
const entries = [
|
|
46
|
-
{ key: "nodeSha256", full: nodePath, kind: "node", limit: MEMORY_CONNECTION_ARTIFACT_LIMITS.nodeBytes },
|
|
47
|
-
{ key: "binSha256", full: descriptor.server.args[0], kind: "code", limit: MEMORY_CONNECTION_ARTIFACT_LIMITS.smallBytes },
|
|
48
|
-
{ key: "manifestSha256", full: manifestPath, kind: "manifest", limit: MEMORY_CONNECTION_ARTIFACT_LIMITS.smallBytes },
|
|
49
|
-
{ key: "packageJsonSha256", full: toolkitRoot + "/package.json", kind: "code", limit: MEMORY_CONNECTION_ARTIFACT_LIMITS.smallBytes },
|
|
50
|
-
{ key: "packageLockSha256", full: toolkitRoot + "/package-lock.json", kind: "code", limit: MEMORY_CONNECTION_ARTIFACT_LIMITS.lockBytes }
|
|
51
|
-
];
|
|
52
|
-
for (const entry of entries) {
|
|
53
|
-
if (entry.full.length > MEMORY_CONNECTION_ARTIFACT_LIMITS.pathChars ||
|
|
54
|
-
entry.full.split("/").length - 1 > MEMORY_CONNECTION_ARTIFACT_LIMITS.components ||
|
|
55
|
-
entries.some(other => other !== entry && within(entry.full, other.full))) reject("MC_ARTIFACT_INPUT", "invalid");
|
|
56
|
-
}
|
|
57
|
-
return { descriptor, hashes, entries, roots: [toolkitRoot, vaultPath] };
|
|
58
|
-
} catch { reject("MC_ARTIFACT_INPUT", "invalid"); }
|
|
59
|
-
}
|
|
60
|
-
function safeDir(s, uid, owned) {
|
|
61
|
-
if (!s.isDirectory() || s.isSymbolicLink() || !(s.mode & 0o100)) reject("MC_ARTIFACT_PARENT_UNSAFE");
|
|
62
|
-
if (owned) {
|
|
63
|
-
if (s.uid !== uid || s.mode & 0o7022) reject("MC_ARTIFACT_PARENT_UNSAFE");
|
|
64
|
-
} else {
|
|
65
|
-
const sharedSticky = s.uid === 0 && (s.mode & 0o7777) === 0o1777;
|
|
66
|
-
if (![0, uid].includes(s.uid) || !sharedSticky && s.mode & 0o7022) reject("MC_ARTIFACT_PARENT_UNSAFE");
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
function safeFile(s, entry, uid) {
|
|
70
|
-
if (!s.isFile() || s.isSymbolicLink() || s.nlink !== 1) reject("MC_ARTIFACT_FILE_UNSAFE");
|
|
71
|
-
const mode = s.mode & 0o7777;
|
|
72
|
-
if (entry.kind === "node") {
|
|
73
|
-
if (![0, uid].includes(s.uid) || (mode & 0o500) !== 0o500 || mode & 0o7022) reject("MC_ARTIFACT_FILE_UNSAFE");
|
|
74
|
-
} else if (s.uid !== uid || (entry.kind === "manifest" ? mode !== 0o600 : ![0o600, 0o644].includes(mode))) {
|
|
75
|
-
reject("MC_ARTIFACT_FILE_UNSAFE");
|
|
76
|
-
}
|
|
77
|
-
if (!Number.isSafeInteger(s.size) || s.size < 0 || s.size > entry.limit) reject("MC_ARTIFACT_FILE_LIMIT");
|
|
78
|
-
}
|
|
79
|
-
async function snapshot(io, entry, roots, uid) {
|
|
80
|
-
const parents = []; let current = "/";
|
|
81
|
-
const root = await io.lstat(current); safeDir(root, uid, false);
|
|
82
|
-
parents.push({ path: current, signature: dirSignature(root), inode: inode(root) });
|
|
83
|
-
const parts = entry.full.slice(1).split("/");
|
|
84
|
-
for (const part of parts.slice(0, -1)) {
|
|
85
|
-
current = path.posix.join(current, part); const s = await io.lstat(current);
|
|
86
|
-
safeDir(s, uid, roots.some(owned => within(owned, current)));
|
|
87
|
-
parents.push({ path: current, signature: dirSignature(s), inode: inode(s) });
|
|
88
|
-
}
|
|
89
|
-
const stat = await io.lstat(entry.full); safeFile(stat, entry, uid);
|
|
90
|
-
return { entry, parents, stat };
|
|
91
|
-
}
|
|
92
|
-
async function recheck(io, item, roots, uid) {
|
|
93
|
-
for (const parent of item.parents) {
|
|
94
|
-
let s; try { s = await io.lstat(parent.path); } catch { reject("MC_ARTIFACT_CHANGED"); }
|
|
95
|
-
safeDir(s, uid, roots.some(owned => within(owned, parent.path)));
|
|
96
|
-
if (dirSignature(s) !== parent.signature) reject("MC_ARTIFACT_CHANGED");
|
|
97
|
-
}
|
|
98
|
-
let named;
|
|
99
|
-
try { named = await io.lstat(item.entry.full); } catch { reject("MC_ARTIFACT_CHANGED"); }
|
|
100
|
-
safeFile(named, item.entry, uid);
|
|
101
|
-
if (fileSignature(named) !== fileSignature(item.stat)) reject("MC_ARTIFACT_CHANGED");
|
|
102
|
-
}
|
|
103
|
-
async function recheckAll(io, items, roots, uid) {
|
|
104
|
-
for (const item of items) await recheck(io, item, roots, uid);
|
|
105
|
-
}
|
|
106
|
-
function rejectAliases(items, roots) {
|
|
107
|
-
const files = items.map(item => inode(item.stat));
|
|
108
|
-
if (new Set(files).size !== files.length) reject("MC_ARTIFACT_ALIAS");
|
|
109
|
-
const directories = roots.map(root => items.flatMap(item => item.parents).find(p => p.path === root)?.inode);
|
|
110
|
-
if (directories.some(value => value === undefined) || new Set(directories).size !== directories.length) reject("MC_ARTIFACT_ALIAS");
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* Verify five explicit byte pins, NOT executable semantics, active runtime,
|
|
115
|
-
* manifest/schema validity or installed dependency/import closure. No discovery,
|
|
116
|
-
* candidate execution/import, node_modules enumeration, install or write.
|
|
117
|
-
* Trusted IO doubles are simulations, never native local-read attestations.
|
|
118
|
-
* Rechecks are cooperative observations, not atomic openat or ABA isolation.
|
|
119
|
-
*/
|
|
120
|
-
export async function inspectMemoryConnectionArtifacts(input, dependencies = {}) {
|
|
121
|
-
let data = null, nativeIO = false;
|
|
122
|
-
const budget = { read: 0 };
|
|
123
|
-
const report = (state, details = {}) => {
|
|
124
|
-
const matched = state === "matched";
|
|
125
|
-
const result = {
|
|
126
|
-
schemaVersion: MEMORY_CONNECTION_VERSION, state, hashes: null,
|
|
127
|
-
metadataSha256: null, bytesRead: budget.read, reasons: [], ...details,
|
|
128
|
-
facts: {
|
|
129
|
-
...MEMORY_CONNECTION_FACTS, verificationScope: "base-artifacts-only",
|
|
130
|
-
evidence: matched ? nativeIO ? "local-artifact-files" : "simulated-local-artifacts" : "none",
|
|
131
|
-
artifactPathsVerified: matched && nativeIO, localReadVerified: matched && nativeIO,
|
|
132
|
-
bytePinsMatched: matched, installedDependenciesVerified: false,
|
|
133
|
-
manifestSemanticsVerified: false, runtimeVersionVerified: false,
|
|
134
|
-
runtimeCompatibilityVerified: false, inspectedCandidatesExecuted: false
|
|
135
|
-
}
|
|
136
|
-
};
|
|
137
|
-
if (Buffer.byteLength(JSON.stringify(result)) > MEMORY_CONNECTION_ARTIFACT_LIMITS.reportBytes) reject("MC_ARTIFACT_REPORT_LIMIT");
|
|
138
|
-
return freezeMemoryConnectionData(result);
|
|
139
|
-
};
|
|
140
|
-
try {
|
|
141
|
-
data = inputData(input);
|
|
142
|
-
nativeIO = dependencies.io === undefined;
|
|
143
|
-
const io = dependencies.io ?? fs, uid = process.getuid?.();
|
|
144
|
-
if (!["darwin", "linux"].includes(process.platform) || !Number.isSafeInteger(uid) || constants.O_NOFOLLOW === undefined) reject("MC_ARTIFACT_PLATFORM");
|
|
145
|
-
data.entries.find(entry => entry.key === 'packageLockSha256').full = await resolvePackageLock(data.descriptor.identity.toolkitRoot, io);
|
|
146
|
-
const items = [];
|
|
147
|
-
for (const entry of data.entries) items.push(await snapshot(io, entry, data.roots, uid));
|
|
148
|
-
rejectAliases(items, data.roots);
|
|
149
|
-
if (items.reduce((sum, item) => sum + item.stat.size, 0) > MEMORY_CONNECTION_ARTIFACT_LIMITS.totalBytes) reject("MC_ARTIFACT_TOTAL_LIMIT");
|
|
150
|
-
await recheckAll(io, items, data.roots, uid);
|
|
151
|
-
// One reusable small buffer, not an allocation of a Node binary's size.
|
|
152
|
-
const chunk = Buffer.alloc(MEMORY_CONNECTION_ARTIFACT_LIMITS.chunkBytes), hashes = {};
|
|
153
|
-
for (const item of items) {
|
|
154
|
-
await recheckAll(io, items, data.roots, uid);
|
|
155
|
-
let handle;
|
|
156
|
-
try { handle = await io.open(item.entry.full, MEMORY_CONNECTION_ARTIFACT_OPEN_FLAGS); }
|
|
157
|
-
catch (e) { reject(errno(e) === "ELOOP" ? "MC_ARTIFACT_FILE_UNSAFE" : "MC_ARTIFACT_UNREADABLE"); }
|
|
158
|
-
const hash = createHash("sha256");
|
|
159
|
-
try {
|
|
160
|
-
const opened = await handle.stat(); safeFile(opened, item.entry, uid);
|
|
161
|
-
if (fileSignature(opened) !== fileSignature(item.stat)) reject("MC_ARTIFACT_CHANGED");
|
|
162
|
-
await recheck(io, item, data.roots, uid);
|
|
163
|
-
let offset = 0;
|
|
164
|
-
while (offset < item.stat.size) {
|
|
165
|
-
const request = Math.min(chunk.length, item.stat.size - offset, MEMORY_CONNECTION_ARTIFACT_LIMITS.totalBytes - budget.read);
|
|
166
|
-
if (request <= 0) reject("MC_ARTIFACT_TOTAL_LIMIT");
|
|
167
|
-
const { bytesRead } = await handle.read(chunk, 0, request, offset);
|
|
168
|
-
if (!Number.isSafeInteger(bytesRead) || bytesRead < 0 || bytesRead > request) reject("MC_ARTIFACT_READ");
|
|
169
|
-
budget.read += bytesRead; // Retained even if metadata/pin/hash later fails.
|
|
170
|
-
if (!bytesRead) reject("MC_ARTIFACT_CHANGED");
|
|
171
|
-
offset += bytesRead; hash.update(chunk.subarray(0, bytesRead));
|
|
172
|
-
}
|
|
173
|
-
const after = await handle.stat(); safeFile(after, item.entry, uid);
|
|
174
|
-
if (fileSignature(after) !== fileSignature(item.stat)) reject("MC_ARTIFACT_CHANGED");
|
|
175
|
-
await recheck(io, item, data.roots, uid);
|
|
176
|
-
} finally {
|
|
177
|
-
try { await handle.close(); } catch { reject("MC_ARTIFACT_CLOSE"); }
|
|
178
|
-
}
|
|
179
|
-
await recheck(io, item, data.roots, uid);
|
|
180
|
-
const value = hash.digest("hex");
|
|
181
|
-
if (value !== data.hashes[item.entry.key]) reject("MC_ARTIFACT_PIN_MISMATCH");
|
|
182
|
-
hashes[item.entry.key] = value;
|
|
183
|
-
}
|
|
184
|
-
await recheckAll(io, items, data.roots, uid);
|
|
185
|
-
const metadataSha256 = createHash("sha256").update(JSON.stringify(items.map(item => ({
|
|
186
|
-
role: item.entry.key, path: item.entry.full, parents: item.parents, signature: fileSignature(item.stat)
|
|
187
|
-
})))).digest("hex");
|
|
188
|
-
return report("matched", { hashes, metadataSha256, reasons: ["MC_ARTIFACT_MATCH"] });
|
|
189
|
-
} catch (e) {
|
|
190
|
-
return report(e instanceof Rejected ? e.state : "blocked", { reasons: [e instanceof Rejected ? e.code : "MC_ARTIFACT_IO"] });
|
|
191
|
-
}
|
|
192
|
-
}
|